Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(repository): SearchUsers 兼容 SQLite 方言并转义 LIKE 通配符 (#3996)
Winoren00a07efcec53
diff --git a/internal/application/repository/user.go b/internal/application/repository/user.goindex 6965245fe..ec474e3fd 100644--- a/internal/application/repository/user.go+++ b/internal/application/repository/user.go@@ -362,10 +362,22 @@ func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorID// SearchUsers searches users by username or emailfunc (r *userRepository) SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error) {var users []*types.User- searchPattern := "%" + query + "%"+ // Dialect-aware bits so the same query works on Postgres and SQLite (Lite+ // build), which has no ILIKE. The keyword is escaped either way: % and _+ // are LIKE wildcards, so an unescaped search for "a_b" also matches "axb"+ // and "%" returns every user.+ isPostgres := r.db.Name() == "postgres"+ userLike := "LOWER(username) LIKE LOWER(?) ESCAPE ?"+ mailLike := "LOWER(email) LIKE LOWER(?) ESCAPE ?"+ if isPostgres {+ userLike = "username ILIKE ? ESCAPE ?"+ mailLike = "email ILIKE ? ESCAPE ?"+ }+ escaped := escapeLikeKeyword(query)+ searchPattern := "%" + escaped + "%"dbQuery := r.db.WithContext(ctx).- Where("username ILIKE ? OR email ILIKE ?", searchPattern, searchPattern).+ Where(userLike+" OR "+mailLike, searchPattern, likeEscapeChar, searchPattern, likeEscapeChar).Where("is_active = ?", true).Order("username ASC")diff --git a/internal/application/repository/user_tenantless_test.go b/internal/application/repository/user_tenantless_test.goindex f08b80d8e..0ffa0401b 100644--- a/internal/application/repository/user_tenantless_test.go+++ b/internal/application/repository/user_tenantless_test.go@@ -2,6 +2,7 @@ package repositoryimport ("context"+ "slices""testing""github.com/Tencent/WeKnora/internal/types"@@ -57,3 +58,64 @@ func assertNullTenantID(t *testing.T, db *gorm.DB, userID string) {t.Fatalf("tenant_id for user %s is not NULL", userID)}}++// TestUserRepositorySearchUsersEscapesLikeWildcards covers the two rules every+// other keyword filter in this package follows: the predicate has to parse on+// SQLite (the Lite driver), which has no ILIKE, and the keyword must not be+// handed to LIKE as a pattern. Without escaping, searching "a_b" also returns+// "axb" and searching "%" returns every user.+func TestUserRepositorySearchUsersEscapesLikeWildcards(t *testing.T) {+ db, err := gorm.Open(sqlite.Open("file:user_searchwildcard?mode=memory&cache=shared"), &gorm.Config{})+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ if err := db.AutoMigrate(&types.User{}); err != nil {+ t.Fatalf("migrate: %v", err)+ }++ repo := NewUserRepository(db)+ for _, u := range []*types.User{+ {ID: "u-underscore", Username: "a_b", Email: "[email protected]", PasswordHash: "h", IsActive: true},+ {ID: "u-anychar", Username: "axb", Email: "[email protected]", PasswordHash: "h", IsActive: true},+ {ID: "u-alice", Username: "alice", Email: "[email protected]", PasswordHash: "h", IsActive: true},+ {ID: "u-percent", Username: "pct%user", Email: "pct%[email protected]", PasswordHash: "h", IsActive: true},+ } {+ if err := repo.CreateUser(context.Background(), u); err != nil {+ t.Fatalf("CreateUser %s: %v", u.Username, err)+ }+ }++ usernames := func(users []*types.User) []string {+ got := make([]string, 0, len(users))+ for _, u := range users {+ got = append(got, u.Username)+ }+ return got+ }++ tests := []struct {+ name string+ want []string+ }{+ // "_" is a single-character wildcard in LIKE, so the unescaped form+ // would also match "axb".+ {"a_b", []string{"a_b"}},+ // "%" alone would otherwise match every user in the table; escaping it+ // still finds the user whose name really contains a percent.+ {"%", []string{"pct%user"}},+ // A keyword with no metacharacters must still match, and SQLite's LIKE+ // folds ASCII case on its own.+ {"ALICE", []string{"alice"}},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := repo.SearchUsers(context.Background(), tt.name, 100)+ if err != nil {+ t.Fatalf("SearchUsers(%q): %v", tt.name, err)+ }+ if g := usernames(got); !slices.Equal(g, tt.want) {+ t.Fatalf("SearchUsers(%q) = %v, want %v", tt.name, g, tt.want)+ }+ })+ }+}