-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
postgres.go
191 lines (166 loc) · 4.34 KB
/
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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Package postgres wraps postgres (pq) driver as an adapter for REL.
//
// Deprecated: Please use github.com/go-rel/postgres instead.
//
// Usage:
// // open postgres connection.
// adapter, err := postgres.Open("postgres://postgres@localhost/rel_test?sslmode=disable")
// if err != nil {
// panic(err)
// }
// defer adapter.Close()
//
// // initialize REL's repo.
// repo := rel.New(adapter)
package postgres
import (
"context"
db "database/sql"
"time"
"github.com/go-rel/rel"
"github.com/go-rel/rel/adapter/sql"
)
// Adapter definition for postgres database.
type Adapter struct {
*sql.Adapter
}
var (
_ rel.Adapter = (*Adapter)(nil)
// Config for postgres adapter.
Config = sql.Config{
Placeholder: "$",
EscapeChar: "\"",
Ordinal: true,
InsertDefaultValues: true,
ErrorFunc: errorFunc,
MapColumnFunc: mapColumnFunc,
}
)
// New postgres adapter using existing connection.
//
// Deprecated: Please use github.com/go-rel/postgres instead.
func New(database *db.DB) *Adapter {
return &Adapter{
Adapter: &sql.Adapter{
Config: Config,
DB: database,
},
}
}
// Open postgres connection using dsn.
func Open(dsn string) (*Adapter, error) {
var database, err = db.Open("postgres", dsn)
return New(database), err
}
// Insert inserts a record to database and returns its id.
func (adapter *Adapter) Insert(ctx context.Context, query rel.Query, primaryField string, mutates map[string]rel.Mutate) (interface{}, error) {
var (
id int64
statement, args = sql.NewBuilder(adapter.Config).Returning(primaryField).Insert(query.Table, mutates)
rows, err = adapter.query(ctx, statement, args)
)
if err == nil && rows.Next() {
defer rows.Close()
rows.Scan(&id)
}
return id, err
}
// InsertAll inserts multiple records to database and returns its ids.
func (adapter *Adapter) InsertAll(ctx context.Context, query rel.Query, primaryField string, fields []string, bulkMutates []map[string]rel.Mutate) ([]interface{}, error) {
var (
ids []interface{}
statement, args = sql.NewBuilder(adapter.Config).Returning(primaryField).InsertAll(query.Table, fields, bulkMutates)
rows, err = adapter.query(ctx, statement, args)
)
if err == nil {
defer rows.Close()
for rows.Next() {
var id int64
rows.Scan(&id)
ids = append(ids, id)
}
}
return ids, err
}
func (adapter *Adapter) query(ctx context.Context, statement string, args []interface{}) (*db.Rows, error) {
var (
err error
rows *db.Rows
)
finish := adapter.Instrumenter.Observe(ctx, "adapter-query", statement)
if adapter.Tx != nil {
rows, err = adapter.Tx.QueryContext(ctx, statement, args...)
} else {
rows, err = adapter.DB.QueryContext(ctx, statement, args...)
}
finish(err)
return rows, errorFunc(err)
}
// Begin begins a new transaction.
func (adapter *Adapter) Begin(ctx context.Context) (rel.Adapter, error) {
newAdapter, err := adapter.Adapter.Begin(ctx)
return &Adapter{
Adapter: newAdapter.(*sql.Adapter),
}, err
}
func errorFunc(err error) error {
if err == nil {
return nil
}
var (
msg = err.Error()
constraintType = sql.ExtractString(msg, "violates ", " constraint")
)
switch constraintType {
case "unique":
return rel.ConstraintError{
Key: sql.ExtractString(err.Error(), "constraint \"", "\""),
Type: rel.UniqueConstraint,
Err: err,
}
case "foreign key":
return rel.ConstraintError{
Key: sql.ExtractString(err.Error(), "constraint \"", "\""),
Type: rel.ForeignKeyConstraint,
Err: err,
}
case "check":
return rel.ConstraintError{
Key: sql.ExtractString(err.Error(), "constraint \"", "\""),
Type: rel.CheckConstraint,
Err: err,
}
default:
return err
}
}
func mapColumnFunc(column *rel.Column) (string, int, int) {
var (
typ string
m, n int
)
// postgres specific
column.Unsigned = false
if column.Default == "" {
column.Default = nil
}
switch column.Type {
case rel.ID:
typ = "SERIAL NOT NULL PRIMARY KEY"
case rel.BigID:
typ = "BIGSERIAL NOT NULL PRIMARY KEY"
case rel.DateTime:
typ = "TIMESTAMPTZ"
if t, ok := column.Default.(time.Time); ok {
column.Default = t.Format("2006-01-02 15:04:05")
}
case rel.Int, rel.BigInt, rel.Text:
column.Limit = 0
typ, m, n = sql.MapColumn(column)
case rel.JSON:
typ = "JSONB"
default:
typ, m, n = sql.MapColumn(column)
}
return typ, m, n
}