-
Notifications
You must be signed in to change notification settings - Fork 6
/
mysqlDescriber.go
868 lines (756 loc) · 23.1 KB
/
mysqlDescriber.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
package mysql
import (
"database/sql"
"fmt"
"github.com/goradd/goradd/pkg/orm/db"
sql2 "github.com/goradd/goradd/pkg/orm/db/sql"
. "github.com/goradd/goradd/pkg/orm/query"
"github.com/goradd/goradd/pkg/stringmap"
strings2 "github.com/goradd/goradd/pkg/strings"
"log"
"math"
"sort"
"strings"
)
/*
This file contains the code that parses the data structure found in a MySQL database into
our own cross-platform internal database description object.
*/
const (
ColumnTypeSet = "Set"
ColumnTypeEnum = "Enum"
)
type mysqlTable struct {
name string
columns []mysqlColumn
indexes []mysqlIndex
fkMap map[string]mysqlForeignKey
comment string
options map[string]interface{}
}
type mysqlColumn struct {
name string
defaultValue sql2.SqlReceiver
isNullable string
dataType string
dataLen int
characterMaxLen sql.NullInt64
columnType string
key string
extra string
comment string
options map[string]interface{}
}
type mysqlIndex struct {
name string
nonUnique bool
tableName string
columnName string
}
type mysqlForeignKey struct {
constraintName string
tableName string
columnName string
referencedSchema sql.NullString
referencedTableName sql.NullString
referencedColumnName sql.NullString
updateRule sql.NullString
deleteRule sql.NullString
}
/*
type DB struct {
dbKey string
db *sql.DB
config mysql.Config
options DbOptions
}
func NewMysql2 (dbKey string , options DbOptions, config *mysql.Config) (*DB, error) {
source := DB{}
db, err := sql.Open("mysql", config.FormatDSN())
source.dbKey = DbKey
source.db = db
source.config = *config
source.options = options
// Ping?
return &source,err
}*/
func (m *DB) loadDescription() {
rawTables := m.getRawTables()
description := m.descriptionFromRawTables(rawTables)
m.goraddDatabase = db.NewDatabase(m.DbKey(), m.IdSuffix(), description)
}
func (m *DB) getRawTables() map[string]mysqlTable {
var tableMap = make(map[string]mysqlTable)
indexes, err := m.getIndexes()
if err != nil {
return nil
}
foreignKeys, err := m.getForeignKeys()
if err != nil {
return nil
}
tables := m.getTables()
for _, table := range tables {
// Do some processing on the foreign keys
for _, fk := range foreignKeys[table.name] {
if fk.referencedColumnName.Valid && fk.referencedTableName.Valid {
if _, ok := table.fkMap[fk.columnName]; ok {
log.Printf("Warning: Column %s:%s multi-table foreign keys are not supported.", table.name, fk.columnName)
delete(table.fkMap, fk.columnName)
} else {
table.fkMap[fk.columnName] = fk
}
}
}
columns, err2 := m.getColumns(table.name)
if err2 != nil {
return nil
}
table.indexes = indexes[table.name]
table.columns = columns
tableMap[table.name] = table
}
return tableMap
}
// Gets information for a table
func (m *DB) getTables() []mysqlTable {
var tableName, tableComment string
var tables []mysqlTable
// Use the MySQL5 Information Schema to get a list of all the tables in this database
// (excluding views, etc.)
dbName := m.databaseName
rows, err := m.SqlDb().Query(fmt.Sprintf(`
SELECT
table_name,
table_comment
FROM
information_schema.tables
WHERE
table_type <> 'VIEW' AND
table_schema = '%s';
`, dbName))
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&tableName, &tableComment)
if err != nil {
log.Fatal(err)
}
log.Println(tableName)
table := mysqlTable{
name: tableName,
comment: tableComment,
columns: []mysqlColumn{},
fkMap: make(map[string]mysqlForeignKey),
indexes: []mysqlIndex{},
}
if table.options, table.comment, err = sql2.ExtractOptions(table.comment); err != nil {
log.Print("Error in comment options for table " + table.name + " - " + err.Error())
}
tables = append(tables, table)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return tables
}
func (m *DB) getColumns(table string) (columns []mysqlColumn, err error) {
dbName := m.databaseName
rows, err := m.SqlDb().Query(fmt.Sprintf(`
SELECT
column_name,
column_default,
is_nullable,
data_type,
character_maximum_length,
column_type,
column_key,
extra,
column_comment
FROM
information_schema.columns
WHERE
table_name = '%s' AND
table_schema = '%s'
ORDER BY
ordinal_position;
`, table, dbName))
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var col mysqlColumn
for rows.Next() {
col = mysqlColumn{}
err = rows.Scan(&col.name, &col.defaultValue.R, &col.isNullable, &col.dataType, &col.characterMaxLen, &col.columnType, &col.key, &col.extra, &col.comment)
if err != nil {
log.Fatal(err)
return nil, err
}
if col.options, col.comment, err = sql2.ExtractOptions(col.comment); err != nil {
log.Print("Error in table comment options for table " + table + ":" + col.name + " - " + err.Error())
}
columns = append(columns, col)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return columns, err
}
func (m *DB) getIndexes() (indexes map[string][]mysqlIndex, err error) {
dbName := m.databaseName
indexes = make(map[string][]mysqlIndex)
rows, err := m.SqlDb().Query(fmt.Sprintf(`
SELECT
index_name,
non_unique,
table_name,
column_name
FROM
information_schema.statistics
WHERE
table_schema = '%s';
`, dbName))
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var index mysqlIndex
for rows.Next() {
index = mysqlIndex{}
err = rows.Scan(&index.name, &index.nonUnique, &index.tableName, &index.columnName)
if err != nil {
log.Fatal(err)
return nil, err
}
tableIndexes := indexes[index.tableName]
tableIndexes = append(tableIndexes, index)
indexes[index.tableName] = tableIndexes
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return indexes, err
}
// getForeignKeys gets information on the foreign keys.
//
// Note that querying the information_schema database is SLOW, so we want to do it as few times as possible.
func (m *DB) getForeignKeys() (foreignKeys map[string][]mysqlForeignKey, err error) {
dbName := m.databaseName
fkMap := make(map[string]mysqlForeignKey)
rows, err := m.SqlDb().Query(fmt.Sprintf(`
SELECT
constraint_name,
table_name,
column_name,
referenced_table_name,
referenced_column_name
FROM
information_schema.key_column_usage
WHERE
constraint_schema = '%s'
ORDER BY
ordinal_position;
`, dbName))
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
fk := mysqlForeignKey{}
err = rows.Scan(&fk.constraintName, &fk.tableName, &fk.columnName, &fk.referencedTableName, &fk.referencedColumnName)
if err != nil {
log.Fatal(err)
return nil, err
}
if fk.referencedColumnName.Valid {
fkMap[fk.constraintName] = fk
}
}
rows.Close()
rows, err = m.SqlDb().Query(fmt.Sprintf(`
SELECT
constraint_name,
update_rule,
delete_rule
FROM
information_schema.referential_constraints
WHERE
constraint_schema = '%s';
`, dbName))
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var constraintName string
var updateRule, deleteRule sql.NullString
err = rows.Scan(&constraintName, &updateRule, &deleteRule)
if err != nil {
log.Fatal(err)
}
if fk, ok := fkMap[constraintName]; ok {
fk.updateRule = updateRule
fk.deleteRule = deleteRule
fkMap[constraintName] = fk
}
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
foreignKeys = make(map[string][]mysqlForeignKey)
stringmap.Range(fkMap, func(_ string, val interface{}) bool {
fk := val.(mysqlForeignKey)
tableKeys := foreignKeys[fk.tableName]
tableKeys = append(tableKeys, fk)
foreignKeys[fk.tableName] = tableKeys
return true
})
return foreignKeys, err
}
// Convert the database native type to a more generic sql type, and a go table type.
func (m *DB) processTypeInfo(tableName string, column mysqlColumn, cd *db.ColumnDescription) {
dataLen := sql2.GetDataDefLength(column.columnType)
isUnsigned := strings.Contains(column.columnType, "unsigned")
switch column.dataType {
case "time":
cd.NativeType = sql2.SqlTypeTime
cd.GoType = ColTypeDateTime.GoType()
cd.SubType = "time"
case "timestamp":
cd.NativeType = sql2.SqlTypeTimestamp
cd.GoType = ColTypeDateTime.GoType()
cd.SubType = "timestamp"
case "datetime":
cd.NativeType = sql2.SqlTypeDatetime
cd.GoType = ColTypeDateTime.GoType()
case "date":
cd.NativeType = sql2.SqlTypeDate
cd.GoType = ColTypeDateTime.GoType()
cd.SubType = "date"
case "tinyint":
if dataLen == 1 {
cd.NativeType = sql2.SqlTypeBool
cd.GoType = ColTypeBool.GoType()
} else {
if isUnsigned {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeUnsigned.GoType()
min, max := sql2.GetMinMax(column.options, 0, 255, tableName, column.name)
cd.MinValue = uint(min)
cd.MaxValue = uint(max)
cd.MaxCharLength = 3
} else {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeInteger.GoType()
min, max := sql2.GetMinMax(column.options, -128, 127, tableName, column.name)
cd.MinValue = int(min)
cd.MaxValue = int(max)
cd.MaxCharLength = 4 // allow for a negative sign
}
}
case "int":
if isUnsigned {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeUnsigned.GoType()
min, max := sql2.GetMinMax(column.options, 0, 4294967295, tableName, column.name)
cd.MinValue = uint(min)
cd.MaxValue = uint(max)
cd.MaxCharLength = 10
} else {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeInteger.GoType()
min, max := sql2.GetMinMax(column.options, -2147483648, 2147483647, tableName, column.name)
cd.MinValue = int(min)
cd.MaxValue = int(max)
cd.MaxCharLength = 11
}
case "smallint":
if isUnsigned {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeUnsigned.GoType()
min, max := sql2.GetMinMax(column.options, 0, 65535, tableName, column.name)
cd.MinValue = uint(min)
cd.MaxValue = uint(max)
cd.MaxCharLength = 5
} else {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeInteger.GoType()
min, max := sql2.GetMinMax(column.options, -32768, 32767, tableName, column.name)
cd.MinValue = int(min)
cd.MaxValue = int(max)
cd.MaxCharLength = 6
}
case "mediumint":
if isUnsigned {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeUnsigned.GoType()
min, max := sql2.GetMinMax(column.options, 0, 16777215, tableName, column.name)
cd.MinValue = uint(min)
cd.MaxValue = uint(max)
cd.MaxCharLength = 8
} else {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeInteger.GoType()
min, max := sql2.GetMinMax(column.options, -8388608, 8388607, tableName, column.name)
cd.MinValue = int(min)
cd.MaxValue = int(max)
cd.MaxCharLength = 8
}
case "bigint": // We need to be explicit about this in go, since int will be whatever the OS native int size is, but go will support int64 always.
// Also, since Json can only be decoded into float64s, we are limited in our ability to represent large min and max numbers in the json to about 2^53
if isUnsigned {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeUnsigned64.GoType()
if v := column.options["min"]; v != nil {
if v2, ok := v.(float64); !ok {
log.Print("Error in min value in comment for table " + tableName + ":" + column.name + ". Value is not a valid number.")
cd.MinValue = uint64(0)
} else if v2 < 0 {
log.Print("Error in min value in comment for table " + tableName + ":" + column.name + ". Value cannot be less than zero.")
cd.MinValue = uint64(0)
} else {
cd.MinValue = uint64(v2)
}
} else {
cd.MinValue = 0
}
if v := column.options["max"]; v != nil {
if v2, ok := v.(float64); !ok {
log.Print("Error in max value in comment for table " + tableName + ":" + column.name + ". Value is not a valid number.")
cd.MaxValue = uint64(math.MaxUint64)
} else {
cd.MaxValue = int64(v2)
}
} else {
cd.MaxValue = uint64(math.MaxUint64)
}
cd.MaxCharLength = 20
} else {
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeInteger64.GoType()
if v := column.options["min"]; v != nil {
if v2, ok := v.(float64); !ok {
log.Print("Error in min value in comment for table " + tableName + ":" + column.name + ". Value is not a valid number.")
cd.MinValue = int64(math.MinInt64)
} else {
cd.MinValue = int64(v2)
}
} else {
cd.MinValue = int64(math.MinInt64)
}
if v := column.options["max"]; v != nil {
if v2, ok := v.(float64); !ok {
log.Print("Error in max value in comment for table " + tableName + ":" + column.name + ". Value is not a valid number.")
cd.MaxValue = int64(math.MaxInt64)
} else {
cd.MaxValue = int64(v2)
}
} else {
cd.MaxValue = int64(math.MaxInt64)
}
cd.MaxCharLength = 20
}
case "float":
cd.NativeType = sql2.SqlTypeFloat
cd.GoType = ColTypeFloat.GoType()
cd.MinValue, cd.MaxValue = sql2.GetMinMax(column.options, -math.MaxFloat32, math.MaxFloat32, tableName, column.name)
case "double":
cd.NativeType = sql2.SqlTypeDouble
cd.GoType = ColTypeDouble.GoType()
cd.MinValue, cd.MaxValue = sql2.GetMinMax(column.options, -math.MaxFloat64, math.MaxFloat64, tableName, column.name)
case "varchar":
cd.NativeType = sql2.SqlTypeVarchar
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = uint64(dataLen)
case "char":
cd.NativeType = sql2.SqlTypeChar
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = uint64(dataLen)
case "blob":
cd.NativeType = sql2.SqlTypeBlob
cd.GoType = ColTypeBytes.GoType()
cd.MaxCharLength = 65535
case "tinyblob":
cd.NativeType = sql2.SqlTypeBlob
cd.GoType = ColTypeBytes.GoType()
cd.MaxCharLength = 255
case "mediumblob":
cd.NativeType = sql2.SqlTypeBlob
cd.GoType = ColTypeBytes.GoType()
cd.MaxCharLength = 16777215
case "longblob":
cd.NativeType = sql2.SqlTypeBlob
cd.GoType = ColTypeBytes.GoType()
cd.MaxCharLength = math.MaxUint32
case "text":
cd.NativeType = sql2.SqlTypeText
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = 65535
case "tinytext":
cd.NativeType = sql2.SqlTypeText
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = 255
case "mediumtext":
cd.NativeType = sql2.SqlTypeText
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = 16777215
case "longtext":
cd.NativeType = sql2.SqlTypeText
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = math.MaxUint32
case "decimal": // No native equivalent in Go. See the "Big" go package for support. You will need to shephard numbers into and out of string format to move data to the database
cd.NativeType = sql2.SqlTypeDecimal
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = uint64(dataLen) + 3
case "year":
cd.NativeType = sql2.SqlTypeInteger
cd.GoType = ColTypeInteger.GoType()
case "set":
log.Print("Note: Using association tables is preferred to using DB SET columns in table " + tableName + ":" + column.name + ".")
cd.NativeType = ColumnTypeSet
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = uint64(column.characterMaxLen.Int64)
case "enum":
log.Print("Note: Using type tables is preferred to using DB ENUM columns in table " + tableName + ":" + column.name + ".")
cd.NativeType = ColumnTypeEnum
cd.GoType = ColTypeString.GoType()
cd.MaxCharLength = uint64(column.characterMaxLen.Int64)
default:
cd.NativeType = sql2.SqlTypeUnknown
cd.GoType = ColTypeString.GoType()
}
cd.DefaultValue = column.defaultValue.Unpack(ColTypeFromGoTypeString(cd.GoType))
}
func (m *DB) descriptionFromRawTables(rawTables map[string]mysqlTable) db.DatabaseDescription {
dd := db.DatabaseDescription{Key: m.DbKey(), AssociatedObjectPrefix: m.AssociatedObjectPrefix()}
keys := stringmap.SortedKeys(rawTables)
for _,tableName := range keys {
table := rawTables[tableName]
if table.options["skip"] != nil {
continue
}
if strings2.EndsWith(tableName, m.TypeTableSuffix()) {
t := m.getTypeTableDescription(table)
dd.Tables = append(dd.Tables, t)
} else if strings2.EndsWith(tableName, m.AssociationTableSuffix()) {
if mm,ok := m.getManyManyDescription(table); ok {
dd.MM = append(dd.MM, mm)
}
} else {
t := m.getTableDescription(table)
dd.Tables = append(dd.Tables, t)
}
}
return dd
}
func (m *DB) getTableDescription(t mysqlTable) db.TableDescription {
var columnDescriptions []db.ColumnDescription
var pkCount int
for _, col := range t.columns {
cd := m.getColumnDescription(t, col)
if cd.IsPk {
// private keys go first
// the following code does an insert after whatever previous pks have been found. Its important to do these in order.
columnDescriptions = append(columnDescriptions, db.ColumnDescription{})
copy(columnDescriptions[pkCount+1:], columnDescriptions[pkCount:])
columnDescriptions[pkCount] = cd
pkCount++
} else {
columnDescriptions = append(columnDescriptions, cd)
}
}
td := db.TableDescription{
Name: t.name,
Columns: columnDescriptions,
}
var ok bool
if opt := t.options["literalName"]; opt != nil {
if td.LiteralName, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ": literalName is not a string")
}
delete(t.options, "literalName")
}
if opt := t.options["literalPlural"]; opt != nil {
if td.LiteralPlural, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ": literalPlural is not a string")
}
delete(t.options, "literalPlural")
}
if opt := t.options["goName"]; opt != nil {
if td.GoName, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ": goName is not a string")
} else {
td.GoName = strings.Title(td.GoName)
}
delete(t.options, "goName")
}
if opt := t.options["goPlural"]; opt != nil {
if td.GoPlural, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ": goPlural is not a string")
} else {
td.GoPlural = strings.Title(td.GoPlural)
}
delete(t.options, "goPlural")
}
td.Comment = t.comment
td.Options = t.options
// Build the indexes
indexes := make(map[string]*db.IndexDescription)
for _,idx := range t.indexes {
/*if idx.name == "PRIMARY" {
continue // assume primary keys are always indexed, so we don't need to report this
}*/
if i, ok2 := indexes[idx.name]; ok2 {
i.ColumnNames = append(i.ColumnNames, idx.columnName)
sort.Strings(i.ColumnNames) // make sure this list stays in a predictable order each time
} else {
i = &db.IndexDescription{IsUnique: !idx.nonUnique, ColumnNames: []string{idx.columnName}}
indexes[idx.name] = i
}
}
stringmap.Range(indexes, func(key string, val interface {}) bool {
td.Indexes = append(td.Indexes, *(val.(*db.IndexDescription)))
return true
})
return td
}
func (m *DB) getTypeTableDescription(t mysqlTable) db.TableDescription {
td := m.getTableDescription(t)
var columnNames []string
var columnTypes []GoColumnType
for _, c := range td.Columns {
columnNames = append(columnNames, c.Name)
colType := ColTypeFromGoTypeString(c.GoType)
columnTypes = append(columnTypes, colType)
}
result, err := m.SqlDb().Query(`
SELECT ` +
"`" + strings.Join(columnNames, "`,`") + "`" +
`
FROM ` +
"`" + td.Name + "`" +
` ORDER BY ` + "`" + columnNames[0] + "`")
if err != nil {
log.Fatal(err)
}
values := sql2.SqlReceiveRows(result, columnTypes, columnNames, nil)
td.TypeData = values
return td
}
func (m *DB) getColumnDescription(table mysqlTable, column mysqlColumn) db.ColumnDescription {
cd := db.ColumnDescription{
Name: column.name,
}
var ok bool
var shouldAutoUpdate bool
if opt := column.options["goName"]; opt != nil {
if cd.GoName, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + table.name + ":" + column.name + ": goName is not a string")
}
delete(column.options,"goName")
}
if opt := column.options["shouldAutoUpdate"]; opt != nil {
if shouldAutoUpdate, ok = opt.(bool); !ok {
log.Print("Error in table comment for table " + table.name + ":" + column.name + ": shouldAutoUpdate is not a boolean")
}
delete(column.options,"shouldAutoUpdate")
}
m.processTypeInfo(table.name, column, &cd)
cd.IsId = strings.Contains(column.extra, "auto_increment")
cd.IsPk = column.key == "PRI"
cd.IsNullable = column.isNullable == "YES"
cd.IsUnique = (column.key == "UNI") || cd.IsPk
// indicates that the database is handling update on modify
// In MySQL this is detectable. In other databases, if you can set this up, but its hard to detect, you can create a comment property to spec this
if strings.Contains(column.extra, "CURRENT_TIMESTAMP") {
cd.SubType = "auto timestamp"
}
if cd.SubType == "auto timestamp" && shouldAutoUpdate {
log.Print("Error in table comment for table " + table.name + ":" + column.name + ": shouldAutoUpdate should not be set on a table that the database is automatically updating.")
}
cd.Comment = column.comment
cd.Options = column.options
if fk, ok2 := table.fkMap[cd.Name]; ok2 {
cd.ForeignKey = &db.ForeignKeyDescription{
ReferencedTable: fk.referencedTableName.String,
ReferencedColumn: fk.referencedColumnName.String,
UpdateAction: sql2.FkRuleToAction(fk.updateRule).String(),
DeleteAction: sql2.FkRuleToAction(fk.deleteRule).String(),
}
}
return cd
}
func (m *DB) getManyManyDescription(t mysqlTable) (mm db.ManyManyDescription, ok bool) {
td := m.getTableDescription(t)
if len(td.Columns) != 2 {
log.Print("Error: table " + td.Name + " must have only 2 primary key columns.")
return
}
var typeIndex = -1
for i, cd := range td.Columns {
if !cd.IsPk {
log.Print("Error: table " + td.Name + ":" + cd.Name + " must be a primary key.")
return
}
if cd.ForeignKey == nil {
log.Print("Error: table " + td.Name + ":" + cd.Name + " must be a foreign key.")
return
}
if cd.IsNullable {
log.Print("Error: table " + td.Name + ":" + cd.Name + " cannot be nullable.")
return
}
if strings2.EndsWith(cd.ForeignKey.ReferencedTable, m.TypeTableSuffix()) {
if typeIndex != -1 {
log.Print("Error: table " + td.Name + ":" + " cannot have two foreign keys to type tables.")
return
}
typeIndex = i
}
}
idx1 := 0
idx2 := 1
if typeIndex == 0 {
idx1 = 1
idx2 = 0
}
options,_,_ := sql2.ExtractOptions(t.columns[idx1].comment)
mm.Table1 = td.Columns[idx1].ForeignKey.ReferencedTable
mm.Column1 = td.Columns[idx1].Name
if opt := options["goName"]; opt != nil {
if mm.GoName1, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ":" + t.columns[idx1].name + ": goName is not a string")
return
}
}
if opt := options["goPlural"]; opt != nil {
if mm.GoPlural1, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ":" + t.columns[idx1].name + ": goPlural is not a string")
return
}
}
options,_,_ = sql2.ExtractOptions(t.columns[idx2].comment)
mm.Table2 = td.Columns[idx2].ForeignKey.ReferencedTable
mm.Column2 = td.Columns[idx2].Name
if opt := options["goName"]; opt != nil {
if mm.GoName2, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ":" + t.columns[idx2].name + ": goName is not a string")
return
}
}
if opt := options["goPlural"]; opt != nil {
if mm.GoPlural2, ok = opt.(string); !ok {
log.Print("Error in table comment for table " + t.name + ":" + t.columns[idx2].name + ": goPlural is not a string")
return
}
}
mm.AssnTableName = t.name
ok = true
return
}