-
Notifications
You must be signed in to change notification settings - Fork 317
/
postgres.go
285 lines (273 loc) · 8.05 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package loader
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/xo/xo/models"
"github.com/xo/xo/templates/gotpl"
)
func init() {
Register(&Loader{
Driver: "postgres",
Kind: map[Kind]string{
KindTable: "r",
KindView: "v",
},
Flags: []Flag{
{
ContextKey: OidsKey,
Desc: "enable postgres OIDs",
Default: "false",
Value: false,
},
},
Schema: models.PostgresSchema,
GoType: PostgresGoType,
Enums: models.PostgresEnums,
EnumValues: models.PostgresEnumValues,
Procs: models.PostgresProcs,
ProcParams: models.PostgresProcParams,
Tables: PostgresTables,
TableColumns: PostgresTableColumns,
TableForeignKeys: models.PostgresTableForeignKeys,
TableIndexes: models.PostgresTableIndexes,
IndexColumns: PostgresIndexColumns,
QueryStrip: PostgresQueryStrip,
QueryColumns: PostgresQueryColumns,
})
}
// PostgresGoType parse a type into a Go type based on the database type definition.
func PostgresGoType(ctx context.Context, typ string, nullable bool) (string, string, int, error) {
// SETOF -> []T
if strings.HasPrefix(typ, "SETOF ") {
goType, _, _, err := PostgresGoType(ctx, typ[len("SETOF "):], false)
if err != nil {
return "", "", 0, err
}
return "[]" + goType, "nil", 0, nil
}
// determine if it's a slice
asSlice := false
if strings.HasSuffix(typ, "[]") {
typ, asSlice = typ[:len(typ)-2], true
}
// extract precision
typ, prec, _, err := parsePrec(typ)
if err != nil {
return "", "", 0, err
}
var goType, zero string
switch typ {
case "boolean":
goType, zero = "bool", "false"
if nullable {
goType, zero = "sql.NullBool", "sql.NullBool{}"
}
case "character", "character varying", "text", "money", "inet", "bpchar":
goType, zero = "string", `""`
if nullable {
goType, zero = "sql.NullString", "sql.NullString{}"
}
case "smallint":
goType, zero = "int16", "0"
if nullable {
goType, zero = "sql.NullInt64", "sql.NullInt64{}"
}
case "integer":
goType, zero = gotpl.Int32(ctx), "0"
if nullable {
goType, zero = "sql.NullInt64", "sql.NullInt64{}"
}
case "bigint":
goType, zero = "int64", "0"
if nullable {
goType, zero = "sql.NullInt64", "sql.NullInt64{}"
}
case "smallserial":
goType, zero = "uint16", "0"
if nullable {
goType, zero = "sql.NullInt64", "sql.NullInt64{}"
}
case "serial":
goType, zero = gotpl.Uint32(ctx), "0"
if nullable {
goType, zero = "sql.NullInt64", "sql.NullInt64{}"
}
case "bigserial":
goType, zero = "uint64", "0"
if nullable {
goType, zero = "sql.NullInt64", "sql.NullInt64{}"
}
case "real":
goType, zero = "float32", "0.0"
if nullable {
goType, zero = "sql.NullFloat64", "sql.NullFloat64{}"
}
case "numeric", "double precision":
goType, zero = "float64", "0.0"
if nullable {
goType, zero = "sql.NullFloat64", "sql.NullFloat64{}"
}
case "bytea":
goType, zero, asSlice = "byte", "nil", true
case "date", "timestamp with time zone", "time with time zone", "time without time zone", "timestamp without time zone":
goType, zero = "time.Time", "time.Time{}"
if nullable {
goType, zero = "sql.NullTime", "sql.NullTime{}"
}
case "interval":
goType, zero = "*time.Duration", "nil"
case `"char"`, "bit":
// FIXME: this needs to actually be tested ...
// should be 'rune' but not sure if database/sql supports 'rune' as a
// type?
//
// this is mainly here because postgres's pg_catalog.* meta tables have
// this as a type.
//
// typ = "rune"
goType, zero = "uint8", "0"
case `"any"`, "bit varying":
goType, zero, asSlice = "byte", "nil", true
case "hstore":
goType, zero = "hstore.Hstore", "nil"
case "uuid":
// FIXME: this is probably not what we want
goType, zero = "uuid.UUID", "uuid.UUID{}"
default:
goType, zero = schemaGoType(ctx, typ)
}
// handle slices
switch {
case asSlice && goType == "string":
return "StringSlice", "StringSlice{}", prec, nil
case asSlice:
return "[]" + goType, "nil", 0, nil
}
return goType, zero, prec, nil
}
// PostgresTables returns the Postgres tables with the manual PK information added.
// ManualPk is true when the table does not have a sequence defined.
func PostgresTables(ctx context.Context, db models.DB, schema string, relkind string) ([]*models.Table, error) {
// get the tables
rows, err := models.PostgresTables(ctx, db, schema, relkind)
if err != nil {
return nil, err
}
// Get the tables that have a sequence defined.
sequences, err := models.PostgresSequences(ctx, db, schema)
if err != nil {
return nil, err
}
// Add information about manual FK.
var tables []*models.Table
for _, row := range rows {
manualPk := true
// Look for a match in the table name where it contains the sequence
for _, sequence := range sequences {
if sequence.TableName == row.TableName {
manualPk = false
}
}
tables = append(tables, &models.Table{
TableName: row.TableName,
Type: row.Type,
ManualPk: manualPk,
})
}
return tables, nil
}
// PostgresTableColumns returns the columns for a table.
func PostgresTableColumns(ctx context.Context, db models.DB, schema string, table string) ([]*models.Column, error) {
return models.PostgresTableColumns(ctx, db, schema, table, EnableOids(ctx))
}
// PostgresIndexColumns returns the column list for an index.
//
// FIXME: rewrite this using SQL exclusively using OVER
func PostgresIndexColumns(ctx context.Context, db models.DB, schema string, table string, index string) ([]*models.IndexColumn, error) {
// load columns
cols, err := models.PostgresIndexColumns(ctx, db, schema, index)
if err != nil {
return nil, err
}
// load col order
colOrd, err := models.PostgresGetColOrder(ctx, db, schema, index)
if err != nil {
return nil, err
}
// build schema name used in errors
s := schema
if s != "" {
s += "."
}
// put cols in order using colOrder
var ret []*models.IndexColumn
for _, v := range strings.Split(colOrd.Ord, " ") {
cid, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("could not convert %s%s index %s column %s to int", s, table, index, v)
}
// find column
found := false
var c *models.IndexColumn
for _, ic := range cols {
if cid == ic.Cid {
found, c = true, ic
break
}
}
// sanity check
if !found {
return nil, fmt.Errorf("could not find %s%s index %s column id %d", s, table, index, cid)
}
ret = append(ret, c)
}
return ret, nil
}
// PostgresQueryStrip strips '::type AS name' in queries.
func PostgresQueryStrip(query []string, queryComments []string) {
for i, l := range query {
pos := stripRE.FindStringIndex(l)
if pos != nil {
query[i] = l[:pos[0]] + l[pos[1]:]
queryComments[i+1] = l[pos[0]:pos[1]]
} else {
queryComments[i+1] = ""
}
}
}
// stripRE is the regexp to match the '::type AS name' portion in a query,
// which is a quirk/requirement of generating queries for postgres.
var stripRE = regexp.MustCompile(`(?i)::[a-z][a-z0-9_\.]+\s+AS\s+[a-z][a-z0-9_\.]+`)
// PostgresQueryColumns parses the query and generates a type for it.
func PostgresQueryColumns(ctx context.Context, db models.DB, _ string, inspect []string) ([]*models.Column, error) {
// create temporary view xoid
xoid := "_xo_" + randomID()
viewq := `CREATE TEMPORARY VIEW ` + xoid + ` AS (` + strings.Join(inspect, "\n") + `)`
models.Logf(viewq)
if _, err := db.ExecContext(ctx, viewq); err != nil {
return nil, err
}
// query to determine schema name where temporary view was created
nspq := `SELECT n.nspname ` +
`FROM pg_class c ` +
`JOIN pg_namespace n ON n.oid = c.relnamespace ` +
`WHERE n.nspname LIKE 'pg_temp%' AND c.relname = $1`
// run query
models.Logf(nspq, xoid)
var schema string
if err := db.QueryRowContext(ctx, nspq, xoid).Scan(&schema); err != nil {
return nil, err
}
// load column information
return models.PostgresTableColumns(ctx, db, schema, xoid, false)
}
// OidsKey is the oids context key.
const OidsKey ContextKey = "oids"
// EnableOids returns the EnableOids value from the context.
func EnableOids(ctx context.Context) bool {
b, _ := ctx.Value(OidsKey).(bool)
return b
}