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(sqlite): support organization and wiki searches (#4698)
杰尼龟236d796147e7
diff --git a/internal/application/repository/organization.go b/internal/application/repository/organization.goindex 43c105f8a..d51cf54c7 100644--- a/internal/application/repository/organization.go+++ b/internal/application/repository/organization.go@@ -91,9 +91,21 @@ func (r *organizationRepository) ListSearchable(ctx context.Context, query strinvar orgs []*types.Organizationq := r.db.WithContext(ctx).Where("searchable = ?", true)if query != "" {- pattern := "%" + query + "%"+ pattern := "%" + escapeLikeKeyword(query) + "%"// 支持按名称、描述或空间 ID 搜索,便于区分同名空间- q = q.Where("name ILIKE ? OR description ILIKE ? OR id::text ILIKE ?", pattern, pattern, pattern)+ if r.db.Name() == "sqlite" {+ q = q.Where(+ "LOWER(name) LIKE LOWER(?) ESCAPE ? OR "++ "LOWER(description) LIKE LOWER(?) ESCAPE ? OR "++ "LOWER(CAST(id AS TEXT)) LIKE LOWER(?) ESCAPE ?",+ pattern, likeEscapeChar, pattern, likeEscapeChar, pattern, likeEscapeChar,+ )+ } else {+ q = q.Where(+ "name ILIKE ? ESCAPE ? OR description ILIKE ? ESCAPE ? OR id::text ILIKE ? ESCAPE ?",+ pattern, likeEscapeChar, pattern, likeEscapeChar, pattern, likeEscapeChar,+ )+ }}err := q.Order("created_at DESC").Limit(limit).Find(&orgs).Errorif err != nil {@@ -357,13 +369,17 @@ func (r *organizationRepository) CountJoinRequests(ctx context.Context, orgID st// UpdateJoinRequestStatus updates the status of a join requestfunc (r *organizationRepository) UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error {+ reviewedAt := gorm.Expr("NOW()")+ if r.db.Name() == "sqlite" {+ reviewedAt = gorm.Expr("CURRENT_TIMESTAMP")+ }return r.db.WithContext(ctx).Model(&types.OrganizationJoinRequest{}).Where("id = ?", id).Updates(map[string]interface{}{"status": status,"reviewed_by": reviewedBy,- "reviewed_at": gorm.Expr("NOW()"),+ "reviewed_at": reviewedAt,"review_message": reviewMessage,}).Error}diff --git a/internal/application/repository/organization_sqlite_test.go b/internal/application/repository/organization_sqlite_test.gonew file mode 100644index 000000000..e9fc6c20b--- /dev/null+++ b/internal/application/repository/organization_sqlite_test.go@@ -0,0 +1,89 @@+package repository++import (+ "context"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"+)++func setupOrganizationSQLiteTestDB(t *testing.T) *gorm.DB {+ t.Helper()+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.Exec(`+CREATE TABLE organizations (+ id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, owner_id TEXT NOT NULL,+ owner_tenant_id INTEGER NOT NULL DEFAULT 0, invite_code TEXT,+ require_approval BOOLEAN DEFAULT 0, invite_code_expires_at DATETIME,+ invite_code_validity_days INTEGER NOT NULL DEFAULT 7, avatar TEXT DEFAULT '',+ searchable BOOLEAN NOT NULL DEFAULT 0, member_limit INTEGER NOT NULL DEFAULT 50,+ created_at DATETIME, updated_at DATETIME, deleted_at DATETIME+);+CREATE TABLE organization_join_requests (+ id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, user_id TEXT NOT NULL,+ tenant_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending',+ requested_role TEXT NOT NULL DEFAULT 'viewer', request_type TEXT NOT NULL DEFAULT 'join',+ prev_role TEXT, message TEXT, reviewed_by TEXT, reviewed_at DATETIME,+ review_message TEXT, created_at DATETIME, updated_at DATETIME+);`).Error)+ return db+}++func TestListSearchableSQLiteSupportsCaseInsensitiveIDAndEscapedSearch(t *testing.T) {+ db := setupOrganizationSQLiteTestDB(t)+ repo := &organizationRepository{db: db}+ ctx := context.Background()+ orgs := []*types.Organization{+ {+ ID: "org-alpha", Name: "Data Platform", Description: "Shared search space", OwnerID: "owner",+ Searchable: true,+ },+ {ID: "org-beta", Name: "A_B testing", Description: "Literal wildcard", OwnerID: "owner", Searchable: true},+ {ID: "org-hidden", Name: "Data Platform", Description: "Hidden", OwnerID: "owner", Searchable: false},+ }+ for _, org := range orgs {+ require.NoError(t, repo.Create(ctx, org))+ }++ for _, tc := range []struct {+ query string+ ids []string+ }{+ {query: "data", ids: []string{"org-alpha"}},+ {query: "ORG-ALP", ids: []string{"org-alpha"}},+ {query: "A_B", ids: []string{"org-beta"}},+ {query: "%", ids: nil},+ } {+ got, err := repo.ListSearchable(ctx, tc.query, 20)+ require.NoError(t, err, tc.query)+ var gotIDs []string+ for _, org := range got {+ gotIDs = append(gotIDs, org.ID)+ }+ assert.Equal(t, tc.ids, gotIDs, tc.query)+ }+}++func TestUpdateJoinRequestStatusSQLiteSetsReviewedAt(t *testing.T) {+ db := setupOrganizationSQLiteTestDB(t)+ repo := &organizationRepository{db: db}+ ctx := context.Background()+ require.NoError(t, db.Exec(`INSERT INTO organization_join_requests+ (id, organization_id, user_id, tenant_id, status, requested_role, request_type)+ VALUES ('req-1', 'org-1', 'user-1', 1, 'pending', 'viewer', 'join')`).Error)++ require.NoError(t, repo.UpdateJoinRequestStatus(+ ctx, "req-1", types.JoinRequestStatusApproved, "reviewer", "welcome",+ ))+ var request types.OrganizationJoinRequest+ require.NoError(t, db.First(&request, "id = ?", "req-1").Error)+ assert.Equal(t, types.JoinRequestStatusApproved, request.Status)+ assert.Equal(t, "reviewer", request.ReviewedBy)+ assert.Equal(t, "welcome", request.ReviewMessage)+ assert.NotNil(t, request.ReviewedAt)+}diff --git a/internal/application/repository/wiki_page.go b/internal/application/repository/wiki_page.goindex 953c52ec7..68c80c216 100644--- a/internal/application/repository/wiki_page.go+++ b/internal/application/repository/wiki_page.go@@ -367,12 +367,25 @@ func (r *wikiPageRepository) List(ctx context.Context, req *types.WikiPageListRequery = query.Where("status = ?", req.Status)}if req.Query != "" {- // Use PostgreSQL full-text search + ILIKE for aliases- query = query.Where(- "(to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(content, '')) @@ plainto_tsquery('simple', ?) OR aliases::text ILIKE ?)",- req.Query,- "%"+req.Query+"%",- )+ pattern := "%" + escapeLikeKeyword(req.Query) + "%"+ if r.wikiDialect() == "sqlite" {+ // SQLite does not provide PostgreSQL's full-text functions or casts.+ // Search the same user-visible fields with a case-insensitive LIKE.+ query = query.Where(+ "(LOWER(COALESCE(title, '')) LIKE LOWER(?) ESCAPE ? OR "++ "LOWER(COALESCE(content, '')) LIKE LOWER(?) ESCAPE ? OR "++ "LOWER(CAST(aliases AS TEXT)) LIKE LOWER(?) ESCAPE ?)",+ pattern, likeEscapeChar, pattern, likeEscapeChar, pattern, likeEscapeChar,+ )+ } else {+ // Use PostgreSQL full-text search + ILIKE for aliases.+ query = query.Where(+ "(to_tsvector('simple', coalesce(title, '') || ' ' || "++ "coalesce(content, '')) @@ plainto_tsquery('simple', ?) OR "++ "aliases::text ILIKE ? ESCAPE ?)",+ req.Query, pattern, likeEscapeChar,+ )+ }}// Directory filters are pushed to SQL so the DB does the counting and// pagination instead of loading every page of the type into memory. `depth`diff --git a/internal/application/repository/wiki_page_test.go b/internal/application/repository/wiki_page_test.goindex c3681e60b..449e2e320 100644--- a/internal/application/repository/wiki_page_test.go+++ b/internal/application/repository/wiki_page_test.go@@ -243,6 +243,47 @@ func TestList_CategoryPathFilterMatchesOnSQLite(t *testing.T) {assert.Equal(t, "entity/in-people", got[0].Slug)}+func TestList_QuerySearchesSQLiteTextFieldsAndEscapesWildcards(t *testing.T) {+ db := setupWikiPagesTestDB(t)+ repo := NewWikiPageRepository(db)+ ctx := context.Background()++ title := makeWikiPage("kb-search", "entity/title", types.WikiPageTypeEntity, types.WikiPageStatusPublished)+ title.Title = "SQLite Search Guide"+ content := makeWikiPage("kb-search", "entity/content", types.WikiPageTypeEntity, types.WikiPageStatusPublished)+ content.Title = "Content page"+ content.Content = "The important phrase is stored in CONTENT."+ alias := makeWikiPage("kb-search", "entity/alias", types.WikiPageTypeEntity, types.WikiPageStatusPublished)+ alias.Title = "Alias page"+ alias.Aliases = types.StringArray{"SQLiteAlias"}+ wildcard := makeWikiPage("kb-search", "entity/wildcard", types.WikiPageTypeEntity, types.WikiPageStatusPublished)+ wildcard.Title = "literal_%_token"+ for _, page := range []*types.WikiPage{title, content, alias, wildcard} {+ require.NoError(t, repo.Create(ctx, page))+ }++ for _, tc := range []struct {+ query string+ slug string+ }{+ {query: "search guide", slug: "entity/title"},+ {query: "important phrase", slug: "entity/content"},+ {query: "sqlitealias", slug: "entity/alias"},+ {query: "literal_%", slug: "entity/wildcard"},+ } {+ pages, total, err := repo.List(ctx, &types.WikiPageListRequest{+ KnowledgeBaseID: "kb-search",+ Query: tc.query,+ Page: 1,+ PageSize: 10,+ })+ require.NoError(t, err)+ assert.Equal(t, int64(1), total, tc.query)+ require.Len(t, pages, 1, tc.query)+ assert.Equal(t, tc.slug, pages[0].Slug, tc.query)+ }+}+// TestFolderTree_CRUDAndChildListing exercises the wiki_folders repository:// child listing ordered by sort_order/name, find-by-name, page counting under// a folder, and that ListDistinctCategoryPaths reflects the folder paths.