-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstatement.go
4345 lines (3853 loc) · 106 KB
/
statement.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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package leopards
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
// Dialect names for external usage.
const (
MySQL = "mysql"
SQLite = "sqlite3"
Postgres = "postgres"
Gremlin = "gremlin"
)
// Querier wraps the basic Query method that is implemented
// by the different builders in this file.
type Querier interface {
// query returns the query representation of the element
// and its arguments (if any).
query() (string, []any)
}
// querierErr allowed propagate Querier's inner error
type querierErr interface {
Err() error
}
// ColumnBuilder is a builder for column definition in table creation.
type ColumnBuilder struct {
Builder
typ string // column type.
name string // column name.
attr string // extra attributes.
modify bool // modify existing.
fk *ForeignKeyBuilder // foreign-key constraint.
check func(*Builder) // column checks.
}
// Column returns a new ColumnBuilder with the given name.
//
// sql.Column("group_id").Type("int").Attr("UNIQUE")
func Column(name string) *ColumnBuilder { return &ColumnBuilder{name: name} }
// Type sets the column type.
func (c *ColumnBuilder) Type(t string) *ColumnBuilder {
c.typ = t
return c
}
// Attr sets an extra attribute for the column, like UNIQUE or AUTO_INCREMENT.
func (c *ColumnBuilder) Attr(attr string) *ColumnBuilder {
if c.attr != "" && attr != "" {
c.attr += " "
}
c.attr += attr
return c
}
// Constraint adds the CONSTRAINT clause to the ADD COLUMN statement in SQLite.
func (c *ColumnBuilder) Constraint(fk *ForeignKeyBuilder) *ColumnBuilder {
c.fk = fk
return c
}
// Check adds a CHECK clause to the ADD COLUMN statement.
func (c *ColumnBuilder) Check(check func(*Builder)) *ColumnBuilder {
c.check = check
return c
}
// Query returns query representation of a Column.
func (c *ColumnBuilder) query() (string, []any) {
c.Ident(c.name)
if c.typ != "" {
if c.postgres() && c.modify {
c.WriteString(" TYPE")
}
c.Pad().WriteString(c.typ)
}
if c.attr != "" {
c.Pad().WriteString(c.attr)
}
if c.fk != nil {
c.WriteString(" CONSTRAINT " + c.fk.symbol)
c.Pad().Join(c.fk.ref)
for _, action := range c.fk.actions {
c.Pad().WriteString(action)
}
}
if c.check != nil {
c.WriteString(" CHECK ")
c.Wrap(c.check)
}
return c.String(), c.args
}
// TableBuilder is a query builder for `CREATE TABLE` statement.
type TableBuilder struct {
Builder
name string // table name.
exists bool // check existence.
charset string // table charset.
collation string // table collation.
options string // table options.
columns []Querier // table columns.
primary []string // primary key.
constraints []Querier // foreign keys and indices.
checks []func(*Builder) // check constraints.
}
// CreateTable returns a query builder for the `CREATE TABLE` statement.
//
// CreateTable("users").
// Columns(
// Column("id").Type("int").Attr("auto_increment"),
// Column("name").Type("varchar(255)"),
// ).
// PrimaryKey("id")
func CreateTable(name string) *TableBuilder { return &TableBuilder{name: name} }
// IfNotExists appends the `IF NOT EXISTS` clause to the `CREATE TABLE` statement.
func (t *TableBuilder) IfNotExists() *TableBuilder {
t.exists = true
return t
}
// Column appends the given column to the `CREATE TABLE` statement.
func (t *TableBuilder) Column(c *ColumnBuilder) *TableBuilder {
t.columns = append(t.columns, c)
return t
}
// Columns appends a list of columns to the builder.
func (t *TableBuilder) Columns(columns ...*ColumnBuilder) *TableBuilder {
t.columns = make([]Querier, 0, len(columns))
for i := range columns {
t.columns = append(t.columns, columns[i])
}
return t
}
// PrimaryKey adds a column to the primary-key constraint in the statement.
func (t *TableBuilder) PrimaryKey(column ...string) *TableBuilder {
t.primary = append(t.primary, column...)
return t
}
// ForeignKeys adds a list of foreign-keys to the statement (without constraints).
func (t *TableBuilder) ForeignKeys(fks ...*ForeignKeyBuilder) *TableBuilder {
queries := make([]Querier, len(fks))
for i := range fks {
// Erase the constraint symbol/name.
fks[i].symbol = ""
queries[i] = fks[i]
}
t.constraints = append(t.constraints, queries...)
return t
}
// Constraints adds a list of foreign-key constraints to the statement.
func (t *TableBuilder) Constraints(fks ...*ForeignKeyBuilder) *TableBuilder {
queries := make([]Querier, len(fks))
for i := range fks {
queries[i] = &Wrapper{"CONSTRAINT %s", fks[i]}
}
t.constraints = append(t.constraints, queries...)
return t
}
// Checks adds CHECK clauses to the CREATE TABLE statement.
func (t *TableBuilder) Checks(checks ...func(*Builder)) *TableBuilder {
t.checks = append(t.checks, checks...)
return t
}
// Charset appends the `CHARACTER SET` clause to the statement. MySQL only.
func (t *TableBuilder) Charset(s string) *TableBuilder {
t.charset = s
return t
}
// Collate appends the `COLLATE` clause to the statement. MySQL only.
func (t *TableBuilder) Collate(s string) *TableBuilder {
t.collation = s
return t
}
// Options appends additional options to the statement (MySQL only).
func (t *TableBuilder) Options(s string) *TableBuilder {
t.options = s
return t
}
// query returns query representation of a `CREATE TABLE` statement.
//
// CREATE TABLE [IF NOT EXISTS] name
//
// (table definition)
// [charset and collation]
func (t *TableBuilder) query() (string, []any) {
t.WriteString("CREATE TABLE ")
if t.exists {
t.WriteString("IF NOT EXISTS ")
}
t.Ident(t.name)
t.Wrap(func(b *Builder) {
b.JoinComma(t.columns...)
if len(t.primary) > 0 {
b.Comma().WriteString("PRIMARY KEY")
b.Wrap(func(b *Builder) {
b.IdentComma(t.primary...)
})
}
if len(t.constraints) > 0 {
b.Comma().JoinComma(t.constraints...)
}
for _, check := range t.checks {
check(b.Comma())
}
})
if t.charset != "" {
t.WriteString(" CHARACTER SET " + t.charset)
}
if t.collation != "" {
t.WriteString(" COLLATE " + t.collation)
}
if t.options != "" {
t.WriteString(" " + t.options)
}
return t.String(), t.args
}
// DescribeBuilder is a query builder for `DESCRIBE` statement.
type DescribeBuilder struct {
Builder
name string // table name.
}
// Describe returns a query builder for the `DESCRIBE` statement.
//
// Describe("users")
func Describe(name string) *DescribeBuilder { return &DescribeBuilder{name: name} }
// query returns query representation of a `DESCRIBE` statement.
func (t *DescribeBuilder) query() (string, []any) {
t.WriteString("DESCRIBE ")
t.Ident(t.name)
return t.String(), nil
}
// TableAlter is a query builder for `ALTER TABLE` statement.
type TableAlter struct {
Builder
name string // table to alter.
Queries []Querier // columns and foreign-keys to add.
}
// AlterTable returns a query builder for the `ALTER TABLE` statement.
//
// AlterTable("users").
// AddColumn(Column("group_id").Type("int").Attr("UNIQUE")).
// AddForeignKey(ForeignKey().Columns("group_id").
// Reference(Reference().Table("groups").Columns("id")).OnDelete("CASCADE")),
// )
func AlterTable(name string) *TableAlter { return &TableAlter{name: name} }
// AddColumn appends the `ADD COLUMN` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) AddColumn(c *ColumnBuilder) *TableAlter {
t.Queries = append(t.Queries, &Wrapper{"ADD COLUMN %s", c})
return t
}
// ModifyColumn appends the `MODIFY/ALTER COLUMN` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) ModifyColumn(c *ColumnBuilder) *TableAlter {
switch {
case t.postgres():
c.modify = true
t.Queries = append(t.Queries, &Wrapper{"ALTER COLUMN %s", c})
default:
t.Queries = append(t.Queries, &Wrapper{"MODIFY COLUMN %s", c})
}
return t
}
// RenameColumn appends the `RENAME COLUMN` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) RenameColumn(old, new string) *TableAlter {
t.Queries = append(t.Queries, Raw(fmt.Sprintf("RENAME COLUMN %s TO %s", t.Quote(old), t.Quote(new))))
return t
}
// ModifyColumns calls ModifyColumn with each of the given builders.
func (t *TableAlter) ModifyColumns(cs ...*ColumnBuilder) *TableAlter {
for _, c := range cs {
t.ModifyColumn(c)
}
return t
}
// DropColumn appends the `DROP COLUMN` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) DropColumn(c *ColumnBuilder) *TableAlter {
t.Queries = append(t.Queries, &Wrapper{"DROP COLUMN %s", c})
return t
}
// ChangeColumn appends the `CHANGE COLUMN` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) ChangeColumn(name string, c *ColumnBuilder) *TableAlter {
prefix := fmt.Sprintf("CHANGE COLUMN %s", t.Quote(name))
t.Queries = append(t.Queries, &Wrapper{prefix + " %s", c})
return t
}
// RenameIndex appends the `RENAME INDEX` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) RenameIndex(curr, new string) *TableAlter {
t.Queries = append(t.Queries, Raw(fmt.Sprintf("RENAME INDEX %s TO %s", t.Quote(curr), t.Quote(new))))
return t
}
// DropIndex appends the `DROP INDEX` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) DropIndex(name string) *TableAlter {
t.Queries = append(t.Queries, Raw(fmt.Sprintf("DROP INDEX %s", t.Quote(name))))
return t
}
// AddIndex appends the `ADD INDEX` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) AddIndex(idx *IndexBuilder) *TableAlter {
b := &Builder{dialect: t.dialect}
b.WriteString("ADD ")
if idx.unique {
b.WriteString("UNIQUE ")
}
b.WriteString("INDEX ")
b.Ident(idx.name)
b.Wrap(func(b *Builder) {
b.IdentComma(idx.columns...)
})
t.Queries = append(t.Queries, b)
return t
}
// AddForeignKey adds a foreign key constraint to the `ALTER TABLE` statement.
func (t *TableAlter) AddForeignKey(fk *ForeignKeyBuilder) *TableAlter {
t.Queries = append(t.Queries, &Wrapper{"ADD CONSTRAINT %s", fk})
return t
}
// DropConstraint appends the `DROP CONSTRAINT` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) DropConstraint(ident string) *TableAlter {
t.Queries = append(t.Queries, Raw(fmt.Sprintf("DROP CONSTRAINT %s", t.Quote(ident))))
return t
}
// DropForeignKey appends the `DROP FOREIGN KEY` clause to the given `ALTER TABLE` statement.
func (t *TableAlter) DropForeignKey(ident string) *TableAlter {
t.Queries = append(t.Queries, Raw(fmt.Sprintf("DROP FOREIGN KEY %s", t.Quote(ident))))
return t
}
// Query returns query representation of the `ALTER TABLE` statement.
//
// ALTER TABLE name
// [alter_specification]
func (t *TableAlter) query() (string, []any) {
t.WriteString("ALTER TABLE ")
t.Ident(t.name)
t.Pad()
t.JoinComma(t.Queries...)
return t.String(), t.args
}
// IndexAlter is a query builder for `ALTER INDEX` statement.
type IndexAlter struct {
Builder
name string // index to alter.
Queries []Querier // alter options.
}
// AlterIndex returns a query builder for the `ALTER INDEX` statement.
//
// AlterIndex("old_key").
// Rename("new_key")
func AlterIndex(name string) *IndexAlter { return &IndexAlter{name: name} }
// Rename appends the `RENAME TO` clause to the `ALTER INDEX` statement.
func (i *IndexAlter) Rename(name string) *IndexAlter {
i.Queries = append(i.Queries, Raw(fmt.Sprintf("RENAME TO %s", i.Quote(name))))
return i
}
// Query returns query representation of the `ALTER INDEX` statement.
//
// ALTER INDEX name
// [alter_specification]
func (i *IndexAlter) query() (string, []any) {
i.WriteString("ALTER INDEX ")
i.Ident(i.name)
i.Pad()
i.JoinComma(i.Queries...)
return i.String(), i.args
}
// ForeignKeyBuilder is the builder for the foreign-key constraint clause.
type ForeignKeyBuilder struct {
Builder
symbol string
columns []string
actions []string
ref *ReferenceBuilder
}
// ForeignKey returns a builder for the foreign-key constraint clause in create/alter table statements.
//
// ForeignKey().
// Columns("group_id").
// Reference(Reference().Table("groups").Columns("id")).
// OnDelete("CASCADE")
func ForeignKey(symbol ...string) *ForeignKeyBuilder {
fk := &ForeignKeyBuilder{}
if len(symbol) != 0 {
fk.symbol = symbol[0]
}
return fk
}
// Symbol sets the symbol of the foreign key.
func (fk *ForeignKeyBuilder) Symbol(s string) *ForeignKeyBuilder {
fk.symbol = s
return fk
}
// Columns sets the columns of the foreign key in the source table.
func (fk *ForeignKeyBuilder) Columns(s ...string) *ForeignKeyBuilder {
fk.columns = append(fk.columns, s...)
return fk
}
// Reference sets the reference clause.
func (fk *ForeignKeyBuilder) Reference(r *ReferenceBuilder) *ForeignKeyBuilder {
fk.ref = r
return fk
}
// OnDelete sets the on delete action for this constraint.
func (fk *ForeignKeyBuilder) OnDelete(action string) *ForeignKeyBuilder {
fk.actions = append(fk.actions, "ON DELETE "+action)
return fk
}
// OnUpdate sets the on delete action for this constraint.
func (fk *ForeignKeyBuilder) OnUpdate(action string) *ForeignKeyBuilder {
fk.actions = append(fk.actions, "ON UPDATE "+action)
return fk
}
// Query returns query representation of a foreign key constraint.
func (fk *ForeignKeyBuilder) query() (string, []any) {
if fk.symbol != "" {
fk.Ident(fk.symbol).Pad()
}
fk.WriteString("FOREIGN KEY")
fk.Wrap(func(b *Builder) {
b.IdentComma(fk.columns...)
})
fk.Pad().Join(fk.ref)
for _, action := range fk.actions {
fk.Pad().WriteString(action)
}
return fk.String(), fk.args
}
// ReferenceBuilder is a builder for the reference clause in constraints. For example, in foreign key creation.
type ReferenceBuilder struct {
Builder
table string // referenced table.
columns []string // referenced columns.
}
// Reference creates a reference builder for the reference_option clause.
//
// Reference().Table("groups").Columns("id")
func Reference() *ReferenceBuilder { return &ReferenceBuilder{} }
// Table sets the referenced table.
func (r *ReferenceBuilder) Table(s string) *ReferenceBuilder {
r.table = s
return r
}
// Columns sets the columns of the referenced table.
func (r *ReferenceBuilder) Columns(s ...string) *ReferenceBuilder {
r.columns = append(r.columns, s...)
return r
}
// Query returns query representation of a reference clause.
func (r *ReferenceBuilder) query() (string, []any) {
r.WriteString("REFERENCES ")
r.Ident(r.table)
r.Wrap(func(b *Builder) {
b.IdentComma(r.columns...)
})
return r.String(), r.args
}
// IndexBuilder is a builder for `CREATE INDEX` statement.
type IndexBuilder struct {
Builder
name string
unique bool
exists bool
table string
method string
columns []string
}
// CreateIndex creates a builder for the `CREATE INDEX` statement.
//
// CreateIndex("index_name").
// Unique().
// Table("users").
// Column("name")
//
// Or:
//
// CreateIndex("index_name").
// Unique().
// Table("users").
// Columns("name", "age")
func CreateIndex(name string) *IndexBuilder {
return &IndexBuilder{name: name}
}
// IfNotExists appends the `IF NOT EXISTS` clause to the `CREATE INDEX` statement.
func (i *IndexBuilder) IfNotExists() *IndexBuilder {
i.exists = true
return i
}
// Unique sets the index to be a unique index.
func (i *IndexBuilder) Unique() *IndexBuilder {
i.unique = true
return i
}
// Table defines the table for the index.
func (i *IndexBuilder) Table(table string) *IndexBuilder {
i.table = table
return i
}
// Using sets the method to create the index with.
func (i *IndexBuilder) Using(method string) *IndexBuilder {
i.method = method
return i
}
// Column appends a column to the column list for the index.
func (i *IndexBuilder) Column(column string) *IndexBuilder {
i.columns = append(i.columns, column)
return i
}
// Columns appends the given columns to the column list for the index.
func (i *IndexBuilder) Columns(columns ...string) *IndexBuilder {
i.columns = append(i.columns, columns...)
return i
}
// Query returns query representation of a reference clause.
func (i *IndexBuilder) query() (string, []any) {
i.WriteString("CREATE ")
if i.unique {
i.WriteString("UNIQUE ")
}
i.WriteString("INDEX ")
if i.exists {
i.WriteString("IF NOT EXISTS ")
}
i.Ident(i.name)
i.WriteString(" ON ")
i.Ident(i.table)
switch i.dialect {
case Postgres:
if i.method != "" {
i.WriteString(" USING ").Ident(i.method)
}
i.Wrap(func(b *Builder) {
b.IdentComma(i.columns...)
})
case MySQL:
i.Wrap(func(b *Builder) {
b.IdentComma(i.columns...)
})
if i.method != "" {
i.WriteString(" USING " + i.method)
}
default:
i.Wrap(func(b *Builder) {
b.IdentComma(i.columns...)
})
}
return i.String(), nil
}
// DropIndexBuilder is a builder for `DROP INDEX` statement.
type DropIndexBuilder struct {
Builder
name string
table string
}
// DropIndex creates a builder for the `DROP INDEX` statement.
//
// MySQL:
//
// DropIndex("index_name").
// Table("users").
//
// SQLite/PostgreSQL:
//
// DropIndex("index_name")
func DropIndex(name string) *DropIndexBuilder {
return &DropIndexBuilder{name: name}
}
// Table defines the table for the index.
func (d *DropIndexBuilder) Table(table string) *DropIndexBuilder {
d.table = table
return d
}
// Query returns query representation of a reference clause.
//
// DROP INDEX index_name [ON table_name]
func (d *DropIndexBuilder) query() (string, []any) {
d.WriteString("DROP INDEX ")
d.Ident(d.name)
if d.table != "" {
d.WriteString(" ON ")
d.Ident(d.table)
}
return d.String(), nil
}
// InsertBuilder is a builder for `INSERT INTO` statement.
type InsertBuilder struct {
Builder
table string
schema string
columns []string
defaults bool
returning []string
values [][]any
conflict *conflict
driver *DB
}
// Insert creates a builder for the `INSERT INTO` statement.
//
// Insert("users").
// Columns("name", "age").
// Values("a8m", 10).
// Values("foo", 20)
//
// Note: Insert inserts all values in one batch.
func (i *InsertBuilder) Save(ctx context.Context) (sql.Result, error) {
for _, iter := range i.driver.beforeInsert {
iter(i)
}
statement, args := i.query()
if i.driver.debug {
fmt.Printf("%s: %s %v\n", time.Now().Format(`2006-01-02 15:04:05`), statement, args)
}
var (
err error
res sql.Result
)
switch {
case i.driver.tx != nil:
res, err = i.driver.tx.ExecContext(ctx, statement, args...)
default:
res, err = i.driver.driver.ExecContext(ctx, statement, args...)
}
for _, iter := range i.driver.afterInsert {
iter(i, res)
}
return res, err
}
func (i *InsertBuilder) Table(table string) *InsertBuilder {
i.table = table
return i
}
// Schema sets the database name for the insert table.
func (i *InsertBuilder) Schema(name string) *InsertBuilder {
i.schema = name
return i
}
// Set is a syntactic sugar API for inserting only one row.
func (i *InsertBuilder) Set(column string, v any) *InsertBuilder {
i.columns = append(i.columns, column)
if len(i.values) == 0 {
i.values = append(i.values, []any{v})
} else {
i.values[0] = append(i.values[0], v)
}
return i
}
// StringOmitErr turn value into string
func StringOmitErr(value any) string {
v := reflect.ValueOf(value)
t := reflect.ValueOf(value)
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
switch v.Kind() {
case reflect.Map, reflect.Struct, reflect.Array, reflect.Interface:
buf, err := json.Marshal(value)
if err != nil {
return ``
}
return string(buf)
default:
return fmt.Sprintf(`%v`, value)
}
}
// SetMap is a syntactic sugar API for inserting only one row.
func (i *InsertBuilder) SetMap(kv map[string]any) *InsertBuilder {
for column, v := range kv {
i.Set(column, v)
}
return i
}
// Columns appends columns to the INSERT statement.
func (i *InsertBuilder) Columns(columns ...string) *InsertBuilder {
i.columns = append(i.columns, columns...)
return i
}
// Values append a value tuple for the insert statement.
func (i *InsertBuilder) Values(values ...any) *InsertBuilder {
i.values = append(i.values, values)
return i
}
// Default sets the default values clause based on the dialect type.
func (i *InsertBuilder) Default() *InsertBuilder {
i.defaults = true
return i
}
// Returning adds the `RETURNING` clause to the insert statement.
// Supported by SQLite and PostgreSQL.
func (i *InsertBuilder) Returning(columns ...string) *InsertBuilder {
i.returning = columns
return i
}
type (
// conflict holds the configuration for the
// `ON CONFLICT` / `ON DUPLICATE KEY` clause.
conflict struct {
target struct {
constraint string
columns []string
where *Predicate
}
action struct {
nothing bool
where *Predicate
update []func(*UpdateSet)
}
}
// ConflictOption allows configuring the
// conflict config using functional options.
ConflictOption func(*conflict)
)
// ConflictColumns sets the unique constraints that trigger the conflict
// resolution on insert to perform an upsert operation. The columns must
// have a unique constraint applied to trigger this behaviour.
//
// sql.Insert("users").
// Columns("id", "name").
// Values(1, "Mashraki").
// OnConflict(
// sql.ConflictColumns("id"),
// sql.ResolveWithNewValues(),
// )
func ConflictColumns(names ...string) ConflictOption {
return func(c *conflict) {
c.target.columns = names
}
}
// ConflictConstraint allows setting the constraint
// name (i.e. `ON CONSTRAINT <name>`) for PostgreSQL.
//
// sql.Insert("users").
// Columns("id", "name").
// Values(1, "Mashraki").
// OnConflict(
// sql.ConflictConstraint("users_pkey"),
// sql.ResolveWithNewValues(),
// )
func ConflictConstraint(name string) ConflictOption {
return func(c *conflict) {
c.target.constraint = name
}
}
// ConflictWhere allows inference of partial unique indexes. See, PostgreSQL
// doc: https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT
func ConflictWhere(p *Predicate) ConflictOption {
return func(c *conflict) {
c.target.where = p
}
}
// UpdateWhere allows setting the update condition. Only rows
// for which this expression returns true will be updated.
func UpdateWhere(p *Predicate) ConflictOption {
return func(c *conflict) {
c.action.where = p
}
}
// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported by SQLite and PostgreSQL.
//
// sql.Insert("users").
// Columns("id", "name").
// Values(1, "Mashraki").
// OnConflict(
// sql.ConflictColumns("id"),
// sql.DoNothing()
// )
func DoNothing() ConflictOption {
return func(c *conflict) {
c.action.nothing = true
}
}
// ResolveWithIgnore sets each column to itself to force an update and return the ID,
// otherwise does not change any data. This may still trigger update hooks in the database.
//
// sql.Insert("users").
// Columns("id").
// Values(1).
// OnConflict(
// sql.ConflictColumns("id"),
// sql.ResolveWithIgnore()
// )
//
// // Output:
// // MySQL: INSERT INTO `users` (`id`) VALUES(1) ON DUPLICATE KEY UPDATE `id` = `users`.`id`
// // PostgreSQL: INSERT INTO "users" ("id") VALUES(1) ON CONFLICT ("id") DO UPDATE SET "id" = "users"."id
func ResolveWithIgnore() ConflictOption {
return func(c *conflict) {
c.action.update = append(c.action.update, func(u *UpdateSet) {
for _, c := range u.columns {
u.SetIgnore(c)
}
})
}
}
// ResolveWithNewValues updates columns using the new values proposed
// for insertion using the special EXCLUDED/VALUES table.
//
// sql.Insert("users").
// Columns("id", "name").
// Values(1, "Mashraki").
// OnConflict(
// sql.ConflictColumns("id"),
// sql.ResolveWithNewValues()
// )
//
// // Output:
// // MySQL: INSERT INTO `users` (`id`, `name`) VALUES(1, 'Mashraki) ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `name` = VALUES(`name`),
// // PostgreSQL: INSERT INTO "users" ("id") VALUES(1) ON CONFLICT ("id") DO UPDATE SET "id" = "excluded"."id, "name" = "excluded"."name"
func ResolveWithNewValues() ConflictOption {
return func(c *conflict) {
c.action.update = append(c.action.update, func(u *UpdateSet) {
for _, c := range u.columns {
u.SetExcluded(c)
}
})
}
}
// ResolveWith allows setting a custom function to set the `UPDATE` clause.
//
// Insert("users").
// Columns("id", "name").
// Values(1, "Mashraki").
// OnConflict(
// ConflictColumns("name"),
// ResolveWith(func(u *UpdateSet) {
// u.SetIgnore("id")
// u.SetNull("created_at")
// u.Set("name", Expr(u.Excluded().C("name")))
// }),
// )
func ResolveWith(fn func(*UpdateSet)) ConflictOption {
return func(c *conflict) {
c.action.update = append(c.action.update, fn)
}
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// sql.Insert("users").
// Columns("id", "name").
// Values(1, "Mashraki").
// OnConflict(
// sql.ConflictColumns("id"),
// sql.ResolveWithNewValues()
// )
func (i *InsertBuilder) OnConflict(opts ...ConflictOption) *InsertBuilder {
if i.conflict == nil {
i.conflict = &conflict{}
}
for _, opt := range opts {
opt(i.conflict)
}
return i
}
// UpdateSet describes a set of changes of the `DO UPDATE` clause.
type UpdateSet struct {
*UpdateBuilder
columns []string
}
// Table returns the table the `UPSERT` statement is executed on.
func (u *UpdateSet) Table() *SelectTable {
return Dialect(u.UpdateBuilder.dialect).Table(u.UpdateBuilder.table)
}
// Columns returns all columns in the `INSERT` statement.
func (u *UpdateSet) Columns() []string {
return u.columns
}
// UpdateColumns returns all columns in the `UPDATE` statement.
func (u *UpdateSet) UpdateColumns() []string {
return append(u.UpdateBuilder.nulls, u.UpdateBuilder.columns...)
}
// Set sets a column to a given value.
func (u *UpdateSet) Set(column string, v any) *UpdateSet {
u.UpdateBuilder.Set(column, v)
return u
}
// Add adds a numeric value to the given column.
func (u *UpdateSet) Add(column string, v any) *UpdateSet {
u.UpdateBuilder.Add(column, v)
return u
}
// SetNull sets a column as null value.
func (u *UpdateSet) SetNull(column string) *UpdateSet {
u.UpdateBuilder.SetNull(column)
return u
}