-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.go
350 lines (305 loc) · 11.7 KB
/
schema.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package pgxjrep
import (
"context"
"encoding/json"
"github.com/iancoleman/strcase"
"github.com/sirupsen/logrus"
"os"
"regexp"
"strings"
)
const PublicSchema = "public"
type DbSchema struct {
ToDbCase func(input string) string
ToJsonCase func(input string) string
colSchema map[string]map[string][]ColumnSchema
colMap map[string]map[string]map[string]bool
keywords []string
}
type ColumnSchema struct {
SchemaName string `json:"schemaName"`
RelationName string `json:"relationName"`
ColumnName string `json:"columnName"`
Position int16 `json:"position"`
TypeOid int64 `json:"typeOid"`
DataType string `json:"dataType"`
TypeType string `json:"typeType"`
Size int `json:"size"`
Modifier int `json:"modifier"`
Dimension int `json:"dimension"`
CharacterMaximumLength *int `json:"characterMaximumLength"`
NumericPrecision *int `json:"numericPrecision"`
NumericScale *int `json:"numericScale"`
EnumValues []string `json:"enumValues"`
DefaultValue string `json:"defaultValue"`
IsNotNull bool `json:"isNotNull"`
IsGenerated bool `json:"isGenerated"`
IsPrimaryKey bool `json:"isPrimaryKey"`
IsRequired bool `json:"isRequired"`
IsReadonly bool `json:"isReadonly"`
ColumnComment bool `json:"columnComment"`
}
type ColumnData struct {
DbName string
JsonName string
Value interface{}
IsString bool
IsPk bool
}
type keywordSchema struct {
Word string `json:"word"`
}
var log *logrus.Logger
func NewSchema(conn PgxConn, ctx context.Context) (*DbSchema, error) {
log = logrus.New()
log.Formatter.(*logrus.TextFormatter).ForceColors = true
log.Formatter.(*logrus.TextFormatter).DisableTimestamp = false
log.Level = logrus.TraceLevel
log.Out = os.Stdout
dbSchema := &DbSchema{
ToDbCase: strcase.ToSnake,
ToJsonCase: strcase.ToLowerCamel,
colSchema: make(map[string]map[string][]ColumnSchema),
colMap: make(map[string]map[string]map[string]bool),
}
sql := `
SELECT json_agg(t)
FROM (SELECT
d.nspname::text AS "schemaName",
c.relname::text AS "relationName",
a.attname::text AS "columnName",
a.attnum AS "position",
COALESCE(td.oid, tb.oid, t.oid)::bigint AS "typeOid",
format_type(atttypid, NULL::integer) AS "dataType",
COALESCE(td.typtype, tb.typtype, t.typtype)::text AS "typeType",
a.attlen::int AS "size",
a.atttypmod::int AS "modifier",
COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS "dimension",
CAST(
information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t),
information_schema._pg_truetypmod(a, t)) AS int
) AS "characterMaximumLength",
CASE atttypid
WHEN 21 /*int2*/ THEN 16
WHEN 23 /*int4*/ THEN 32
WHEN 20 /*int8*/ THEN 64
WHEN 1700 /*numeric*/ THEN
CASE WHEN atttypmod = -1
THEN null
ELSE ((atttypmod - 4) >> 16) & 65535
END
WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
ELSE null
END::int AS "numericPrecision",
CASE
WHEN atttypid IN (21, 23, 20) THEN 0
WHEN atttypid IN (1700) THEN
CASE
WHEN atttypmod = -1 THEN null
ELSE (atttypmod - 4) & 65535
END
ELSE null
END::int AS "numericScale",
CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
THEN (SELECT array_agg(enumlabel) FROM pg_enum WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid))
ELSE NULL
END AS "enumValues",
CASE
WHEN a.attgenerated = '' THEN pg_get_expr(ad.adbin, ad.adrelid)
ELSE NULL::text
END::information_schema.character_data AS "defaultValue",
a.attnotnull AS "isNotNull",
CASE
WHEN coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval', false)
OR attidentity != '' OR attgenerated != ''
OR (t.typname = 'uuid' AND LENGTH(COALESCE(pg_get_expr(ad.adbin, ad.adrelid), '')) > 0) THEN true
ELSE false
END::bool AS "isGenerated",
CASE
WHEN a.attnum = any (ct.conkey) THEN true
ELSE false
END::bool AS "isPrimaryKey",
CASE
WHEN length(coalesce(pg_get_expr(ad.adbin, ad.adrelid), '')) > 0
OR attidentity != '' OR attgenerated != ''
OR a.attnotnull = false THEN false
ELSE true
END::bool AS "isRequired",
CASE
WHEN coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval', false)
OR attidentity != '' OR attgenerated != ''
OR (t.typname = 'uuid' AND length(coalesce(pg_get_expr(ad.adbin, ad.adrelid), '')) > 0) THEN true
WHEN (c.relkind = ANY (ARRAY ['r', 'p']))
OR (c.relkind = ANY (ARRAY ['v', 'f'])) AND pg_column_is_updatable(c.oid::regclass, a.attnum, false) THEN false
ELSE true
END::bool AS "isReadonly",
pg_catalog.col_description(c.oid, a.attnum) AS "columnComment"
FROM
pg_class c
LEFT JOIN pg_attribute a ON a.attrelid = c.oid
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid OR t.typbasetype > 0 AND t.typbasetype = tb.oid
LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p'
WHERE
a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
AND c.relkind IN ('r', 'p', 'f', 'v', 'm')
AND d.nspname NOT LIKE 'pg_%' AND d.nspname != 'information_schema'
AND (pg_has_role(c.relowner, 'USAGE'::text) OR has_table_privilege(quote_ident(d.nspname)||'.'||quote_ident(c.relname), 'SELECT'::text))
ORDER BY
d.nspname,
c.relname,
a.attnum
) t
`
jsn := new(string)
err := conn.QueryRow(ctx, sql).Scan(jsn)
if err != nil {
return nil, err
}
var res []ColumnSchema
err = json.Unmarshal([]byte(*jsn), &res)
if err != nil {
return nil, err
}
for _, v := range res {
if _, ok := dbSchema.colSchema[v.SchemaName]; !ok {
dbSchema.colSchema[v.SchemaName] = make(map[string][]ColumnSchema)
dbSchema.colMap[v.SchemaName] = make(map[string]map[string]bool)
}
if _, ok := dbSchema.colSchema[v.SchemaName][v.RelationName]; !ok {
dbSchema.colMap[v.SchemaName][v.RelationName] = make(map[string]bool)
}
dbSchema.colSchema[v.SchemaName][v.RelationName] = append(dbSchema.colSchema[v.SchemaName][v.RelationName], v)
dbSchema.colMap[v.SchemaName][v.RelationName][v.ColumnName] = true
jsonName := dbSchema.ToJsonCase(v.ColumnName)
if jsonName != v.ColumnName {
dbSchema.colMap[v.SchemaName][v.RelationName][jsonName] = false
}
}
//keywords
sql = "SELECT json_agg(t) FROM (SELECT word FROM pg_get_keywords() WHERE catcode != 'U' ORDER BY 1) t"
jsn = new(string)
err = conn.QueryRow(ctx, sql).Scan(jsn)
if err != nil {
return nil, err
}
var ks []keywordSchema
err = json.Unmarshal([]byte(*jsn), &ks)
if err != nil {
return nil, err
}
for _, v := range ks {
dbSchema.keywords = append(dbSchema.keywords, v.Word)
}
return dbSchema, nil
}
func (s *DbSchema) ColSchema(relation string) []ColumnSchema {
sch, rel := s.resolveNames(relation)
return s.colSchema[sch][rel]
}
func (s *DbSchema) ColMap(relation string) map[string]bool {
sch, rel := s.resolveNames(relation)
return s.colMap[sch][rel]
}
func (s *DbSchema) ResolveColumns(relation string, columns []string) []ColumnData {
colMap := make(map[string]interface{})
for _, v := range columns {
colMap[v] = nil
}
return s.ResolveColumnMap(relation, colMap)
}
func (s *DbSchema) ResolveColumnMap(relation string, values map[string]interface{}) []ColumnData {
var colVals []ColumnData
var isChar = func(term string) bool {
for _, v := range []string{"varchar", "char", "text"} {
if term == v {
return true
}
}
return false
}
cols := s.ColSchema(relation)
for _, col := range cols {
cd := ColumnData{
DbName: col.ColumnName,
JsonName: s.ToJsonCase(col.ColumnName),
Value: nil,
IsString: isChar(col.DataType),
IsPk: col.IsPrimaryKey,
}
if val, ok := values[cd.DbName]; ok {
cd.Value = val
colVals = append(colVals, cd)
} else if val, ok = values[cd.JsonName]; ok {
cd.Value = val
colVals = append(colVals, cd)
}
}
var unresolvedColumns []string
colMap := s.ColMap(relation)
for k := range values {
if _, ok := colMap[k]; !ok {
unresolvedColumns = append(unresolvedColumns, k)
}
}
if len(unresolvedColumns) > 0 {
log.Warningf("Relation %s does not contain columns: "+strings.Join(unresolvedColumns, ", "), relation)
}
return colVals
}
func (s *DbSchema) SingleQuote(value string) string {
return "'" + value + "'"
}
func (s *DbSchema) Quote(value string) string {
if strings.ContainsAny(value, "\"") {
return value
}
match, _ := regexp.MatchString("[A-Z]+", value)
if match {
return "\"" + value + "\""
}
for _, v := range s.keywords {
if v == value {
return "\"" + value + "\""
}
}
return value
}
func (s *DbSchema) UnQuote(value string) string {
if !strings.ContainsAny(value, "\"") {
return value
}
return strings.Replace(value, "\"", "", -1)
}
func (s *DbSchema) QuoteRelation(relation string) string {
sch, rel := s.resolveNames(relation)
if sch == PublicSchema {
return s.Quote(rel)
}
return s.Quote(sch) + "." + s.Quote(rel)
}
func (s *DbSchema) resolveNames(relation string) (string, string) {
var sch, rel string
names := strings.Split(relation, ".")
namesLen := len(names)
if namesLen == 2 {
sch = names[0]
rel = names[1]
} else if namesLen == 1 {
sch = PublicSchema
rel = names[0]
} else {
log.Panicln("invalid relation name: ", relation)
}
if _, ok := s.colSchema[sch]; !ok {
log.Panicln("schema not found: ", sch)
}
if _, ok := s.colSchema[sch][rel]; !ok {
log.Panicln("relation not found: ", sch, rel)
}
return sch, rel
}