forked from go-courier/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
90 lines (72 loc) · 1.87 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package sqlx
import (
"database/sql"
"database/sql/driver"
"fmt"
"os"
"github.com/kunlun-qilian/sqlx/v3/builder"
)
func NewFeatureDatabase(name string) *Database {
if projectFeature, exists := os.LookupEnv("PROJECT_FEATURE"); exists && projectFeature != "" {
name = name + "__" + projectFeature
}
return NewDatabase(name)
}
func NewDatabase(name string) *Database {
return &Database{
Name: name,
Tables: builder.Tables{},
}
}
type Database struct {
Name string
Schema string
Tables builder.Tables
}
func (database Database) WithSchema(schema string) *Database {
database.Schema = schema
tables := builder.Tables{}
database.Tables.Range(func(tab *builder.Table, idx int) {
tables.Add(tab.WithSchema(database.Schema))
})
database.Tables = tables
return &database
}
type DBNameBinder interface {
WithDBName(dbName string) driver.Connector
}
func (database *Database) OpenDB(connector driver.Connector) *DB {
if dbNameBinder, ok := connector.(DBNameBinder); ok {
connector = dbNameBinder.WithDBName(database.Name)
}
dialect, ok := connector.(builder.Dialect)
if !ok {
panic(fmt.Errorf("connector should implement builder.Dialect"))
}
return &DB{
Database: database,
dialect: dialect,
SqlExecutor: sql.OpenDB(connector),
}
}
func (database *Database) AddTable(table *builder.Table) {
database.Tables.Add(table)
}
func (database *Database) Register(model builder.Model) *builder.Table {
table := builder.TableFromModel(model)
table.Schema = database.Schema
database.AddTable(table)
return table
}
func (database *Database) Table(tableName string) *builder.Table {
return database.Tables.Table(tableName)
}
func (database *Database) T(model builder.Model) *builder.Table {
if td, ok := model.(builder.TableDefinition); ok {
return td.T()
}
if t, ok := model.(*builder.Table); ok {
return t
}
return database.Table(model.TableName())
}