-
Notifications
You must be signed in to change notification settings - Fork 1
/
zdb_postgres.go
53 lines (42 loc) · 1.11 KB
/
zdb_postgres.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
package sql
import (
"database/sql"
"fmt"
"github.com/jeckbjy/gsk/orm/driver"
)
// docker中启动: docker run -p 5432:5432 --name pg -e POSTGRES_PASSWORD=123456 -d postgres
// 驱动:https://github.com/lib/pq
type postgresDB struct {
baseDB
}
func (d *postgresDB) Name() string {
return "postgres"
}
func (d *postgresDB) Clone() Engine {
return &postgresDB{}
}
func (d *postgresDB) Current() (string, error) {
row := d.db.QueryRow("select current_database()")
var name sql.NullString
if err := row.Scan(&name); err != nil {
return "", err
}
return name.String, nil
}
func (d *postgresDB) CreateDatabase(name string) error {
// https://notathoughtexperiment.me/blog/how-to-do-create-database-dbname-if-not-exists-in-postgres-in-golang/
query := fmt.Sprintf("SELECT EXISTS(SELECT datname FROM pg_catalog.pg_database WHERE datname = '%s');", name)
row := d.db.QueryRow(query)
var exists bool
err := row.Scan(&exists)
if err != nil {
return err
}
if !exists {
return d.Exec("CREATE DATABASE " + name)
}
return nil
}
func (d *postgresDB) Indexes(table string) ([]*driver.Index, error) {
return nil, nil
}