chore: 可根据 driver 自动设置 Dialect

This commit is contained in:
tiglog 2023-08-22 17:33:43 +08:00
parent 37f3df120d
commit f35c211961

View File

@ -38,6 +38,9 @@ type ConnectionConfig struct {
// just remember that having a connection name is mandatory if
// you have multiple connections
Name string
// 不是必需,不指定 Dialect 时必需
Driver string
// If you already have an active database connection configured pass it in this value and
// do not pass Driver and DSN fields.
DB *sql.DB
@ -77,6 +80,18 @@ func NewDb(opt DbOption) (*sql.DB, error) {
return db, nil
}
func getDialectByDriver(driver string) (*Dialect, error) {
switch driver {
case "postgres":
return Dialects.PostgreSQL, nil
case "mysql":
return Dialects.MySQL, nil
case "sqlite3":
return Dialects.SQLite3, nil
}
return nil, fmt.Errorf("unsupported db driver %s", driver)
}
// SetupConnections declares a new connections for ORM.
func SetupConnections(configs ...ConnectionConfig) error {
@ -132,6 +147,13 @@ func setupConnection(config ConnectionConfig) error {
if config.Name == "" {
config.Name = "default"
}
if config.Dialect == nil {
dialect, err := getDialectByDriver(config.Driver)
if err != nil {
return err
}
config.Dialect = dialect
}
for _, entity := range config.Entities {
s := schemaOfHeavyReflectionStuff(entity)