fix(knowledge): default custom metadata on create

main
wizardchen 2026-07-28 22:19:26 +08:00 committed by lyingbug
parent b581094c7b
commit 2358564bde
3 changed files with 50 additions and 3 deletions

View File

@ -0,0 +1,40 @@
package repository
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestCreateKnowledgeDefaultsCustomMetadataToEmptyObject(t *testing.T) {
dsn := "file:" + uuid.New().String() + "?mode=memory&cache=shared"
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1)
t.Cleanup(func() { _ = sqlDB.Close() })
require.NoError(t, db.AutoMigrate(&types.Knowledge{}))
repo := NewKnowledgeRepository(db)
knowledge := &types.Knowledge{
TenantID: 1,
KnowledgeBaseID: "kb-1",
Type: "file",
Title: "document.txt",
ParseStatus: types.ParseStatusPending,
EnableStatus: "disabled",
}
require.NoError(t, repo.CreateKnowledge(context.Background(), knowledge))
require.JSONEq(t, `{}`, string(knowledge.CustomMetadata))
persisted, err := repo.GetKnowledgeByID(context.Background(), knowledge.TenantID, knowledge.ID)
require.NoError(t, err)
require.JSONEq(t, `{}`, string(persisted.CustomMetadata))
}

View File

@ -158,7 +158,7 @@ type Knowledge struct {
Metadata JSON `json:"metadata" gorm:"type:json"`
// CustomMetadata is user-authored descriptive metadata. It is deliberately
// separate from Metadata, which contains internal ingestion state and IDs.
CustomMetadata JSON `json:"custom_metadata" gorm:"type:json"`
CustomMetadata JSON `json:"custom_metadata" gorm:"type:json;not null"`
// Last FAQ import result (for FAQ type knowledge only)
LastFAQImportResult JSON `json:"last_faq_import_result" gorm:"type:json"`
// Creation time of the knowledge
@ -220,11 +220,18 @@ func (k *Knowledge) GetMetadata() map[string]string {
return metadata
}
// BeforeCreate hook generates a UUID for new Knowledge entities before they are created.
// BeforeCreate initializes required defaults for new Knowledge entities.
func (k *Knowledge) BeforeCreate(tx *gorm.DB) (err error) {
if k.ID == "" {
k.ID = uuid.New().String()
}
// JSON.Value returns SQL NULL for an empty value. PostgreSQL's column
// default is not applied when GORM explicitly inserts that NULL, so keep the
// application-side representation aligned with the NOT NULL database
// invariant for every knowledge creation path.
if len(k.CustomMetadata) == 0 {
k.CustomMetadata = JSON(`{}`)
}
return nil
}

View File

@ -77,7 +77,7 @@ CREATE TABLE knowledges (
file_hash VARCHAR(64),
storage_size BIGINT NOT NULL DEFAULT 0,
metadata JSON,
custom_metadata JSON,
custom_metadata JSON NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,