From f35c21196122433b56de1758a8303ae62415d0f5 Mon Sep 17 00:00:00 2001 From: tiglog Date: Tue, 22 Aug 2023 17:33:43 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E5=8F=AF=E6=A0=B9=E6=8D=AE=20driver?= =?UTF-8?q?=20=E8=87=AA=E5=8A=A8=E8=AE=BE=E7=BD=AE=20Dialect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gdb/orm/orm.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/gdb/orm/orm.go b/gdb/orm/orm.go index aca135b..9dee1bb 100644 --- a/gdb/orm/orm.go +++ b/gdb/orm/orm.go @@ -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)