-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysql_flavor.go
709 lines (590 loc) · 19.4 KB
/
mysql_flavor.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
package sqac
import (
"fmt"
"log"
"reflect"
"strconv"
"strings"
"github.com/1414C/sqac/common"
)
// MySQLFlavor is a MySQL-specific implementation.
// Methods defined in the PublicDB interface of struct-type
// BaseFlavor are called by default for MySQLFlavor. If
// the method as it exists in the BaseFlavor implementation
// is not compatible with the schema-syntax required by
// MySQL, the method in question may be overridden.
// Overriding (redefining) a BaseFlavor method may be
// accomplished through the addition of a matching method
// signature and implementation on the MySQLFlavor
// struct-type.
type MySQLFlavor struct {
BaseFlavor
//================================================================
// possible local MySQL-specific overrides
//================================================================
// GetDBDriverName() string
// CreateTables(i ...interface{}) error
// DropTables(i ...interface{}) error
// AlterTables(i ...interface{}) error
// ExistsTable(i interface{}) bool
// ExistsColumn(tn string, cn string, ct string) bool
// CreateIndex(tn string, in string) error
// DropIndex(tn string, in string) error
// ExistsIndex(tn string, in string) bool
// CreateSequence(sn string, start string) error
// DropSequence(sn string) error
// ExistsSequence(sn string) bool
}
// createTables creates tables on the postgres database referenced
// by pf.DB. This internally visible version is able to defer
// foreign-key creation if called with calledFromAlter = true.
func (myf *MySQLFlavor) createTables(calledFromAlter bool, i ...interface{}) ([]ForeignKeyBuffer, error) {
var tc TblComponents
fkBuffer := make([]ForeignKeyBuffer, 0)
// get the list of table Model{}s
di := i[0].([]interface{})
for t, ent := range di {
ftr := reflect.TypeOf(ent)
if myf.log {
log.Println("CreateTable() entity type:", ftr)
}
// determine the table name
tn := common.GetTableName(di[t])
if tn == "" {
return nil, fmt.Errorf("unable to determine table name in myf.createTables")
}
// if the table is found to exist, skip the creation
// and move on to the next table in the list.
if myf.ExistsTable(tn) {
if myf.log {
log.Printf("createTable - table %s exists - skipping...\n", tn)
}
continue
}
// build the create table schema and return all of the table info
tc = myf.buildTablSchema(tn, di[t])
myf.QsLog(tc.tblSchema)
// create the table on the db
myf.db.MustExec(tc.tblSchema)
for _, sq := range tc.seq {
start, _ := strconv.Atoi(sq.Value)
myf.AlterSequenceStart(sq.Name, start)
}
// create the table indices
for k, in := range tc.ind {
myf.CreateIndex(k, in)
}
// add foreign-key information to the buffer
for _, v := range tc.fkey {
fkv := ForeignKeyBuffer{
ent: ent,
fkinfo: v,
}
fkBuffer = append(fkBuffer, fkv)
}
}
// create the foreign-keys if any and if flag 'calledFromAlter = false'
// attempt to create the foreign-key, but maybe do not hit a hard-fail
// if FK creation fails. When called from within AlterTable, creation
// of new tables in the list is carried out first - by this method. It
// is possbile that a column required by for new foreign-key has yet to
// be added to one of the tables pending alteration. A soft failure
// for FK creation issues seems approriate here, and the data for the
// failed FK creation is added to the fkBuffer and passed back to the
// called (AlterTable), where the FK creation can be tried again
// following the completion of the table alterations.
if calledFromAlter == false {
for _, v := range fkBuffer {
err := myf.CreateForeignKey(v.ent, v.fkinfo.FromTable, v.fkinfo.RefTable, v.fkinfo.FromField, v.fkinfo.RefField)
if err != nil {
log.Printf("CreateForeignKey failed. got: %v", err)
return nil, err
}
}
} else {
return fkBuffer, nil // fkBuffer will always be !nil, but may be len==0
}
return nil, nil
}
// buildTableSchema builds a CREATE TABLE schema for the MySQL DB (MariaDB),
// and returns it to the caller, along with the components determined from
// the db and sqac struct-tags. this method is used in CreateTables
// and AlterTables methods.
func (myf *MySQLFlavor) buildTablSchema(tn string, ent interface{}) TblComponents {
qt := myf.GetDBQuote()
pKeys := ""
var sequences []common.SqacPair
indexes := make(map[string]IndexInfo)
fKeys := make([]FKeyInfo, 0)
tableSchema := "CREATE TABLE " + qt + tn + qt + "("
// get a list of the field names, go-types and db attributes.
// TagReader is a common function across db-flavors. For
// this reason, the db-specific-data-type for each field
// is determined locally.
fldef, err := common.TagReader(ent, nil)
if err != nil {
panic(err)
}
// set the MySQL field-types and build the table schema,
// as well as any other schemas that are needed to support
// the table definition. In all cases any foreign-key or
// index requirements must be deferred until all other
// artifacts have been created successfully.
// https://mariadb.com/kb/en/library/data-types/
// future: https://dev.mysql.com/doc/refman/5.7/en/spatial-extensions.html
for idx, fd := range fldef {
var col ColComponents
col.fName = fd.FName
col.fType = ""
col.fPrimaryKey = ""
col.fDefault = ""
col.fNullable = ""
// https://stackoverflow.com/questions/168736/how-do-you-set-a-default-value-for-a-mysql-datetime-column
// if the field has been marked as NoDB, continue with the next field
if fd.NoDB == true {
continue
}
switch fd.UnderGoType { //fd.GoType {
case "int", "int16", "int32", "rune":
col.fType = "int"
case "int64":
col.fType = "bigint"
case "int8":
col.fType = "tinyint"
case "uint", "uint16", "uint32":
col.fType = "int unsigned"
case "uint64":
col.fType = "bigint unsigned"
case "uint8", "byte":
col.fType = "tinyint"
case "float32", "float64":
col.fType = "double"
case "bool":
col.fType = "boolean" // or tinyint(1)?
case "string":
col.fType = "varchar(255)" //
case "time.Time":
col.fType = "timestamp"
default:
err := fmt.Errorf("go type %s is not presently supported", fldef[idx].FType)
panic(err)
}
fldef[idx].FType = col.fType
// read sqac tag pairs and apply
seqName := ""
if !strings.Contains(fd.GoType, "*time.Time") {
for _, p := range fd.SqacPairs {
switch p.Name {
case "primary_key":
col.fPrimaryKey = "PRIMARY KEY"
pKeys = pKeys + " " + qt + fd.FName + qt + ","
if p.Value == "inc" {
// warn that user-specified db_type type will be ignored
if col.uType != "" {
log.Printf("WARNING: %s auto-incrementing primary-key field %s has user-specified db_type: %s user-type is ignored. \n", common.GetTableName(ent), col.fName, col.uType)
col.uType = ""
}
col.fAutoInc = true
}
case "start":
start, err := strconv.Atoi(p.Value)
if err != nil {
panic(err)
}
if seqName == "" && start > 0 {
seqName = tn
sequences = append(sequences, common.SqacPair{Name: seqName, Value: p.Value})
}
case "default":
if fd.UnderGoType == "string" {
col.fDefault = "DEFAULT '" + p.Value + "'"
} else {
col.fDefault = "DEFAULT " + p.Value
}
if fd.UnderGoType == "time.Time" && p.Value == "eot()" {
p.Value = "TIMESTAMP('2038-01-09 03:14:07')"
col.fDefault = "DEFAULT " + p.Value
}
case "constraint":
if p.Value == "unique" {
col.fUniqueConstraint = "UNIQUE"
}
case "nullable":
if p.Value == "false" {
col.fNullable = "NOT NULL"
}
case "index":
switch p.Value {
case "non-unique":
indexes = myf.processIndexTag(indexes, tn, fd.FName, "idx_", false, true)
case "unique":
indexes = myf.processIndexTag(indexes, tn, fd.FName, "idx_", true, true)
default:
indexes = myf.processIndexTag(indexes, tn, fd.FName, p.Value, false, false)
}
case "fkey":
fKeys = myf.processFKeyTag(fKeys, tn, fd.FName, p.Value)
default:
}
}
} else { // *time.Time only supports default directive
for _, p := range fd.SqacPairs {
if p.Name == "default" {
if p.Value == "eot()" {
// maximum mysql ts - consider using DATETIME,
// although DT use would not be consistent with
// the other db dialects in sqac.
p.Value = "TIMESTAMP('2038-01-09 03:14:07')"
}
col.fDefault = "DEFAULT " + p.Value
}
}
}
fldef[idx].FType = col.fType
// add the current column to the schema
if col.uType != "" {
tableSchema = tableSchema + qt + col.fName + qt + " " + col.uType
} else {
tableSchema = tableSchema + qt + col.fName + qt + " " + col.fType
}
if col.fAutoInc == true {
tableSchema = tableSchema + " AUTO_INCREMENT"
}
if col.fNullable != "" {
tableSchema = tableSchema + " " + col.fNullable
}
if col.fDefault != "" {
tableSchema = tableSchema + " " + col.fDefault
}
if col.fUniqueConstraint != "" {
tableSchema = tableSchema + " " + col.fUniqueConstraint
}
tableSchema = tableSchema + ", "
}
if tableSchema != "" && pKeys == "" {
tableSchema = strings.TrimSpace(tableSchema)
tableSchema = strings.TrimSuffix(tableSchema, ",")
tableSchema = tableSchema + ")"
}
if tableSchema != "" && pKeys != "" {
pKeys = strings.TrimSuffix(pKeys, ",")
tableSchema = tableSchema + "PRIMARY KEY (" + pKeys + ") )"
}
tableSchema = tableSchema + " ENGINE=InnoDB DEFAULT CHARSET=latin1;"
// fill the return structure passing out the CREATE TABLE schema, and component info
rc := TblComponents{
tblSchema: tableSchema,
flDef: fldef,
seq: sequences,
ind: indexes,
fkey: fKeys,
pk: pKeys,
err: err,
}
if myf.log {
rc.Log()
}
return rc
}
// CreateTables creates tables on the mysql database referenced
// by myf.DB.
func (myf *MySQLFlavor) CreateTables(i ...interface{}) error {
// call createTables specifying that the call has not originated
// from within the AlterTables(...) method.
_, err := myf.createTables(false, i)
if err != nil {
return err
}
return nil
}
// AlterTables alters tables on the MySQL database referenced
// by myf.DB.
func (myf *MySQLFlavor) AlterTables(i ...interface{}) error {
var err error
fkBuffer := make([]ForeignKeyBuffer, 0)
ci := make([]interface{}, 0)
ai := make([]interface{}, 0)
// construct create-table and alter-table buffers
for t := range i {
// determine the table name
tn := common.GetTableName(i[t])
if tn == "" {
return fmt.Errorf("unable to determine table name in pf.AlterTables")
}
// if the table does not exist, add the Model{} definition to
// the CreateTables buffer (ci).
// if the table does exist, add the Model{} definition to the
// AlterTables buffer (ai).
if !myf.ExistsTable(tn) {
ci = append(ci, i[t])
} else {
ai = append(ai, i[t])
}
}
// if create-tables buffer 'ci' contains any entries, call createTables and
// take note of any returned foreign-key definitions.
if len(ci) > 0 {
fkBuffer, err = myf.createTables(true, ci)
if err != nil {
return err
}
}
// if alter-tables buffer 'ai' constains any entries, process the table
// deltas and take note of any new foreign-key definitions.
for t, ent := range ai {
// determine the table name
tn := common.GetTableName(ai[t])
if tn == "" {
return fmt.Errorf("unable to determine table name in myf.AlterTables")
}
// build the alter-table schema and get its components
tc := myf.buildTablSchema(tn, ai[t])
// go through the latest version of the model and check each
// field against its definition in the database.
qt := myf.GetDBQuote()
alterSchema := "ALTER TABLE " + qt + tn + qt
var cols []string
for _, fd := range tc.flDef {
// new columns first
if !myf.ExistsColumn(tn, fd.FName) && fd.NoDB == false {
colSchema := "ADD COLUMN " + qt + fd.FName + qt + " " + fd.FType
for _, p := range fd.SqacPairs {
switch p.Name {
case "primary_key":
// abort - adding primary key
panic(fmt.Errorf("aborting - cannot add a primary-key (table-field %s-%s) through migration", tn, fd.FName))
case "default":
if fd.UnderGoType == "string" {
colSchema = colSchema + " DEFAULT '" + p.Value + "'"
} else {
colSchema = colSchema + " DEFAULT " + p.Value
}
case "nullable":
if p.Value == "false" {
colSchema = colSchema + " NOT NULL"
}
default:
}
}
cols = append(cols, colSchema+",")
}
}
// ALTER TABLE ADD COLUMNS...
if len(cols) > 0 {
for _, c := range cols {
alterSchema = alterSchema + " " + c
}
alterSchema = strings.TrimSuffix(alterSchema, ",")
myf.ProcessSchema(alterSchema)
}
// add indexes if required
for k, v := range tc.ind {
if !myf.ExistsIndex(v.TableName, k) {
myf.CreateIndex(k, v)
}
}
// add to the list of foreign-keys
for _, v := range tc.fkey {
fkb := ForeignKeyBuffer{
ent: ent,
fkinfo: v,
}
fkBuffer = append(fkBuffer, fkb)
}
}
// all table alterations and creations have been completed at this point, with the
// exception of the foreign-key creations. iterate over the fkBuffer, check for
// the existence of each foreign-key and create those that do not yet exist.
for _, v := range fkBuffer {
fkn, err := common.GetFKeyName(v.ent, v.fkinfo.FromTable, v.fkinfo.RefTable, v.fkinfo.FromField, v.fkinfo.RefField)
if err != nil {
return err
}
fkExists, _ := myf.ExistsForeignKeyByName(v.ent, fkn)
if !fkExists {
err = myf.CreateForeignKey(v.ent, v.fkinfo.FromTable, v.fkinfo.RefTable, v.fkinfo.FromField, v.fkinfo.RefField)
if err != nil {
log.Println(err)
return err
}
}
}
return nil
}
// DropIndex drops the specfied index on the connected database.
func (myf *MySQLFlavor) DropIndex(tn string, in string) error {
if myf.ExistsIndex(tn, in) {
indexSchema := "DROP INDEX " + in + " ON " + tn + ";"
myf.ProcessSchema(indexSchema)
return nil
}
return nil
}
// DestructiveResetTables drops tables on the MySQL db if they exist,
// as well as any related objects such as sequences. this is
// useful if you wish to regenerated your table and the
// number-range used by an auto-incementing primary key.
func (myf *MySQLFlavor) DestructiveResetTables(i ...interface{}) error {
err := myf.DropTables(i...)
if err != nil {
return err
}
err = myf.CreateTables(i...)
if err != nil {
return err
}
return nil
}
// AlterSequenceStart may be used to make changes to the start value
// of the named auto_increment field in the MySQL database. Note
// that this is intended to deal with auto-incrementing primary
// keys only. It is possible in MySQL to setup a non-primary-key
// field as auto_increment as follows:
//
// ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);
//
// This is not presently supported.
func (myf *MySQLFlavor) AlterSequenceStart(name string, start int) error {
// ALTER TABLE users AUTO_INCREMENT=1001;
alterSequenceSchema := " ALTER TABLE " + name + " AUTO_INCREMENT=" + strconv.Itoa(start) + ";"
myf.ProcessSchema(alterSequenceSchema)
return nil
}
// GetNextSequenceValue is used primarily for testing. It returns
// the current value of the MySQL auto-increment field for the named
// table.
func (myf *MySQLFlavor) GetNextSequenceValue(name string) (int, error) {
seq := 0
if myf.ExistsTable(name) {
seqQuery := "SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + myf.GetDBName() + "' AND TABLE_NAME = '" + name + "';"
myf.QsLog(seqQuery)
err := myf.db.QueryRow(seqQuery).Scan(&seq)
if err != nil {
return 0, err
}
return seq, nil
}
return seq, nil
}
// DropForeignKey drops a foreign-key on an existing column
func (myf *MySQLFlavor) DropForeignKey(i interface{}, ft, fkn string) error {
// mysql: SELECT COUNT(*) FROM information_schema.table_constraints WHERE constraint_name='user__fk__store_id' AND table_name='client';
schema := "ALTER TABLE " + ft + " DROP FOREIGN KEY " + fkn
myf.QsLog(schema)
_, err := myf.Exec(schema)
if err != nil {
return err
}
return nil
}
// ExistsForeignKeyByName checks to see if the named foreign-key exists on the
// table corresponding to provided sqac model (i).
func (myf *MySQLFlavor) ExistsForeignKeyByName(i interface{}, fkn string) (bool, error) {
var count uint64
tn := common.GetTableName(i)
fkQuery := "SELECT COUNT(*) FROM information_schema.table_constraints WHERE constraint_name='" + fkn + "' AND table_name='" + tn + "';"
myf.QsLog(fkQuery)
err := myf.Get(&count, fkQuery)
if err != nil {
return false, nil
}
if count > 0 {
return true, nil
}
return false, nil
}
// ExistsForeignKeyByFields checks to see if a foreign-key exists between the named
// tables and fields.
func (myf *MySQLFlavor) ExistsForeignKeyByFields(i interface{}, ft, rt, ff, rf string) (bool, error) {
fkn, err := common.GetFKeyName(i, ft, rt, ff, rf)
if err != nil {
return false, err
}
return myf.ExistsForeignKeyByName(i, fkn)
}
//================================================================
// CRUD ops
//================================================================
// Create the entity (single-row) on the database
func (myf *MySQLFlavor) Create(ent interface{}) error {
var info CrudInfo
info.ent = ent
info.log = false
info.mode = "C"
err := myf.BuildComponents(&info)
if err != nil {
return err
}
// build the mysql insert query
insQuery := "INSERT INTO " + info.tn + " " + info.fList + " VALUES " + info.vList + ";"
myf.QsLog(insQuery)
// clear the source data - deals with non-persistet columns
e := reflect.ValueOf(info.ent).Elem()
e.Set(reflect.Zero(e.Type()))
// attempt the insert and read the result back into info.resultMap
result, err := myf.db.Exec(insQuery)
if err != nil {
return err
}
lastID, err := result.LastInsertId()
if err != nil {
return err
}
selQuery := "SELECT * FROM " + info.tn + " WHERE " + info.incKeyName + " = " + strconv.FormatInt(lastID, 10) + " LIMIT 1;"
myf.QsLog(selQuery)
err = myf.db.QueryRowx(selQuery).StructScan(info.ent) // .MapScan(info.resultMap) // SliceScan
if err != nil {
return err
}
info.entValue = reflect.ValueOf(info.ent)
return nil
}
// Update an existing entity (single-row) on the database
func (myf *MySQLFlavor) Update(ent interface{}) error {
var info CrudInfo
info.ent = ent
info.log = false
info.mode = "U"
err := myf.BuildComponents(&info)
if err != nil {
return err
}
keyList := ""
for k, s := range info.keyMap {
fType := reflect.TypeOf(s).String()
if myf.IsLog() {
log.Printf("CRUD UPDATE key: %v, value: %v\n", k, s)
log.Println("CRUD UPDATED TYPE:", fType)
}
if fType == "string" {
keyList = fmt.Sprintf("%s %s = '%v' AND", keyList, k, s)
} else {
keyList = fmt.Sprintf("%s %s = %v AND", keyList, k, s)
}
}
keyList = strings.TrimSuffix(keyList, " AND")
colList := ""
for k, v := range info.fldMap {
colList = fmt.Sprintf("%s %s = %s, ", colList, k, v)
}
colList = strings.TrimSuffix(colList, ", ")
updQuery := "UPDATE " + info.tn + " SET " + colList + " WHERE " + keyList + ";"
myf.QsLog(updQuery)
// clear the source data - deals with non-persistet columns
e := reflect.ValueOf(info.ent).Elem()
e.Set(reflect.Zero(e.Type()))
// attempt the update and check for errors
_, err = myf.db.Exec(updQuery)
if err != nil {
return err
}
// read the updated row
selQuery := "SELECT * FROM " + info.tn + " WHERE " + keyList + " LIMIT 1;"
myf.QsLog(selQuery)
err = myf.db.QueryRowx(selQuery).StructScan(info.ent) // .MapScan(info.resultMap) // SliceScan
if err != nil {
return err
}
info.entValue = reflect.ValueOf(info.ent)
return nil
}