db/connection_factory.go
2023-04-12 15:58:25 +08:00

46 lines
886 B
Go

package db
import (
"errors"
"fmt"
)
const (
DriverMysql = "mysql"
DriverSqlite3 = "sqlite3"
)
type ConnectionFactory struct {
}
type Connector interface {
connect(config *DBConfig) *Connection
}
func (f ConnectionFactory) Make(config *DBConfig) *Connection {
return f.MakeConnection(config)
}
func (f ConnectionFactory) MakeConnection(config *DBConfig) *Connection {
return f.CreateConnection(config)
}
func (f ConnectionFactory) CreateConnection(config *DBConfig) *Connection {
switch config.Driver {
case DriverMysql:
connector := MysqlConnector{}
conn := connector.connect(config)
return conn
case DriverSqlite3:
connector := SqliteConnector{}
conn := connector.connect(config)
return conn
case "":
panic(errors.New("a driver must be specified"))
default:
panic(errors.New(fmt.Sprintf("unsupported driver:%s", config.Driver)))
}
return nil
}