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" ) 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) } hostTable := host.NamingStrategy.TableName("Conversation") if err := UseDatabase(host, "iot_ai_"); err != nil { t.Fatalf("UseDatabase() error = %v", err) } moduleDB := sqls.DB() statement := &gorm.Statement{DB: moduleDB} if err := statement.Parse(&models.Conversation{}); err != nil { t.Fatalf("Statement.Parse() error = %v", err) } 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") } }