-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpgsql.go
More file actions
1431 lines (1310 loc) · 33.8 KB
/
pgsql.go
File metadata and controls
1431 lines (1310 loc) · 33.8 KB
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 pgsql
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"os"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"examples/pgsql/db1/model"
"examples/pgsql/db1/replace"
"examples/pgsql/db1/schema"
"examples/common"
"github.com/cd365/hey/v7"
"github.com/cd365/hey/v7/cst"
_ "github.com/lib/pq"
)
var way *hey.Way
func initialize() error {
var (
db *sql.DB
err error
)
{
username := "postgres"
password := "postgres"
host := "localhost"
port := "5432"
database := "postgres"
{
// Get the value of an environment variable.
if value := os.Getenv("HEY_PGSQL_USERNAME"); value != cst.Empty {
username = value
}
if value := os.Getenv("HEY_PGSQL_PASSWORD"); value != cst.Empty {
password = value
}
if value := os.Getenv("HEY_PGSQL_HOST"); value != cst.Empty {
host = value
}
if value := os.Getenv("HEY_PGSQL_PORT"); value != cst.Empty {
port = value
}
if value := os.Getenv("HEY_PGSQL_DATABASE_NAME"); value != cst.Empty {
database = value
}
}
driver := "postgres"
dataSourceName := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", username, password, host, port, database)
db, err = sql.Open(driver, dataSourceName)
if err != nil {
return err
}
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(20)
db.SetConnMaxIdleTime(time.Minute * 3)
db.SetConnMaxLifetime(time.Minute * 3)
}
{
_, err = db.Exec(initSql)
if err != nil {
return err
}
}
options := make([]hey.Option, 0, 8)
{
config := hey.ConfigDefaultPostgresql()
replaces := hey.NewReplacer()
for k, v := range replace.MapTable {
replaces.Set(k, v)
}
for k, v := range replace.MapColumn {
replaces.Set(k, v)
}
config.Manual.Replacer = replaces
config.InsertForbidColumn = []string{"id", "deleted_at"}
config.UpdateForbidColumn = []string{"id", "created_at"}
// config.NewSQLLimit = hey.NewOffsetRowsFetchNextRowsOnly
maxLimit := int64(5000)
maxOffset := int64(500000) - maxLimit
config.MaxLimit = maxLimit
config.MaxOffset = maxOffset
config.DefaultPageSize = 20
// config.TxOptions = &sql.TxOptions{
// Isolation: sql.LevelReadCommitted,
// ReadOnly: false,
// }
options = append(options, hey.WithConfig(config))
options = append(options, hey.WithDatabase(db))
options = append(options, hey.WithTrack(&common.MyTrack{}))
}
way = hey.NewWay(options...)
return nil
}
func Main() {
// log.Default().SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
log.Default().SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
if err := initialize(); err != nil {
panic(err)
}
defer func() {
Delete()
}()
SelectEmpty()
Insert()
Update()
Select()
Transaction()
MyMulti()
Complex()
TableColumn()
WindowFunc()
WayMulti()
}
/*
The following code demonstrates how to construct SQL statements using `way` and how to interact with the database using `way`.
*/
var (
department = schema.Department
employee = schema.Employee
)
func SelectEmpty() {
tmp := way.Table(employee)
tmp.Select(employee.Select()).Desc(employee.Id).Limit(1)
ctx := context.Background()
exists := &model.Employee{}
err := tmp.Scan(ctx, exists)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
log.Printf("Data does not exist: %s", err.Error())
} else {
log.Fatal(err.Error())
}
}
log.Printf("%#v", exists)
}
func Delete() {
// Example 1: Simple condition deletion.
{
ctx := context.Background()
script := way.Table(department).WhereFunc(func(f hey.Filter) {
f.Equal(department.Id, 1)
})
way.Debug(script.ToDelete())
_, err := script.Delete(ctx)
if err != nil {
log.Fatal(err)
}
}
// Example 2: Deleting based on multiple values from the same column.
{
script := way.Table(department).WhereFunc(func(f hey.Filter) {
f.In(department.Id, 1, 2, 3)
})
way.Debug(script.ToDelete())
}
// Example 3: Combination conditions of multiple columns.
{
script := way.Table(department).WhereFunc(func(f hey.Filter) {
f.GreaterThanEqual(department.Id, 1).Group(func(g hey.Filter) {
g.IsNull(department.DeletedAt)
g.OrGroup(func(g hey.Filter) {
g.Equal(department.DeletedAt, 0)
})
})
})
way.Debug(script.ToDelete())
}
// Example 4: Deletion of combined conditions with multiple columns and multiple logic.
{
script := way.Table(department).WhereFunc(func(f hey.Filter) {
f.InGroup([]string{department.Id, department.SerialNum}, [][]any{
{1, 1},
{2, 1},
{3, 1},
})
f.OrGroup(func(g hey.Filter) {
g.In(
department.Id,
way.Table(department).Select(department.Id).WhereFunc(func(f hey.Filter) {
f.GreaterThan(department.DeletedAt, 0)
}).ToSelect(),
)
})
})
way.Debug(script.ToSelect())
}
// Delete example data
{
ctx := context.Background()
_, err := way.Table(department).WhereFunc(func(f hey.Filter) {
f.GreaterThan(department.Id, 0)
}).Delete(ctx)
if err != nil {
log.Fatal(err)
}
_, err = way.Table(employee).WhereFunc(func(f hey.Filter) {
f.GreaterThan(employee.Id, 0)
}).Delete(ctx)
if err != nil {
log.Fatal(err)
}
}
}
func Insert() {
// Example 1: Simple insertion.
{
script := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.ColumnValue(department.Name, "Sales Department")
i.ColumnValue(department.SerialNum, 1)
})
way.Debug(script.ToInsert())
}
// Example 2: Use default values and set SQL statement comments.
{
timestamp := way.Now().Unix()
table := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.ColumnValue(department.Name, "Sales Department")
i.ColumnValue(department.SerialNum, 1)
i.Default(department.CreatedAt, timestamp)
i.Default(department.UpdatedAt, timestamp)
})
way.Debug(table.ToInsert())
table.Labels("Example 1")
way.Debug(table.ToInsert())
// Not setting any columns will result in an incorrectly formatted SQL statement.
table = way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Default(department.CreatedAt, timestamp)
i.Default(department.UpdatedAt, timestamp)
})
way.Debug(table.ToInsert())
}
// Example 3: Delete the specified column before inserting data.
{
timestamp := way.Now().Unix()
script := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.ColumnValue(department.Name, "Sales Department")
i.ColumnValue(department.SerialNum, 1)
i.ColumnValue(department.DeletedAt, timestamp)
i.Default(department.CreatedAt, timestamp)
i.Default(department.UpdatedAt, timestamp)
// This deletes columns that have already been added.
i.Remove(department.DeletedAt)
})
way.Debug(script.ToInsert())
}
// Example 4: Use map insertion.
{
timestamp := way.Now().Unix()
script := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Create(map[string]any{
department.Name: "Sales Department",
department.SerialNum: 1,
department.CreatedAt: timestamp,
department.UpdatedAt: timestamp,
})
})
way.Debug(script.ToInsert())
}
// Example 5: Batch insertion using map slices.
{
timestamp := way.Now().Unix()
script := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Create([]map[string]any{
{
department.Name: "Sales Department1",
department.SerialNum: 1,
department.CreatedAt: timestamp,
department.UpdatedAt: timestamp,
},
{
department.Name: "Sales Department2",
department.SerialNum: 1,
department.CreatedAt: timestamp,
department.UpdatedAt: timestamp,
},
})
})
way.Debug(script.ToInsert())
}
// Example 6: Inserting a structure.
{
timestamp := way.Now().Unix()
script := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Forbid(department.Id, department.DeletedAt)
name := "Sales Department"
i.Create(&model.Department{
Name: &name,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
})
})
way.Debug(script.ToInsert())
}
// Example 7: Batch insertion using structure slices.
{
timestamp := way.Now().Unix()
script := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Forbid(department.Id, department.DeletedAt)
name1 := "Sales Department1"
name2 := "Sales Department2"
name3 := "Sales Department3"
i.Create([]*model.Department{
{
Name: &name1,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
},
{
Name: &name2,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
},
{
Name: &name3,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
},
})
})
way.Debug(script.ToInsert())
}
// Example 8: Large amounts of data inserted in batches.
{
// Use the (*Way).MultiStmtExecute method to perform large-scale data inserts.
}
// Example 9: Insert a record and retrieve the id value of the inserted record(pgsql).
{
timestamp := way.Now().Unix()
ctx := context.Background()
id, err := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Forbid(department.Id, department.DeletedAt)
name := fmt.Sprintf("Sales Department %d", time.Now().Nanosecond())
i.Create(&model.Department{
Name: &name,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
})
i.Returning(func(r hey.SQLReturning) {
r.Returning(department.Id)
r.SetExecute(r.QueryRowScan())
})
}).Insert(ctx)
if err != nil {
log.Println(err.Error())
} else {
log.Println("id:", id)
}
}
// Example 10: Insert a record and retrieve the id value of the inserted record(mysql).
if false {
timestamp := way.Now().Unix()
ctx := context.Background()
id, err := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Forbid(department.Id, department.DeletedAt)
name := fmt.Sprintf("Sales Department %d", time.Now().Nanosecond())
i.Create(&model.Department{
Name: &name,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
})
i.Returning(func(r hey.SQLReturning) {
r.SetExecute(r.LastInsertId())
})
}).Insert(ctx)
if err != nil {
log.Println(err.Error())
} else {
log.Println("id:", id)
}
}
// Example 11: Insert a single data record and retrieve one or more columns of the inserted data(pgsql).
{
timestamp := way.Now().Unix()
ctx := context.Background()
scanName := ""
id, err := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Forbid(department.Id, department.DeletedAt)
name := fmt.Sprintf("Sales Department %d", time.Now().Nanosecond())
i.Create(&model.Department{
Name: &name,
SerialNum: 1,
CreatedAt: timestamp,
UpdatedAt: timestamp,
})
i.Returning(func(r hey.SQLReturning) {
r.Returning(department.Id, department.Name)
r.SetExecute(func(ctx context.Context, stmt *hey.Stmt, args ...any) (id int64, err error) {
err = stmt.QueryRow(ctx, func(row *sql.Row) error {
return row.Scan(&id, &scanName)
}, args...)
return
})
})
}).Insert(ctx)
if err != nil {
log.Println(err.Error())
} else {
log.Println("id:", id, "scan-name:", scanName)
}
}
// Example 12: Use the query result set as the data source for insertion.
{
ctx := context.Background()
rows, err := way.Table(department).InsertFunc(func(i hey.SQLInsert) {
i.Column(department.Name, department.SerialNum)
i.SetSubquery(
way.Table(department).WhereFunc(func(f hey.Filter) {
f.LessThan(department.Id, 0)
}).Select(department.Name, department.SerialNum).Desc(department.Id).Limit(1000).ToSelect(),
)
}).Insert(ctx)
if err != nil {
log.Println(err.Error())
} else {
log.Println("rows:", rows)
}
}
{
ctx := context.Background()
timestamp := time.Now().Unix()
_, err := way.Table(employee).InsertFunc(func(i hey.SQLInsert) {
i.ColumnValue(employee.Name, "Jack")
i.ColumnValue(employee.Age, 18)
i.ColumnValue(employee.CreatedAt, timestamp)
i.ColumnValue(employee.UpdatedAt, timestamp)
i.ReturningId()
}).Insert(ctx)
if err != nil {
log.Fatal(err.Error())
}
}
}
func Update() {
// Example 1: Simple update.
{
script := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
f.Equal(department.Id, 1)
u.Set(department.SerialNum, 999)
}).Labels("Example").ToUpdate()
way.Debug(script)
}
// Example 2: Update conditions using subquery.
{
ctx := context.Background()
rows, err := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
subquery := way.Table(department).Limit(1).Select(department.Id).WhereFunc(func(f hey.Filter) {
f.Equal(department.SerialNum, 11)
}).Desc(department.Id)
f.CompareEqual(department.Id, subquery.ToSelect())
f.OrGroup(func(g hey.Filter) {
g.In(department.Id, subquery.ToSelect())
})
u.Set(department.SerialNum, 999)
}).Update(ctx)
if err != nil {
log.Println(err.Error())
} else {
log.Println("rows:", rows)
}
}
// Example 3: Set the default update column.
{
script := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
f.Equal(department.Id, 1)
u.Set(department.SerialNum, 999)
u.Default(department.UpdatedAt, way.Now().Unix())
}).ToUpdate()
way.Debug(script)
}
// Example 4: Update using map[string]any.
{
script := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
f.Equal(department.Id, 1)
u.Update(map[string]any{
department.SerialNum: 999,
department.Name: "Sales Department",
})
u.Default(department.UpdatedAt, way.Now().Unix())
}).ToUpdate()
way.Debug(script)
}
// Example 5: Update using struct.
{
id := int64(1)
name := "Sales Department"
serialNum := 123
update := &UPDATEDepartment{
Name: &name,
SerialNum: &serialNum,
}
update.Id = &id
script := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
f.Equal(department.Id, 1)
u.Forbid(department.Id)
u.Update(update)
u.Remove(department.UpdatedAt)
u.Default(department.UpdatedAt, way.Now().Unix())
}).ToUpdate()
way.Debug(script)
}
// Example 6: Set column values to increment/decrement.
{
script := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
f.Equal(department.Id, 1)
u.Set(department.Name, "Sales Department")
u.Incr(department.SerialNum, 1)
u.Default(department.UpdatedAt, way.Now().Unix())
}).ToUpdate()
way.Debug(script)
}
// Example 7: Assign values directly to columns, or set raw values in the SQL script.
{
script := way.Table(department).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
f.Equal(department.Id, 1)
u.Assign(department.DeletedAt, department.UpdatedAt)
u.Assign(department.SerialNum, "123")
// u.Assign(department.Name, cst.Empty)
u.Assign(department.Name, cst.NULL)
u.Remove(department.Name)
u.Assign(department.Name, "'Sales Department'")
u.Remove(department.CreatedAt)
}).ToUpdate()
way.Debug(script)
}
}
func Select() {
// SELECT VERSION()
{
ctx := context.Background()
version := ""
err := way.Table(nil).
Select("VERSION()").
Scan(ctx, &version)
if err != nil {
panic(err)
}
log.Println(version)
// OR
version = ""
err = way.Table(nil).
Select(hey.FuncSQL("VERSION")).
Scan(ctx, &version)
if err != nil {
panic(err)
}
log.Println(version)
}
tmp := way.Table(employee)
script := tmp.ToSelect()
way.Debug(script)
// ORDER BY xxx LIMIT n
{
tmp.ToEmpty()
tmp.Asc(employee.Id).Limit(1)
script = tmp.ToSelect()
way.Debug(script)
ctx := context.Background()
value := &model.Employee{}
if err := tmp.Scan(ctx, value); err != nil {
log.Fatal(err.Error())
}
log.Printf("%#v", value)
// values := make([]model.Employee, 0)
values := make([]*model.Employee, 0) // make([]**model.Employee, 0) // Allow multilevel pointers
if err := tmp.Scan(ctx, &values); err != nil {
log.Fatal(err.Error())
}
for _, v := range values {
log.Printf("%#v", v)
}
}
// OFFSET
{
tmp.ToEmpty()
tmp.Asc(employee.Id).Limit(1).Offset(10)
script = tmp.ToSelect()
way.Debug(script)
}
// PAGE
{
tmp.ToEmpty()
tmp.Asc(employee.Id).Page(2, 10)
script = tmp.ToSelect()
way.Debug(script)
}
// comment
{
tmp.ToEmpty()
tmp.Labels("test label").Asc(employee.Id).Page(2, 10)
script = tmp.ToSelect()
way.Debug(script)
}
// SELECT columns
{
tmp.ToEmpty()
tmp.Select(employee.Id, employee.Salary).Asc(employee.Id).Limit(1)
script = tmp.ToSelect()
way.Debug(script)
}
// GROUP BY
{
tmp.ToEmpty()
tmp.Select(employee.Id).Group(employee.Id).GroupFunc(func(g hey.SQLGroupBy) {
g.Having(func(having hey.Filter) {
having.GreaterThanEqual(employee.Id, 0)
})
}).Asc(employee.Id).Limit(1)
script = tmp.ToSelect()
way.Debug(script)
}
// DISTINCT
{
tmp.ToEmpty()
tmp.Distinct().Select(employee.Id, employee.SerialNum).Asc(employee.Id).Limit(1)
script = tmp.ToSelect()
way.Debug(script)
}
// WITH
{
a := "a"
c := department
tmpWith := way.Table(a).Labels("test1").WithFunc(func(w hey.SQLWith) {
w.Set(
a,
way.Table(c).Select(employee.Id, employee.SerialNum).WhereFunc(func(f hey.Filter) {
f.Equal(employee.Id, 1)
}).Desc(employee.Id).Limit(10).ToSelect(),
)
}).Asc(employee.Id).Limit(1)
script = tmpWith.ToSelect()
way.Debug(script)
}
// JOIN
{
a := way.T(cst.A)
b := way.T(cst.B)
ac := a.Column
bc := b.Column
where := way.F()
get := way.Table(employee).Alias(a.Table())
get.LeftJoin(func(join hey.SQLJoin) (hey.SQLAlias, hey.SQLJoinOn) {
joinTable := join.Table(department, b.Table())
joinOn := join.Equal(ac(employee.DepartmentId), bc(department.Id))
where.GreaterThan(ac(employee.Id), 0)
return joinTable, joinOn
})
get.Where(where)
get.Select(
ac(cst.Asterisk),
hey.Alias(hey.Coalesce(bc(department.Name), hey.VarcharValue("")), "department_name"), // string
bc(department.SerialNum, "department_serial_num"), // pointer int
)
get.Desc(ac(employee.Id))
get.Limit(10).Offset(1)
// count, err := get.Count(context.Background())
script = get.ToSelect()
way.Debug(script)
}
// SELECT EXISTS, COUNT, Scan by map[string]any
{
tmp.ToEmpty()
ctx := context.Background()
exists, err := tmp.Table(employee).QueryExists(ctx)
if err != nil {
log.Fatal(err.Error())
}
log.Println(exists)
count, err := tmp.Count(ctx)
if err != nil {
log.Fatal(err.Error())
}
log.Println(count)
result, err := tmp.Limit(1).
MapScan(ctx)
if err != nil {
log.Fatal(err.Error())
}
if len(result) > 0 {
first := result[0]
for k, v := range first {
if v == nil {
log.Printf("%s = %#v\n", k, v)
} else {
value := reflect.ValueOf(v).Elem().Interface()
if val, ok := value.([]byte); ok {
value = string(val)
}
log.Printf("%s = %#v\n", k, value)
}
}
}
}
// Query single column multiple rows.
{
tmp.ToEmpty()
ctx := context.Background()
ids := make([]int64, 0)
err := tmp.Table(employee).
Select(employee.Id).
Desc(employee.Id).
Limit(10).
Scan(ctx, &ids)
if err != nil {
log.Fatal(err.Error())
}
log.Printf("%#v\n", ids)
}
// Execute multiple SQL statements using the same *sql.Stmt. QUERY-SQL
{
ctx := context.Background()
script = tmp.SelectFunc(func(q hey.SQLSelect) {
q.ToEmpty()
}).WhereFunc(func(f hey.Filter) {
f.Equal(employee.Id, 0)
}).Limit(1).ToSelect()
lists := make([][]*model.Employee, 0, 8)
queue := make(chan []any, 8)
go func() {
defer close(queue)
for i := 1; i <= 20; i++ {
queue <- []any{i}
}
}()
err := way.MultiStmtQuery(ctx, script.Prepare, queue, func(rows *sql.Rows) error {
result := make([]*model.Employee, 0)
err := way.RowsScan(&result)(rows)
if err != nil {
return err
}
lists = append(lists, result)
return nil
})
if err != nil {
log.Fatal(err.Error())
}
log.Println(len(lists), lists)
}
// Execute multiple SQL statements using the same *sql.Stmt. INSERT/UPDATE/DELETE/...
{
ctx := context.Background()
script = tmp.UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
u.Set(employee.Age, 0)
f.ToEmpty()
f.Equal(employee.Id, 0)
}).ToUpdate()
var result error
prepare := script.Prepare
cancelCtx, cancel := context.WithCancel(ctx)
defer cancel()
abort := &atomic.Bool{}
group := &sync.WaitGroup{}
mutex := &sync.Mutex{}
queue := make(chan []any, 8)
store := func(err error) {
if err == nil {
return
}
mutex.Lock()
defer mutex.Unlock()
if result == nil {
result = err
}
}
group.Add(1)
go func() {
defer group.Done()
defer close(queue)
var err error
defer func() {
store(err)
}()
for i := 1; i <= 20; i++ {
if abort.Load() {
return
}
select {
case <-cancelCtx.Done():
return
case queue <- []any{i * 2, i}:
}
}
}()
totalAffectedRows := &atomic.Int64{}
for range 1 << 3 {
group.Add(1)
go func() {
defer group.Done()
defer abort.CompareAndSwap(false, true)
affectedRows, err := way.MultiStmtExecute(ctx, prepare, queue)
if err != nil {
store(err)
return
}
totalAffectedRows.Add(affectedRows)
}()
}
group.Wait()
if result != nil {
log.Println(result.Error())
}
log.Println(totalAffectedRows.Load())
}
// More ways to call ...
}
func Transaction() {
var err error
rows := int64(0)
idEqual := func(idValue any) hey.Filter { return way.F().Equal(employee.Id, idValue) }
modify := map[string]any{
"salary": 1500,
}
delete3 := way.Table("example3").Where(idEqual(3))
delete4 := way.Table("example4").Where(idEqual(4))
ctx := context.Background()
err = way.Transaction(ctx, func(tx *hey.Way) error {
tx.TransactionMessage("transaction-message-1")
remove := tx.Table(employee).Where(idEqual(1))
// _, _ = remove.Delete(ctx)
script := remove.ToDelete()
way.Debug(script)
update := tx.Table(department).Where(idEqual(1)).UpdateFunc(func(f hey.Filter, u hey.SQLUpdateSet) {
u.Update(modify)
})
// _, _ = update.Update(ctx)
script = update.ToDelete()
way.Debug(script)
if false {
rows, err = tx.Execute(ctx, delete3.ToDelete())
if err != nil {
return err
}
if rows <= 0 {
return hey.ErrNoRowsAffected
}
delete4.W(tx)
rows, err = delete4.Delete(ctx)
if err != nil {
return err
}
if rows <= 0 {
return hey.ErrNoRowsAffected
}
}
return nil
})
if err != nil {
log.Println(err.Error())
}
// Custom handling of transaction.
err = func() (err error) {
tx := (*hey.Way)(nil)
tx, err = way.Begin(ctx)
if err != nil {
return err
}
tx.TransactionMessage("transaction-message-2")
success := false
defer func() {
if !success {
// for example:
_ = tx.Rollback()
if err == nil {
// panic occurred in the database transaction.
err = fmt.Errorf("%v", recover())
}
}
}()
/*
This is where your business logic is handled.
*/
if err = tx.Commit(); err != nil {
return err
}
success = true
return err
}()
if err != nil {
log.Println(err.Error())
}
}
func MyMulti() {
ctx := context.Background()
m := way.Multi()
m.W(way)
script := m.V().
Table(employee).
WhereFunc(func(f hey.Filter) {
f.Equal(employee.Id, 1)
}).
Select(employee.Id, employee.Name, employee.Email, employee.CreatedAt).