-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
75 lines (66 loc) · 1.58 KB
/
db.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
package charts
import (
"context"
"database/sql"
"fmt"
"github.com/GuiaBolso/darwin"
"github.com/opencensus-integrations/ocsql"
// Needed to talk to postgres
_ "github.com/lib/pq"
)
var (
db *sql.DB
driver = "postgres"
migrations = []darwin.Migration{
{
Version: 1,
Description: "Creating table graphs",
Script: `
CREATE TABLE graphs (
id text primary key,
description text,
creator_id text,
data jsonb,
type text,
created_at timestamp with time zone,
modified_at timestamp with time zone
);
`,
},
{
Version: 2,
Description: "Create users",
Script: `
CREATE EXTENSION pgcrypto;
CREATE TABLE users(
id text primary key,
role text,
apikey UUID DEFAULT gen_random_uuid(),
created_at timestamp with time zone,
modified_at timestamp with time zone
);
`,
},
}
)
// InitDB creates a package global db connection from a database string.
func InitDB(dataSourceName string) (*sql.DB, error) {
var err error
// Connect to Database
wrappedDriver, err := ocsql.Register(driver, ocsql.WithAllTraceOptions())
if err != nil {
return nil, fmt.Errorf("Failed to register the ocsql driver: %v", err)
}
db, _ = sql.Open(wrappedDriver, dataSourceName)
if err = db.PingContext(context.Background()); err != nil {
return nil, err
}
// Migrate
driver := darwin.NewGenericDriver(db, darwin.PostgresDialect{})
d := darwin.New(driver, migrations, nil)
err = d.Migrate()
if err != nil {
return nil, err
}
return db, err
}