2022-07-28 14:25:42 +00:00
|
|
|
package dialect
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"sync"
|
2023-02-27 21:36:43 +00:00
|
|
|
"time"
|
2022-07-28 14:25:42 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
Dialects map[string]interface{} `mapstructure:",remain"`
|
|
|
|
Dialect Matcher
|
|
|
|
}
|
|
|
|
|
|
|
|
type Dialect struct {
|
|
|
|
Matcher Matcher
|
|
|
|
Config Connector
|
|
|
|
IsDefault bool
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
dialects []*Dialect
|
|
|
|
defaultDialect *Dialect
|
|
|
|
dialectsMu sync.Mutex
|
|
|
|
)
|
|
|
|
|
|
|
|
type Matcher interface {
|
|
|
|
MatchName(string) bool
|
|
|
|
Decode([]interface{}) (Connector, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Connector interface {
|
|
|
|
Connect(useAdmin bool) (*sql.DB, error)
|
2023-02-27 21:36:43 +00:00
|
|
|
Password() string
|
|
|
|
Database
|
|
|
|
}
|
|
|
|
|
|
|
|
type Database interface {
|
2022-07-28 14:25:42 +00:00
|
|
|
DatabaseName() string
|
|
|
|
Username() string
|
|
|
|
Type() string
|
2023-02-27 21:36:43 +00:00
|
|
|
Timetravel(time.Duration) string
|
2022-07-28 14:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Register(matcher Matcher, config Connector, isDefault bool) {
|
|
|
|
dialectsMu.Lock()
|
|
|
|
defer dialectsMu.Unlock()
|
|
|
|
|
|
|
|
d := &Dialect{Matcher: matcher, Config: config}
|
|
|
|
|
|
|
|
if isDefault {
|
|
|
|
defaultDialect = d
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
dialects = append(dialects, d)
|
|
|
|
}
|
|
|
|
|
|
|
|
func SelectByConfig(config map[string]interface{}) *Dialect {
|
|
|
|
for key := range config {
|
|
|
|
for _, d := range dialects {
|
|
|
|
if d.Matcher.MatchName(key) {
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return defaultDialect
|
|
|
|
}
|