|
1 | 1 | package state |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "fmt" |
4 | 5 | "log" |
5 | 6 | "os" |
6 | 7 | "time" |
7 | 8 |
|
| 9 | + "github.com/dipdup-net/go-lib/config" |
8 | 10 | "github.com/pkg/errors" |
9 | | - "gorm.io/driver/clickhouse" |
10 | 11 | "gorm.io/driver/mysql" |
11 | 12 | "gorm.io/driver/postgres" |
12 | 13 | "gorm.io/driver/sqlite" |
13 | | - "gorm.io/driver/sqlserver" |
14 | 14 | "gorm.io/gorm" |
15 | 15 | "gorm.io/gorm/logger" |
16 | 16 | ) |
17 | 17 |
|
18 | | -// Supported database kinds |
19 | | -const ( |
20 | | - DBKindSqlite = "sqlite" |
21 | | - DBKindPostgres = "postgres" |
22 | | - DBKindMysql = "mysql" |
23 | | - DBKindClickHouse = "clickhouse" |
24 | | - DBKindSqlServer = "sqlserver" |
25 | | -) |
26 | | - |
27 | 18 | // OpenConnection - |
28 | | -func OpenConnection(kind, path string) (*gorm.DB, error) { |
| 19 | +func OpenConnection(cfg config.Database) (*gorm.DB, error) { |
29 | 20 | var dialector gorm.Dialector |
30 | | - switch kind { |
31 | | - case DBKindSqlite: |
32 | | - dialector = sqlite.Open(path) |
33 | | - case DBKindPostgres: |
34 | | - dialector = postgres.Open(path) |
35 | | - case DBKindMysql: |
36 | | - dialector = mysql.Open(path) |
37 | | - case DBKindClickHouse: |
38 | | - dialector = clickhouse.Open(path) |
39 | | - case DBKindSqlServer: |
40 | | - dialector = sqlserver.Open(path) |
| 21 | + switch cfg.Kind { |
| 22 | + case config.DBKindSqlite: |
| 23 | + dialector = sqlite.Open(cfg.Path) |
| 24 | + case config.DBKindPostgres: |
| 25 | + connString := fmt.Sprintf( |
| 26 | + "host=%s user=%s password=%s dbname=%s port=%d", |
| 27 | + cfg.Host, cfg.User, cfg.Password, cfg.Database, cfg.Port, |
| 28 | + ) |
| 29 | + dialector = postgres.Open(connString) |
| 30 | + case config.DBKindMysql: |
| 31 | + connString := fmt.Sprintf( |
| 32 | + "%s:%s@tcp(%s:%d)/%s", |
| 33 | + cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database, |
| 34 | + ) |
| 35 | + dialector = mysql.Open(connString) |
41 | 36 | default: |
42 | | - return nil, errors.Errorf("Unsupported database %s", kind) |
| 37 | + return nil, errors.Errorf("Unsupported database kind %s", cfg.Kind) |
43 | 38 | } |
44 | 39 |
|
45 | 40 | return gorm.Open(dialector, &gorm.Config{ |
|
0 commit comments