Files
ai-agent/internal/bootstrap/db_test.go
T

80 lines
2.3 KiB
Go
Raw Normal View History

2026-04-09 10:01:23 +08:00
package bootstrap
import (
"testing"
"code.tczkiot.com/wlw/ai-agent/internal/models"
"code.tczkiot.com/wlw/ai-agent/internal/pkg/config"
"github.com/glebarez/sqlite"
"github.com/mlogclub/simple/sqls"
"gorm.io/gorm"
"gorm.io/gorm/schema"
2026-04-09 10:01:23 +08:00
)
func TestNewDialector(t *testing.T) {
t.Parallel()
cases := []struct {
dbType string
want string
}{
{dbType: "postgres", want: "postgres"},
{dbType: "postgresql", want: "postgres"},
{dbType: " PostgreSQL ", want: "postgres"},
}
for _, tt := range cases {
t.Run(tt.dbType, func(t *testing.T) {
t.Parallel()
dialector, err := newDialector(config.DBConfig{Type: tt.dbType, DSN: "postgres-dsn"})
if err != nil {
t.Fatalf("newDialector() error = %v", err)
}
if got := dialector.Name(); got != tt.want {
t.Fatalf("dialector.Name() = %q, want %q", got, tt.want)
}
})
}
}
func TestNewDialectorRejectsRemovedAndUnsupportedTypes(t *testing.T) {
t.Parallel()
for _, dbType := range []string{"sqlite", "mysql", "oracle", ""} {
if _, err := newDialector(config.DBConfig{Type: dbType}); err == nil {
t.Fatalf("newDialector(%q) error = nil, want unsupported type error", dbType)
}
}
}
func TestUseDatabaseSharesConnectionWithoutChangingHostNaming(t *testing.T) {
// SQLite remains only as a lightweight in-memory unit-test fixture. Runtime
// database initialization accepts PostgreSQL exclusively.
host, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
NamingStrategy: schema.NamingStrategy{TablePrefix: "iot_"},
})
if err != nil {
t.Fatalf("gorm.Open() error = %v", err)
2026-04-09 10:01:23 +08:00
}
hostTable := host.NamingStrategy.TableName("Conversation")
2026-04-09 10:01:23 +08:00
if err := UseDatabase(host, "iot_ai_"); err != nil {
t.Fatalf("UseDatabase() error = %v", err)
2026-04-09 10:01:23 +08:00
}
moduleDB := sqls.DB()
statement := &gorm.Statement{DB: moduleDB}
if err := statement.Parse(&models.Conversation{}); err != nil {
t.Fatalf("Statement.Parse() error = %v", err)
2026-04-09 10:01:23 +08:00
}
if statement.Schema.Table != "iot_ai_conversation" {
t.Fatalf("module table=%q want iot_ai_conversation", statement.Schema.Table)
}
if got := host.NamingStrategy.TableName("Conversation"); got != hostTable {
t.Fatalf("host table changed from %q to %q", hostTable, got)
}
if moduleDB.ConnPool != host.ConnPool {
t.Fatal("module database does not share the host connection pool")
2026-04-09 10:01:23 +08:00
}
}