From 9aa5624872d3a4138c92afeb376cb79578b6ccec Mon Sep 17 00:00:00 2001 From: floss4good Date: Tue, 1 Apr 2025 01:41:32 +0300 Subject: [PATCH] use sync.OnceValue when building the list with UserData column names --- models/user/moderation.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/models/user/moderation.go b/models/user/moderation.go index 81a0c86610..b1c1d42767 100644 --- a/models/user/moderation.go +++ b/models/user/moderation.go @@ -7,6 +7,7 @@ import ( "context" "reflect" "slices" + "sync" "forgejo.org/models/moderation" "forgejo.org/modules/json" @@ -56,6 +57,18 @@ func newUserData(user *User) UserData { } } +// userDataColumnNames builds (only once) and returns a slice with the column names +// (e.g. FieldName -> field_name) corresponding to UserData struct fields. +var userDataColumnNames = sync.OnceValue(func() []string { + mapper := new(names.GonicMapper) + udType := reflect.TypeOf(UserData{}) + columnNames := make([]string, 0, udType.NumField()) + for i := 0; i < udType.NumField(); i++ { + columnNames = append(columnNames, mapper.Obj2Table(udType.Field(i).Name)) + } + return columnNames +}) + // IfNeededCreateShadowCopyForUser checks if for the given user there are any reports of abusive content submitted // and if found a shadow copy of relevant user fields will be stored into DB and linked to the above report(s). // This function should be called when a user is deleted or updated. @@ -70,13 +83,7 @@ func IfNeededCreateShadowCopyForUser(ctx context.Context, user *User, alteredCol shouldCheckIfReported := len(alteredCols) == 0 // no columns being updated, therefore a deletion if !shouldCheckIfReported { // for updates we need to go further only if certain column are being changed - mapper := new(names.GonicMapper) - ucType := reflect.TypeOf(UserData{}) - - for i := 0; i < ucType.NumField(); i++ { - field := ucType.Field(i) - // get the corresponding column name for a field name (e.g. FieldName -> field_name). - colName := mapper.Obj2Table(field.Name) + for _, colName := range userDataColumnNames() { if shouldCheckIfReported = slices.Contains(alteredCols, colName); shouldCheckIfReported { break }