-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspect.go
371 lines (307 loc) · 8.47 KB
/
inspect.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package mysql
import (
"context"
"database/sql"
"fmt"
"strings"
"golang.org/x/mod/semver"
"github.com/ychengcloud/cre"
schema "github.com/ychengcloud/cre/loader/sql"
"github.com/ychengcloud/cre/spec"
)
type inspect struct {
Driver cre.Driver
schema *schema.Schema
// Database information
version string
collate string
charset string
}
var _ schema.Inspector = (*inspect)(nil)
func NewInspector(drv cre.Driver) schema.Inspector {
return &inspect{Driver: drv}
}
func (i *inspect) Inspect(ctx context.Context, name string) (*schema.Schema, error) {
i.schema = &schema.Schema{Name: name}
err := i.dbInfo(ctx)
if err != nil {
return nil, err
}
tables, err := i.tables(ctx)
if err != nil {
return nil, err
}
i.schema.Tables = tables
err = i.inspectColumns(ctx)
if err != nil {
return nil, err
}
err = i.inspectIndexes(ctx)
if err != nil {
return nil, err
}
err = i.inspectForeignKeys(ctx)
if err != nil {
return nil, err
}
return i.schema, nil
}
func (i *inspect) dbInfo(ctx context.Context) error {
row, err := i.querySqlRow(ctx, VariablesQuery)
if err != nil {
return err
}
if err := row.Scan(&i.version, &i.collate, &i.charset); err != nil {
return err
}
return nil
}
// compareVersion returns an integer comparing two versions according to
// semantic version precedence.
func (i *inspect) compareVersion(version string) int {
v := i.version
if i.mariadb() {
v = v[:strings.Index(v, "MariaDB")-1]
}
return semver.Compare("v"+v, "v"+version)
}
// indexExpr check if the connected database supports
// index expressions (functional key part).
func (i *inspect) indexExpr() bool {
return !i.mariadb() && i.compareVersion("8.0.13") >= 0
}
// mariadb check if the Driver is connected to a MariaDB database.
func (i *inspect) mariadb() bool {
return strings.Index(i.version, "MariaDB") > 0
}
func (i *inspect) tables(ctx context.Context) ([]*schema.Table, error) {
var (
name string
autoIncrement sql.NullInt64
charset, collation, comment, options sql.NullString
)
rows, err := i.querySqlRows(ctx, TablesQuery, i.schema.Name)
if err != nil {
return nil, err
}
defer rows.Close()
var tables []*schema.Table
for rows.Next() {
if err := rows.Scan(&name, &charset, &collation, &autoIncrement, &comment, &options); err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("mysql/tables: no tables found for schema [%q]", i.schema.Name)
}
return nil, err
}
table := &schema.Table{
Name: name,
Schema: i.schema,
Charset: charset.String,
Collation: collation.String,
AutoIncrement: int(autoIncrement.Int64),
Comment: comment.String,
Options: options.String,
}
tables = append(tables, table)
}
if err = rows.Err(); err != nil {
return nil, err
}
return tables, nil
}
func (i *inspect) inspectColumns(ctx context.Context) error {
for _, table := range i.schema.Tables {
columns, err := i.columns(ctx, table)
if err != nil {
return err
}
table.Columns = columns
}
return nil
}
func (i *inspect) inspectIndexes(ctx context.Context) error {
for _, table := range i.schema.Tables {
indexes, err := i.indexes(ctx, table.Name)
if err != nil {
return err
}
table.Indexes = indexes
}
return nil
}
func (i *inspect) inspectForeignKeys(ctx context.Context) error {
for _, table := range i.schema.Tables {
foreignKeys, err := i.foreignKeys(ctx, table)
if err != nil {
return err
}
table.ForeignKeys = foreignKeys
}
return nil
}
func (i *inspect) columns(ctx context.Context, t *schema.Table) ([]*schema.Column, error) {
args := []any{i.schema.Name, t.Name}
rows, err := i.querySqlRows(ctx, ColumnsQuery, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var columns []*schema.Column
for rows.Next() {
var name, colType, comment, nullable, key, defaults, extra, charset, collation sql.NullString
var precision, scale sql.NullInt64
if err := rows.Scan(&name, &colType, &comment, &nullable, &key, &defaults, &extra, &charset, &collation, &precision, &scale); err != nil {
return nil, err
}
ct, err := ParseType(colType.String)
if err != nil {
return nil, err
}
column := &schema.Column{
Name: name.String,
Type: ct,
Comment: comment.String,
Default: defaults,
Nullable: nullable.String == "YES",
Charset: charset.String,
Collation: collation.String,
Primary: key.String == "PRI",
Table: t,
}
parseExtra(column, extra.String)
switch column.Type.(type) {
case *spec.FloatType:
column.Precision = int(precision.Int64)
column.Scale = int(scale.Int64)
}
columns = append(columns, column)
}
if err = rows.Err(); err != nil {
return nil, err
}
return columns, nil
}
func (i *inspect) indexes(ctx context.Context, name string) ([]*schema.Index, error) {
args := []any{i.schema.Name, name}
query := IndexesQuery
if i.indexExpr() {
query = IndexesExprQuery
}
rows, err := i.querySqlRows(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var indexs []*schema.Index
indexMap := make(map[string]*schema.Index)
for rows.Next() {
var (
nonunique bool
seqno int
name, indexType string
subPart sql.NullInt64
column, expr, comment, collate sql.NullString
)
if err := rows.Scan(&name, &column, &nonunique, &seqno, &indexType, &collate, &comment, &subPart, &expr); err != nil {
return nil, fmt.Errorf("mysql/indexes: scanning index: %w", err)
}
index, ok := indexMap[name]
if !ok {
index = &schema.Index{
Name: name,
Unique: !nonunique,
Type: indexType,
Comment: comment.String,
}
if name == "PRIMARY" {
index.Primary = true
}
indexMap[name] = index
indexs = append(indexs, index)
}
part := &schema.IndexColumn{
SeqNo: seqno,
Column: column.String,
}
if subPart.Int64 > 0 {
part.Sub = int(subPart.Int64)
}
index.IndexColumns = append(index.IndexColumns, part)
}
if err = rows.Err(); err != nil {
return nil, err
}
return indexs, nil
}
func (i *inspect) foreignKeys(ctx context.Context, t *schema.Table) ([]*schema.ForeignKey, error) {
args := []any{i.schema.Name, t.Name}
query := ForeignKeysQuery
rows, err := i.querySqlRows(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var foreignKeys []*schema.ForeignKey
foreignKeysMap := make(map[string]*schema.ForeignKey)
for rows.Next() {
var (
name, table, column, tableSchema, refTable, refColumn, refSchema, updateRule, deleteRule string
)
if err := rows.Scan(&name, &table, &column, &tableSchema, &refTable, &refColumn, &refSchema, &updateRule, &deleteRule); err != nil {
return nil, fmt.Errorf("mysql/fks: scanning fk: %w", err)
}
foreignKey, ok := foreignKeysMap[name]
rt := t.Schema.Table(refTable)
if rt == nil {
return nil, fmt.Errorf("mysql/fks: ref table %q not found for fk %q", refTable, name)
}
if !ok {
foreignKey = &schema.ForeignKey{
Name: name,
Table: t,
//目前只支持引用同一个数据库的外键
RefTable: rt,
OnUpdate: schema.ReferenceOption(updateRule),
OnDelete: schema.ReferenceOption(deleteRule),
}
foreignKeysMap[name] = foreignKey
foreignKeys = append(foreignKeys, foreignKey)
}
c := t.Column(column)
if c == nil {
return nil, fmt.Errorf("mysql/fks: column %q not found for fk %q", column, foreignKey.Name)
}
foreignKey.Columns = append(foreignKey.Columns, c)
rc := foreignKey.RefTable.Column(refColumn)
if rc == nil {
return nil, fmt.Errorf("mysql/fks: ref column %q not found for fk %q", refColumn, foreignKey.Name)
}
foreignKey.RefColumns = append(foreignKey.RefColumns, rc)
}
if err = rows.Err(); err != nil {
return nil, err
}
return foreignKeys, nil
}
func (i *inspect) querySqlRows(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
result, err := i.Driver.Query(ctx, query, args...)
if err != nil {
return nil, err
}
rows, ok := result.(*sql.Rows)
if !ok {
return nil, fmt.Errorf("mysql: invalid type %T. expect *sql.Rows for result", result)
}
return rows, nil
}
func (i *inspect) querySqlRow(ctx context.Context, query string, args ...any) (*sql.Row, error) {
result, err := i.Driver.QueryRow(ctx, query, args...)
if err != nil {
return nil, err
}
row, ok := result.(*sql.Row)
if !ok {
return nil, fmt.Errorf("mysql: invalid type %T. expect *sqlld.Row for result", result)
}
return row, nil
}