feat: add VectorStore entity, repository, and migrations
Introduce the VectorStore domain model as a foundation for multi-store vector DB architecture (Phase 1, PR 1/4). - VectorStore entity with ConnectionConfig (AES-GCM encrypted) and IndexConfig - VectorStoreRepository interface and GORM implementation (CRUD + duplicate check) - PostgreSQL migration (000031) and SQLite migration (000001) - Unit tests for types, encryption, validation, and helpers
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// vectorStoreRepository implements the VectorStoreRepository interface
|
||||
type vectorStoreRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewVectorStoreRepository creates a new vector store repository
|
||||
func NewVectorStoreRepository(db *gorm.DB) interfaces.VectorStoreRepository {
|
||||
return &vectorStoreRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new vector store
|
||||
func (r *vectorStoreRepository) Create(ctx context.Context, store *types.VectorStore) error {
|
||||
return r.db.WithContext(ctx).Create(store).Error
|
||||
}
|
||||
|
||||
// GetByID retrieves a vector store by ID within a tenant scope.
|
||||
// Returns (nil, nil) when the record is not found (not an error).
|
||||
func (r *vectorStoreRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.VectorStore, error) {
|
||||
var store types.VectorStore
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"id = ? AND tenant_id = ?", id, tenantID,
|
||||
).First(&store).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &store, nil
|
||||
}
|
||||
|
||||
// List lists all vector stores for a tenant (newest first)
|
||||
func (r *vectorStoreRepository) List(ctx context.Context, tenantID uint64) ([]*types.VectorStore, error) {
|
||||
var stores []*types.VectorStore
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"tenant_id = ?", tenantID,
|
||||
).Order("created_at DESC").Find(&stores).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stores, nil
|
||||
}
|
||||
|
||||
// Update updates a vector store (only mutable fields: name).
|
||||
// engine_type, connection_config, index_config are immutable and excluded via Select.
|
||||
// updated_at is handled by the DB trigger, so it is not included in Select.
|
||||
func (r *vectorStoreRepository) Update(ctx context.Context, store *types.VectorStore) error {
|
||||
return r.db.WithContext(ctx).Model(&types.VectorStore{}).Where(
|
||||
"id = ? AND tenant_id = ?", store.ID, store.TenantID,
|
||||
).Select("name").Updates(store).Error
|
||||
}
|
||||
|
||||
// Delete soft-deletes a vector store
|
||||
func (r *vectorStoreRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).Where(
|
||||
"id = ? AND tenant_id = ?", id, tenantID,
|
||||
).Delete(&types.VectorStore{}).Error
|
||||
}
|
||||
|
||||
// ExistsByEndpointAndIndex checks if a store with the same endpoint and index already exists.
|
||||
// Comparison is done at the application level because JSONB field extraction syntax
|
||||
// differs between PostgreSQL and SQLite, and the row count is small (a few per tenant).
|
||||
func (r *vectorStoreRepository) ExistsByEndpointAndIndex(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
engineType types.RetrieverEngineType,
|
||||
endpoint string,
|
||||
indexName string,
|
||||
) (bool, error) {
|
||||
var stores []*types.VectorStore
|
||||
if err := r.db.WithContext(ctx).Where(
|
||||
"tenant_id = ? AND engine_type = ?", tenantID, string(engineType),
|
||||
).Find(&stores).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, s := range stores {
|
||||
if s.ConnectionConfig.GetEndpoint() == endpoint &&
|
||||
s.IndexConfig.GetIndexNameOrDefault(engineType) == indexName {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// VectorStoreRepository defines the repository interface for VectorStore CRUD.
|
||||
type VectorStoreRepository interface {
|
||||
// Create creates a new vector store
|
||||
Create(ctx context.Context, store *types.VectorStore) error
|
||||
// GetByID retrieves a vector store by ID within a tenant scope
|
||||
GetByID(ctx context.Context, tenantID uint64, id string) (*types.VectorStore, error)
|
||||
// List lists all vector stores for a tenant
|
||||
List(ctx context.Context, tenantID uint64) ([]*types.VectorStore, error)
|
||||
// Update updates a vector store (only mutable fields: name)
|
||||
Update(ctx context.Context, store *types.VectorStore) error
|
||||
// Delete soft-deletes a vector store
|
||||
Delete(ctx context.Context, tenantID uint64, id string) error
|
||||
// ExistsByEndpointAndIndex checks if a store with the same endpoint and index already exists
|
||||
ExistsByEndpointAndIndex(ctx context.Context, tenantID uint64, engineType types.RetrieverEngineType, endpoint string, indexName string) (bool, error)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// VectorStore represents a configured vector database instance for a tenant.
|
||||
// Each tenant can register multiple VectorStore entries (even of the same engine type)
|
||||
// to support multi-store scenarios (e.g., ES-hot + ES-warm clusters).
|
||||
type VectorStore struct {
|
||||
// Unique identifier (UUID, auto-generated)
|
||||
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Tenant ID for scoping
|
||||
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
|
||||
// User-friendly name, e.g., "elasticsearch-hot"
|
||||
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
|
||||
// Engine type: postgres, elasticsearch, qdrant, milvus, weaviate, sqlite
|
||||
EngineType RetrieverEngineType `yaml:"engine_type" json:"engine_type" gorm:"type:varchar(50);not null"`
|
||||
// Driver-specific connection parameters (sensitive fields encrypted with AES-GCM)
|
||||
ConnectionConfig ConnectionConfig `yaml:"connection_config" json:"connection_config" gorm:"type:json"`
|
||||
// Optional index/collection configuration (engine-specific defaults if empty)
|
||||
IndexConfig IndexConfig `yaml:"index_config" json:"index_config" gorm:"type:json"`
|
||||
// Timestamps
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for VectorStore
|
||||
func (VectorStore) TableName() string {
|
||||
return "vector_stores"
|
||||
}
|
||||
|
||||
// BeforeCreate is a GORM hook that runs before creating a new record.
|
||||
// Automatically generates a UUID for new vector stores.
|
||||
func (v *VectorStore) BeforeCreate(tx *gorm.DB) error {
|
||||
if v.ID == "" {
|
||||
v.ID = uuid.New().String()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validEngineTypes defines the engine types that can be registered as VectorStore.
|
||||
// InfinityRetrieverEngineType and ElasticFaissRetrieverEngineType are legacy/experimental
|
||||
// types that do not have standalone deployable instances, so they are excluded.
|
||||
var validEngineTypes = map[RetrieverEngineType]bool{
|
||||
PostgresRetrieverEngineType: true,
|
||||
ElasticsearchRetrieverEngineType: true,
|
||||
QdrantRetrieverEngineType: true,
|
||||
MilvusRetrieverEngineType: true,
|
||||
WeaviateRetrieverEngineType: true,
|
||||
SQLiteRetrieverEngineType: true,
|
||||
}
|
||||
|
||||
// IsValidEngineType checks whether the given engine type is valid for VectorStore.
|
||||
func IsValidEngineType(t RetrieverEngineType) bool {
|
||||
return validEngineTypes[t]
|
||||
}
|
||||
|
||||
// Validate checks required fields and engine type validity.
|
||||
func (v *VectorStore) Validate() error {
|
||||
if v.Name == "" {
|
||||
return errors.NewValidationError("name is required")
|
||||
}
|
||||
if !validEngineTypes[v.EngineType] {
|
||||
return errors.NewValidationError(fmt.Sprintf("unsupported engine type: %s", v.EngineType))
|
||||
}
|
||||
if v.TenantID == 0 {
|
||||
return errors.NewValidationError("tenant_id is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ConnectionConfig
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ConnectionConfig holds driver-specific connection parameters.
|
||||
// Sensitive fields (Password, APIKey) are encrypted with AES-GCM at rest.
|
||||
type ConnectionConfig struct {
|
||||
// Common
|
||||
Addr string `yaml:"addr" json:"addr,omitempty"`
|
||||
Username string `yaml:"username" json:"username,omitempty"`
|
||||
Password string `yaml:"password" json:"password,omitempty"` // AES-GCM encrypted
|
||||
APIKey string `yaml:"api_key" json:"api_key,omitempty"` // AES-GCM encrypted
|
||||
// Qdrant
|
||||
Host string `yaml:"host" json:"host,omitempty"`
|
||||
Port int `yaml:"port" json:"port,omitempty"`
|
||||
UseTLS bool `yaml:"use_tls" json:"use_tls,omitempty"`
|
||||
// Weaviate
|
||||
GrpcAddress string `yaml:"grpc_address" json:"grpc_address,omitempty"`
|
||||
Scheme string `yaml:"scheme" json:"scheme,omitempty"`
|
||||
// Postgres
|
||||
UseDefaultConnection bool `yaml:"use_default_connection" json:"use_default_connection,omitempty"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
// Encrypts Password and APIKey before persisting to database.
|
||||
func (c ConnectionConfig) Value() (driver.Value, error) {
|
||||
if key := utils.GetAESKey(); key != nil {
|
||||
if c.Password != "" {
|
||||
if encrypted, err := utils.EncryptAESGCM(c.Password, key); err == nil {
|
||||
c.Password = encrypted
|
||||
}
|
||||
}
|
||||
if c.APIKey != "" {
|
||||
if encrypted, err := utils.EncryptAESGCM(c.APIKey, key); err == nil {
|
||||
c.APIKey = encrypted
|
||||
}
|
||||
}
|
||||
}
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
// Decrypts Password and APIKey after loading from database.
|
||||
func (c *ConnectionConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(b, c); err != nil {
|
||||
return err
|
||||
}
|
||||
if key := utils.GetAESKey(); key != nil {
|
||||
if c.Password != "" {
|
||||
if decrypted, err := utils.DecryptAESGCM(c.Password, key); err == nil {
|
||||
c.Password = decrypted
|
||||
}
|
||||
}
|
||||
if c.APIKey != "" {
|
||||
if decrypted, err := utils.DecryptAESGCM(c.APIKey, key); err == nil {
|
||||
c.APIKey = decrypted
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetEndpoint returns a normalized endpoint string for duplicate detection.
|
||||
func (c ConnectionConfig) GetEndpoint() string {
|
||||
if c.Addr != "" {
|
||||
return c.Addr
|
||||
}
|
||||
if c.Host != "" {
|
||||
port := c.Port
|
||||
if port == 0 {
|
||||
port = 6334 // Qdrant default port
|
||||
}
|
||||
return fmt.Sprintf("%s:%d", c.Host, port)
|
||||
}
|
||||
if c.UseDefaultConnection {
|
||||
return "__default_postgres__"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// MaskSensitiveFields returns a copy with Password and APIKey masked.
|
||||
func (c ConnectionConfig) MaskSensitiveFields() ConnectionConfig {
|
||||
masked := c
|
||||
if masked.Password != "" {
|
||||
masked.Password = "***"
|
||||
}
|
||||
if masked.APIKey != "" {
|
||||
masked.APIKey = "***"
|
||||
}
|
||||
return masked
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IndexConfig
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// IndexConfig holds optional index/collection configuration for the vector store.
|
||||
// If empty, engine-specific defaults are used.
|
||||
type IndexConfig struct {
|
||||
IndexName string `yaml:"index_name" json:"index_name,omitempty"` // ES, OpenSearch
|
||||
NumberOfShards int `yaml:"number_of_shards" json:"number_of_shards,omitempty"` // ES, OpenSearch
|
||||
NumberOfReplicas int `yaml:"number_of_replicas" json:"number_of_replicas,omitempty"` // ES, OpenSearch
|
||||
CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant
|
||||
CollectionName string `yaml:"collection_name" json:"collection_name,omitempty"` // Milvus
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (c IndexConfig) Value() (driver.Value, error) {
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (c *IndexConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// GetIndexNameOrDefault returns the effective index/collection name,
|
||||
// falling back to engine-specific defaults when the user has not specified one.
|
||||
func (c IndexConfig) GetIndexNameOrDefault(engineType RetrieverEngineType) string {
|
||||
switch engineType {
|
||||
case ElasticsearchRetrieverEngineType:
|
||||
if c.IndexName != "" {
|
||||
return c.IndexName
|
||||
}
|
||||
return "xwrag_default"
|
||||
case QdrantRetrieverEngineType:
|
||||
if c.CollectionPrefix != "" {
|
||||
return c.CollectionPrefix
|
||||
}
|
||||
return "weknora_embeddings"
|
||||
case MilvusRetrieverEngineType:
|
||||
if c.CollectionName != "" {
|
||||
return c.CollectionName
|
||||
}
|
||||
return "weknora_embeddings"
|
||||
case WeaviateRetrieverEngineType:
|
||||
if c.CollectionPrefix != "" {
|
||||
return c.CollectionPrefix
|
||||
}
|
||||
return "WeKnora"
|
||||
default:
|
||||
return c.IndexName
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// testAESKey is a 32-byte key for testing AES-GCM encryption.
|
||||
const testAESKey = "01234567890123456789012345678901"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// VectorStore
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestVectorStore_Validate(t *testing.T) {
|
||||
valid := VectorStore{
|
||||
Name: "test-store",
|
||||
EngineType: PostgresRetrieverEngineType,
|
||||
TenantID: 1,
|
||||
}
|
||||
|
||||
t.Run("valid input returns nil", func(t *testing.T) {
|
||||
assert.NoError(t, valid.Validate())
|
||||
})
|
||||
|
||||
t.Run("empty name returns error", func(t *testing.T) {
|
||||
s := valid
|
||||
s.Name = ""
|
||||
err := s.Validate()
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "name is required")
|
||||
})
|
||||
|
||||
t.Run("unsupported engine type returns error", func(t *testing.T) {
|
||||
s := valid
|
||||
s.EngineType = "unknown"
|
||||
err := s.Validate()
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "unsupported engine type")
|
||||
})
|
||||
|
||||
t.Run("zero tenant_id returns error", func(t *testing.T) {
|
||||
s := valid
|
||||
s.TenantID = 0
|
||||
err := s.Validate()
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "tenant_id is required")
|
||||
})
|
||||
}
|
||||
|
||||
func TestVectorStore_BeforeCreate(t *testing.T) {
|
||||
t.Run("generates UUID when ID is empty", func(t *testing.T) {
|
||||
v := &VectorStore{}
|
||||
err := v.BeforeCreate(&gorm.DB{})
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, v.ID)
|
||||
assert.Len(t, v.ID, 36) // UUID format: 8-4-4-4-12
|
||||
})
|
||||
|
||||
t.Run("preserves existing ID", func(t *testing.T) {
|
||||
v := &VectorStore{ID: "existing-id"}
|
||||
err := v.BeforeCreate(&gorm.DB{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "existing-id", v.ID)
|
||||
})
|
||||
}
|
||||
|
||||
func TestVectorStore_TableName(t *testing.T) {
|
||||
assert.Equal(t, "vector_stores", VectorStore{}.TableName())
|
||||
}
|
||||
|
||||
func TestIsValidEngineType(t *testing.T) {
|
||||
validTypes := []RetrieverEngineType{
|
||||
PostgresRetrieverEngineType,
|
||||
ElasticsearchRetrieverEngineType,
|
||||
QdrantRetrieverEngineType,
|
||||
MilvusRetrieverEngineType,
|
||||
WeaviateRetrieverEngineType,
|
||||
SQLiteRetrieverEngineType,
|
||||
}
|
||||
for _, et := range validTypes {
|
||||
t.Run("valid: "+string(et), func(t *testing.T) {
|
||||
assert.True(t, IsValidEngineType(et))
|
||||
})
|
||||
}
|
||||
|
||||
invalidTypes := []RetrieverEngineType{
|
||||
"unknown",
|
||||
"opensearch",
|
||||
"",
|
||||
InfinityRetrieverEngineType,
|
||||
ElasticFaissRetrieverEngineType,
|
||||
}
|
||||
for _, et := range invalidTypes {
|
||||
name := string(et)
|
||||
if name == "" {
|
||||
name = "(empty)"
|
||||
}
|
||||
t.Run("invalid: "+name, func(t *testing.T) {
|
||||
assert.False(t, IsValidEngineType(et))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ConnectionConfig
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestConnectionConfig_ValueScan(t *testing.T) {
|
||||
t.Run("encrypts password and api_key on Value, decrypts on Scan", func(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", testAESKey)
|
||||
|
||||
original := ConnectionConfig{
|
||||
Addr: "http://es:9200",
|
||||
Username: "elastic",
|
||||
Password: "secret-pass",
|
||||
APIKey: "sk-api-key",
|
||||
}
|
||||
|
||||
// Value — encrypt
|
||||
raw, err := original.Value()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify the serialized JSON has encrypted fields
|
||||
var intermediate map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(raw.([]byte), &intermediate))
|
||||
assert.True(t, strings.HasPrefix(intermediate["password"].(string), "enc:v1:"))
|
||||
assert.True(t, strings.HasPrefix(intermediate["api_key"].(string), "enc:v1:"))
|
||||
// Non-sensitive fields remain plaintext
|
||||
assert.Equal(t, "http://es:9200", intermediate["addr"])
|
||||
assert.Equal(t, "elastic", intermediate["username"])
|
||||
|
||||
// Scan — decrypt
|
||||
var scanned ConnectionConfig
|
||||
err = scanned.Scan(raw.([]byte))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-pass", scanned.Password)
|
||||
assert.Equal(t, "sk-api-key", scanned.APIKey)
|
||||
assert.Equal(t, "http://es:9200", scanned.Addr)
|
||||
assert.Equal(t, "elastic", scanned.Username)
|
||||
})
|
||||
|
||||
t.Run("skips encryption when fields are empty", func(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", testAESKey)
|
||||
|
||||
original := ConnectionConfig{Addr: "http://es:9200"}
|
||||
raw, err := original.Value()
|
||||
require.NoError(t, err)
|
||||
|
||||
var intermediate map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(raw.([]byte), &intermediate))
|
||||
_, hasPassword := intermediate["password"]
|
||||
_, hasAPIKey := intermediate["api_key"]
|
||||
assert.False(t, hasPassword)
|
||||
assert.False(t, hasAPIKey)
|
||||
})
|
||||
|
||||
t.Run("skips encryption when AES key is not set", func(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", "")
|
||||
|
||||
original := ConnectionConfig{
|
||||
Password: "secret-pass",
|
||||
APIKey: "sk-api-key",
|
||||
}
|
||||
raw, err := original.Value()
|
||||
require.NoError(t, err)
|
||||
|
||||
var intermediate map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(raw.([]byte), &intermediate))
|
||||
assert.Equal(t, "secret-pass", intermediate["password"])
|
||||
assert.Equal(t, "sk-api-key", intermediate["api_key"])
|
||||
})
|
||||
|
||||
t.Run("does not double-encrypt already encrypted values", func(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", testAESKey)
|
||||
|
||||
original := ConnectionConfig{Password: "secret-pass"}
|
||||
raw1, err := original.Value()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Scan to get the encrypted form, then re-serialize
|
||||
var scanned ConnectionConfig
|
||||
require.NoError(t, json.Unmarshal(raw1.([]byte), &scanned))
|
||||
// scanned.Password is now "enc:v1:..."
|
||||
raw2, err := scanned.Value()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Both serialized forms should produce the same decrypted result
|
||||
var result ConnectionConfig
|
||||
require.NoError(t, result.Scan(raw2.([]byte)))
|
||||
assert.Equal(t, "secret-pass", result.Password)
|
||||
})
|
||||
|
||||
t.Run("Scan nil value returns no error", func(t *testing.T) {
|
||||
var c ConnectionConfig
|
||||
assert.NoError(t, c.Scan(nil))
|
||||
})
|
||||
|
||||
t.Run("Scan non-byte value returns no error", func(t *testing.T) {
|
||||
var c ConnectionConfig
|
||||
assert.NoError(t, c.Scan(42))
|
||||
})
|
||||
|
||||
t.Run("original struct is not mutated by Value", func(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", testAESKey)
|
||||
|
||||
original := ConnectionConfig{Password: "secret-pass"}
|
||||
_, err := original.Value()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-pass", original.Password, "value receiver should not mutate original")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConnectionConfig_GetEndpoint(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
config ConnectionConfig
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "returns Addr when set",
|
||||
config: ConnectionConfig{Addr: "http://es:9200"},
|
||||
expected: "http://es:9200",
|
||||
},
|
||||
{
|
||||
name: "returns host:port when Host and Port set",
|
||||
config: ConnectionConfig{Host: "qdrant-prod", Port: 6334},
|
||||
expected: "qdrant-prod:6334",
|
||||
},
|
||||
{
|
||||
name: "defaults Port to 6334 when Host set and Port is 0",
|
||||
config: ConnectionConfig{Host: "qdrant-prod"},
|
||||
expected: "qdrant-prod:6334",
|
||||
},
|
||||
{
|
||||
name: "returns sentinel for default postgres connection",
|
||||
config: ConnectionConfig{UseDefaultConnection: true},
|
||||
expected: "__default_postgres__",
|
||||
},
|
||||
{
|
||||
name: "returns empty string when nothing is set",
|
||||
config: ConnectionConfig{},
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
name: "Addr takes precedence over Host",
|
||||
config: ConnectionConfig{Addr: "http://es:9200", Host: "qdrant"},
|
||||
expected: "http://es:9200",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.expected, tt.config.GetEndpoint())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionConfig_MaskSensitiveFields(t *testing.T) {
|
||||
t.Run("masks password and api_key", func(t *testing.T) {
|
||||
c := ConnectionConfig{
|
||||
Addr: "http://es:9200",
|
||||
Username: "elastic",
|
||||
Password: "secret-pass",
|
||||
APIKey: "sk-api-key",
|
||||
}
|
||||
masked := c.MaskSensitiveFields()
|
||||
assert.Equal(t, "***", masked.Password)
|
||||
assert.Equal(t, "***", masked.APIKey)
|
||||
assert.Equal(t, "http://es:9200", masked.Addr)
|
||||
assert.Equal(t, "elastic", masked.Username)
|
||||
})
|
||||
|
||||
t.Run("does not mask empty fields", func(t *testing.T) {
|
||||
c := ConnectionConfig{Addr: "http://es:9200"}
|
||||
masked := c.MaskSensitiveFields()
|
||||
assert.Empty(t, masked.Password)
|
||||
assert.Empty(t, masked.APIKey)
|
||||
})
|
||||
|
||||
t.Run("does not mutate original", func(t *testing.T) {
|
||||
c := ConnectionConfig{Password: "secret-pass", APIKey: "sk-api-key"}
|
||||
_ = c.MaskSensitiveFields()
|
||||
assert.Equal(t, "secret-pass", c.Password)
|
||||
assert.Equal(t, "sk-api-key", c.APIKey)
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IndexConfig
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestIndexConfig_ValueScan(t *testing.T) {
|
||||
t.Run("round-trip serialization", func(t *testing.T) {
|
||||
original := IndexConfig{
|
||||
IndexName: "my_index",
|
||||
NumberOfShards: 3,
|
||||
NumberOfReplicas: 1,
|
||||
}
|
||||
raw, err := original.Value()
|
||||
require.NoError(t, err)
|
||||
|
||||
var scanned IndexConfig
|
||||
require.NoError(t, scanned.Scan(raw.([]byte)))
|
||||
assert.Equal(t, original, scanned)
|
||||
})
|
||||
|
||||
t.Run("empty config serializes to {}", func(t *testing.T) {
|
||||
raw, err := IndexConfig{}.Value()
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{}`, string(raw.([]byte)))
|
||||
})
|
||||
|
||||
t.Run("Scan nil value returns no error", func(t *testing.T) {
|
||||
var c IndexConfig
|
||||
assert.NoError(t, c.Scan(nil))
|
||||
})
|
||||
|
||||
t.Run("Scan non-byte value returns no error", func(t *testing.T) {
|
||||
var c IndexConfig
|
||||
assert.NoError(t, c.Scan(42))
|
||||
})
|
||||
}
|
||||
|
||||
func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
config IndexConfig
|
||||
engineType RetrieverEngineType
|
||||
expected string
|
||||
}{
|
||||
// Elasticsearch
|
||||
{
|
||||
name: "elasticsearch with custom index",
|
||||
config: IndexConfig{IndexName: "custom_index"},
|
||||
engineType: ElasticsearchRetrieverEngineType,
|
||||
expected: "custom_index",
|
||||
},
|
||||
{
|
||||
name: "elasticsearch default",
|
||||
config: IndexConfig{},
|
||||
engineType: ElasticsearchRetrieverEngineType,
|
||||
expected: "xwrag_default",
|
||||
},
|
||||
// Qdrant
|
||||
{
|
||||
name: "qdrant with custom collection prefix",
|
||||
config: IndexConfig{CollectionPrefix: "custom_embeddings"},
|
||||
engineType: QdrantRetrieverEngineType,
|
||||
expected: "custom_embeddings",
|
||||
},
|
||||
{
|
||||
name: "qdrant default",
|
||||
config: IndexConfig{},
|
||||
engineType: QdrantRetrieverEngineType,
|
||||
expected: "weknora_embeddings",
|
||||
},
|
||||
// Milvus
|
||||
{
|
||||
name: "milvus with custom collection name",
|
||||
config: IndexConfig{CollectionName: "custom_collection"},
|
||||
engineType: MilvusRetrieverEngineType,
|
||||
expected: "custom_collection",
|
||||
},
|
||||
{
|
||||
name: "milvus default",
|
||||
config: IndexConfig{},
|
||||
engineType: MilvusRetrieverEngineType,
|
||||
expected: "weknora_embeddings",
|
||||
},
|
||||
// Weaviate
|
||||
{
|
||||
name: "weaviate with custom prefix",
|
||||
config: IndexConfig{CollectionPrefix: "Custom"},
|
||||
engineType: WeaviateRetrieverEngineType,
|
||||
expected: "Custom",
|
||||
},
|
||||
{
|
||||
name: "weaviate default",
|
||||
config: IndexConfig{},
|
||||
engineType: WeaviateRetrieverEngineType,
|
||||
expected: "WeKnora",
|
||||
},
|
||||
// Postgres (no index config)
|
||||
{
|
||||
name: "postgres returns empty (no index config)",
|
||||
config: IndexConfig{},
|
||||
engineType: PostgresRetrieverEngineType,
|
||||
expected: "",
|
||||
},
|
||||
// SQLite (no index config)
|
||||
{
|
||||
name: "sqlite returns empty (no index config)",
|
||||
config: IndexConfig{},
|
||||
engineType: SQLiteRetrieverEngineType,
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.expected, tt.config.GetIndexNameOrDefault(tt.engineType))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS vector_stores;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Migration: 000032_vector_stores
|
||||
-- Description: Create vector_stores table for tenant-specific vector database configurations
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000032] Creating vector_stores table'; END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS vector_stores (
|
||||
id VARCHAR(36) NOT NULL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
engine_type VARCHAR(50) NOT NULL,
|
||||
connection_config JSONB NOT NULL DEFAULT '{}',
|
||||
index_config JSONB NOT NULL DEFAULT '{}',
|
||||
tenant_id BIGINT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP NULL
|
||||
);
|
||||
|
||||
-- Name uniqueness per tenant (excluding soft-deleted rows)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_vector_stores_name_tenant
|
||||
ON vector_stores(name, tenant_id)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_vector_stores_tenant_id ON vector_stores(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_vector_stores_engine_type ON vector_stores(engine_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_vector_stores_deleted_at ON vector_stores(deleted_at);
|
||||
|
||||
-- Note: updated_at is managed by GORM hooks, no database trigger needed.
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000032] vector_stores table created successfully'; END $$;
|
||||
Reference in New Issue
Block a user