-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathpg_conn.go
1141 lines (1087 loc) · 33.7 KB
/
pg_conn.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 devstatscode
import (
"database/sql"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
_ "github.com/lib/pq" // As suggested by lib/pq driver
)
// WriteTSPoints write batch of points to postgresql
// use mergeSeries = "name" to put all series in "name" table, and create "series" column that conatins all point names.
//
// without merge, alee names will create separate tables.
//
// use non-null mut when you are using this function from multiple threads that write to the same series name at the same time
//
// use non-null mut only then.
//
// No more giant lock approach here, but it is up to user to spcify call context, especially 2 last parameters!
func WriteTSPoints(ctx *Ctx, con *sql.DB, pts *TSPoints, mergeSeries string, hllEmpty []uint8, mut *sync.Mutex) {
npts := len(*pts)
if npts == 0 {
return
}
Printf("WriteTSPoints: writing %d points\n", npts)
if ctx.Debug > 0 {
Printf("Points:\n%+v\n", pts.Str())
}
defer func() { Printf("WriteTSPoints: writing %d points - finished\n", npts) }()
merge := false
mergeS := ""
if mergeSeries != "" {
if !checkPsqlName("s" + mergeSeries) {
return
}
mergeS = "s" + mergeSeries
merge = true
}
tags := make(map[string]map[string]struct{})
fields := make(map[string]map[string]int)
for _, p := range *pts {
if p.tags != nil {
name := p.name
if !merge {
if !checkPsqlName("t" + p.name) {
continue
}
name = "t" + p.name
}
_, ok := tags[name]
if !ok {
tags[name] = make(map[string]struct{})
}
for tagName := range p.tags {
if !checkPsqlName(tagName) {
continue
}
tags[name][tagName] = struct{}{}
}
}
if p.fields != nil {
name := p.name
if !merge {
if !checkPsqlName("s" + p.name) {
continue
}
name = "s" + p.name
}
_, ok := fields[name]
if !ok {
fields[name] = make(map[string]int)
}
for fieldName, fieldValue := range p.fields {
if !checkPsqlName(fieldName) {
continue
}
fName := fieldName
t, ok := fields[name][fName]
if !ok {
t = -1
}
ty := -1
switch fieldValue.(type) {
case float64:
ty = 0
case time.Time:
ty = 1
case string:
ty = 2
case []uint8: // HLL
ty = 3
default:
Fatalf("usupported metric value type: %+v,%T (field %s)", fieldValue, fieldValue, fieldName)
}
if t >= 0 && t != ty {
Fatalf(
"Field %s has a value %+v,%T, previous values were different type %d != %d",
fieldName, fieldValue, fieldValue, ty, t,
)
}
fields[name][fName] = ty
}
}
}
if ctx.Debug > 0 {
Printf("Merge: %v,%s\n", merge, mergeSeries)
Printf("%d tags:\n%+v\n", len(tags), tags)
Printf("%d fields:\n%+v\n", len(fields), fields)
}
sqls := []string{}
// Only used when multiple threads are writing the same series
if mut != nil {
mut.Lock()
}
var (
exists bool
colExists bool
)
for name, data := range tags {
if len(data) == 0 {
continue
}
exists = TableExists(con, ctx, name)
if !exists {
sq := "create table if not exists \"" + name + "\"("
sq += "time timestamp primary key, "
indices := []string{}
for col := range data {
sq += "\"" + escapeName(col) + "\" text, "
iname := makePsqlName("i"+name[1:]+col, false)
indices = append(indices, "create index if not exists \""+iname+"\" on \""+name+"\"(\""+escapeName(col)+"\")")
}
l := len(sq)
sq = sq[:l-2] + ")"
sqls = append(sqls, sq)
sqls = append(sqls, indices...)
sqls = append(sqls, "grant select on \""+name+"\" to ro_user")
sqls = append(sqls, "grant select on \""+name+"\" to devstats_team")
} else {
for col := range data {
eCol := escapeName(col)
colExists = TableColumnExists(con, ctx, name, eCol)
if !colExists {
sq := "alter table \"" + name + "\" add column if not exists \"" + eCol + "\" text"
sqls = append(sqls, sq)
iname := makePsqlName("i"+name[1:]+col, false)
sqls = append(sqls, "create index if not exists \""+iname+"\" on \""+name+"\"(\""+eCol+"\")")
}
}
}
}
if merge {
bTable := false
colMap := make(map[string]struct{})
for _, data := range fields {
if len(data) == 0 {
continue
}
if !bTable {
exists = TableExists(con, ctx, mergeS)
if !exists {
sq := "create table if not exists \"" + mergeS + "\"("
sq += "time timestamp not null, series text not null, period text not null default '', "
indices := []string{
"create index if not exists \"" + makePsqlName("i"+mergeS[1:]+"t", false) + "\" on \"" + mergeS + "\"(time)",
"create index if not exists \"" + makePsqlName("i"+mergeS[1:]+"s", false) + "\" on \"" + mergeS + "\"(series)",
"create index if not exists \"" + makePsqlName("i"+mergeS[1:]+"p", false) + "\" on \"" + mergeS + "\"(period)",
}
for col, ty := range data {
col = escapeName(col)
if ty == 0 {
sq += "\"" + col + "\" double precision not null default 0.0, "
// if uncommented then avoid double escape of " in col
//indices = append(indices, "create index if not exists \""+makePsqlName("i"+mergeS[1:]+col, false)+"\" on \""+mergeS+"\"(\""+col+"\")")
} else if ty == 1 {
sq += "\"" + col + "\" timestamp not null default '1900-01-01 00:00:00', "
} else if ty == 3 {
sq += "\"" + col + "\" hll not null default hll_empty(), "
} else {
sq += "\"" + col + "\" text not null default '', "
}
colMap[col] = struct{}{}
}
sq += "primary key(time, series, period))"
sqls = append(sqls, sq)
sqls = append(sqls, indices...)
sqls = append(sqls, "grant select on \""+mergeS+"\" to ro_user")
sqls = append(sqls, "grant select on \""+mergeS+"\" to devstats_team")
}
bTable = true
}
for col, ty := range data {
col = escapeName(col)
_, ok := colMap[col]
if !ok {
colExists = TableColumnExists(con, ctx, mergeS, col)
colMap[col] = struct{}{}
if !colExists {
if ty == 0 {
sqls = append(sqls, "alter table \""+mergeS+"\" add column if not exists \""+col+"\" double precision not null default 0.0")
// if uncommented then avoid double escape of " in col
//sqls = append(sqls, "create index if not exists \""+makePsqlName("i"+mergeS[1:]+col, false)+"\" on \""+mergeS+"\"(\""+col+"\")")
} else if ty == 1 {
sqls = append(sqls, "alter table \""+mergeS+"\" add column if not exists \""+col+"\" timestamp not null default '1900-01-01 00:00:00'")
} else if ty == 3 {
sqls = append(sqls, "alter table \""+mergeS+"\" add column if not exists \""+col+"\" hll not null default hll_empty()")
} else {
sqls = append(sqls, "alter table \""+mergeS+"\" add column if not exists \""+col+"\" text not null default ''")
}
}
}
}
}
} else {
for name, data := range fields {
if len(data) == 0 {
continue
}
exists = TableExists(con, ctx, name)
if !exists {
sq := "create table if not exists \"" + name + "\"("
sq += "time timestamp not null, period text not null default '', "
indices := []string{
"create index if not exists \"" + makePsqlName("i"+name[1:]+"t", false) + "\" on \"" + name + "\"(time)",
"create index if not exists \"" + makePsqlName("i"+name[1:]+"p", false) + "\" on \"" + name + "\"(period)",
}
for col, ty := range data {
col = escapeName(col)
if ty == 0 {
sq += "\"" + col + "\" double precision not null default 0.0, "
// if uncommented then avoid double escape of " in col
//indices = append(indices, "create index if not exists \""+makePsqlName("i"+name[1:]+col, false)+"\" on \""+name+"\"(\""+col+"\")")
} else if ty == 1 {
sq += "\"" + col + "\" timestamp not null default '1900-01-01 00:00:00', "
} else if ty == 3 {
sq += "\"" + col + "\" hll not null default hll_empty(), "
} else {
sq += "\"" + col + "\" text not null default '', "
}
}
sq += "primary key(time, period))"
sqls = append(sqls, sq)
sqls = append(sqls, indices...)
sqls = append(sqls, "grant select on \""+name+"\" to ro_user")
sqls = append(sqls, "grant select on \""+name+"\" to devstats_team")
} else {
for col, ty := range data {
col = escapeName(col)
colExists = TableColumnExists(con, ctx, name, col)
if !colExists {
if ty == 0 {
sqls = append(sqls, "alter table \""+name+"\" add column if not exists \""+col+"\" double precision not null default 0.0")
// if uncommented then avoid double escape of " in col
//sqls = append(sqls, "create index if not exists \""+makePsqlName("i"+name[1:]+col, false)+"\" on \""+name+"\"(\""+col+"\")")
} else if ty == 1 {
sqls = append(sqls, "alter table \""+name+"\" add column if not exists \""+col+"\" timestamp not null default '1900-01-01 00:00:00'")
} else if ty == 3 {
sqls = append(sqls, "alter table \""+name+"\" add column if not exists \""+col+"\" hll not null default hll_empty()")
} else {
sqls = append(sqls, "alter table \""+name+"\" add column if not exists \""+col+"\" text not null default ''")
}
}
}
}
}
}
if ctx.Debug > 0 && len(sqls) > 0 {
Printf("structural sqls:\n%s\n", strings.Join(sqls, "\n"))
}
for _, q := range sqls {
// Notice: This **may** fail, when using multiple processes (not threads) to create structures (tables, columns and indices)
// But each operation can only fail when some other process already executed it succesfully
// So **ALL** those failures are *OK*.
// We can avoid thenm by using transaction, but it is much slower then, effect is the same and all we want **IS THE SPEED**
// So this is done for purpose!
_, err := ExecSQL(con, ctx, q)
if err != nil {
Printf("Ignored %s: %+v\n", q, err)
}
}
// Only used when multiple threads are writing the same series
if mut != nil {
mut.Unlock()
}
ns := 0
for _, p := range *pts {
if p.tags != nil {
if !checkPsqlName("t" + p.name) {
continue
}
name := "t" + p.name
namesI := []string{"time"}
argsI := []string{"$1"}
vals := []interface{}{p.t}
i := 2
for tagName, tagValue := range p.tags {
if !checkPsqlName(tagName) {
continue
}
tagName = escapeName(tagName)
namesI = append(namesI, "\""+tagName+"\"")
argsI = append(argsI, "$"+strconv.Itoa(i))
vals = append(vals, tagValue)
i++
}
if i == 2 {
if ctx.Debug >= 0 {
Printf("tag %s has no values, skipping\n", name)
}
continue
}
namesIA := strings.Join(namesI, ", ")
argsIA := strings.Join(argsI, ", ")
namesU := []string{}
argsU := []string{}
for tagName, tagValue := range p.tags {
if !checkPsqlName(tagName) {
continue
}
tagName = escapeName(tagName)
namesU = append(namesU, "\""+tagName+"\"")
argsU = append(argsU, "$"+strconv.Itoa(i))
vals = append(vals, tagValue)
i++
}
namesUA := strings.Join(namesU, ", ")
argsUA := strings.Join(argsU, ", ")
if len(namesU) > 1 {
namesUA = "(" + namesUA + ")"
argsUA = "(" + argsUA + ")"
}
var q string
if len(namesU) > 0 {
argT := "$" + strconv.Itoa(i)
vals = append(vals, p.t)
q = fmt.Sprintf(
"insert into \"%[1]s\"("+namesIA+") values("+argsIA+") "+
"on conflict(time) do update set "+namesUA+" = "+argsUA+" "+
"where \"%[1]s\".time = "+argT,
name,
)
} else {
q = fmt.Sprintf(
"insert into \"%[1]s\"("+namesIA+") values("+argsIA+") "+
"on conflict(time) do nothing",
name,
)
}
ExecSQLWithErr(con, ctx, q, vals...)
ns++
}
if p.fields != nil && !merge {
if !checkPsqlName("s" + p.name) {
continue
}
name := "s" + p.name
namesI := []string{"time", "period"}
argsI := []string{"$1", "$2"}
vals := []interface{}{p.t, p.period}
i := 3
for fieldName, fieldValue := range p.fields {
if !checkPsqlName(fieldName) {
continue
}
fieldName = escapeName(fieldName)
namesI = append(namesI, "\""+fieldName+"\"")
argsI = append(argsI, "$"+strconv.Itoa(i))
switch val := fieldValue.(type) {
case []uint8:
if len(val) == 0 {
vals = append(vals, hllEmpty)
} else {
vals = append(vals, val)
}
default:
vals = append(vals, fieldValue)
}
i++
}
if i == 3 {
if ctx.Debug >= 0 {
Printf("field %s has no values other than time and period, skipping\n", name)
}
continue
}
namesIA := strings.Join(namesI, ", ")
argsIA := strings.Join(argsI, ", ")
namesU := []string{}
argsU := []string{}
for fieldName, fieldValue := range p.fields {
if !checkPsqlName(fieldName) {
continue
}
fieldName = escapeName(fieldName)
namesU = append(namesU, "\""+fieldName+"\"")
argsU = append(argsU, "$"+strconv.Itoa(i))
switch val := fieldValue.(type) {
case []uint8:
if len(val) == 0 {
vals = append(vals, hllEmpty)
} else {
vals = append(vals, val)
}
default:
vals = append(vals, fieldValue)
}
i++
}
namesUA := strings.Join(namesU, ", ")
argsUA := strings.Join(argsU, ", ")
if len(namesU) > 1 {
namesUA = "(" + namesUA + ")"
argsUA = "(" + argsUA + ")"
}
var q string
if len(namesU) > 0 {
argT := "$" + strconv.Itoa(i)
argP := "$" + strconv.Itoa(i+1)
vals = append(vals, p.t)
vals = append(vals, p.period)
q = fmt.Sprintf(
"insert into \"%[1]s\"("+namesIA+") values("+argsIA+") "+
"on conflict(time, period) do update set "+namesUA+" = "+argsUA+" "+
"where \"%[1]s\".time = "+argT+" and \"%[1]s\".period = "+argP,
name,
)
} else {
q = fmt.Sprintf(
"insert into \"%[1]s\"("+namesIA+") values("+argsIA+") "+
"on conflict(time, period) do nothing",
name,
)
}
ExecSQLWithErr(con, ctx, q, vals...)
ns++
}
if p.fields != nil && merge {
namesI := []string{"time", "period", "series"}
argsI := []string{"$1", "$2", "$3"}
vals := []interface{}{p.t, p.period, p.name}
i := 4
for fieldName, fieldValue := range p.fields {
if !checkPsqlName(fieldName) {
continue
}
fieldName = escapeName(fieldName)
namesI = append(namesI, "\""+fieldName+"\"")
argsI = append(argsI, "$"+strconv.Itoa(i))
switch val := fieldValue.(type) {
case []uint8:
if len(val) == 0 {
vals = append(vals, hllEmpty)
} else {
vals = append(vals, val)
}
default:
vals = append(vals, fieldValue)
}
i++
}
if i == 4 {
if ctx.Debug >= 0 {
Printf("field %s has no values other than time, period and series, skipping\n", mergeS)
}
continue
}
namesIA := strings.Join(namesI, ", ")
argsIA := strings.Join(argsI, ", ")
namesU := []string{}
argsU := []string{}
for fieldName, fieldValue := range p.fields {
if !checkPsqlName(fieldName) {
continue
}
fieldName = escapeName(fieldName)
namesU = append(namesU, "\""+fieldName+"\"")
argsU = append(argsU, "$"+strconv.Itoa(i))
switch val := fieldValue.(type) {
case []uint8:
if len(val) == 0 {
vals = append(vals, hllEmpty)
} else {
vals = append(vals, val)
}
default:
vals = append(vals, fieldValue)
}
i++
}
namesUA := strings.Join(namesU, ", ")
argsUA := strings.Join(argsU, ", ")
if len(namesU) > 1 {
namesUA = "(" + namesUA + ")"
argsUA = "(" + argsUA + ")"
}
var q string
if len(namesU) > 0 {
argT := "$" + strconv.Itoa(i)
argP := "$" + strconv.Itoa(i+1)
argS := "$" + strconv.Itoa(i+2)
vals = append(vals, p.t)
vals = append(vals, p.period)
vals = append(vals, p.name)
q = fmt.Sprintf(
"insert into \"%[1]s\"("+namesIA+") values("+argsIA+") "+
"on conflict(time, series, period) do update set "+namesUA+" = "+argsUA+" "+
"where \"%[1]s\".time = "+argT+" and \"%[1]s\".period = "+argP+" and \"%[1]s\".series = "+argS,
mergeS,
)
} else {
q = fmt.Sprintf(
"insert into \"%[1]s\"("+namesIA+") values("+argsIA+") "+
"on conflict(time, series, period) do nothing",
mergeS,
)
}
ExecSQLWithErr(con, ctx, q, vals...)
ns++
}
}
if ctx.Debug > 0 {
Printf("upserts: %d\n", ns)
}
}
// makePsqlName makes sure the identifier is shorter than 64
// fatal: when used to create table or column
// non-fatal: only when used for create index if not exists
// to use `create index if not exists` we must give it a name
// (so postgres can detect if index exists), name is created from table and column names
// so if this is too long, just make it shorter - hence non-fatal
func makePsqlName(name string, fatal bool) string {
name = strings.Replace(name, `"`, `""`, -1)
l := len(name)
if l > 63 {
if fatal {
Fatalf("postgresql identifier name too long (%d, %s)", l, name)
return name
}
Printf("Notice: makePsqlName: postgresql identifier name too long (%d, %s)\n", l, name)
newName := StripUnicode(name[:32] + name[l-31:])
return newName
}
return name
}
// escapeName - escapes " into "" in psql table/column names
func escapeName(name string) string {
return strings.Replace(name, `"`, `""`, -1)
}
// checkPsqlName - prints warning when psql name exceeds 63 bytes
// return: true - name is OK, false: name is too long (warning is issued)
func checkPsqlName(name string) bool {
name = strings.Replace(name, `"`, `""`, -1)
l := len(name)
if l > 63 {
Printf("Notice: checkPsqlName: postgresql identifier name too long (%d, %s)\n", l, name)
return false
}
return true
}
// GetTagValues returns tag values for a given key
func GetTagValues(con *sql.DB, ctx *Ctx, name, key string) (ret []string) {
rows := QuerySQLWithErr(
con,
ctx,
fmt.Sprintf(
"select %s from t%s order by time asc",
key,
name,
),
)
defer func() { FatalOnError(rows.Close()) }()
s := ""
for rows.Next() {
FatalOnError(rows.Scan(&s))
ret = append(ret, s)
}
FatalOnError(rows.Err())
return
}
// TableExists - checks if a given table exists
func TableExists(con *sql.DB, ctx *Ctx, tableName string) bool {
var s *string
FatalOnError(QueryRowSQL(con, ctx, fmt.Sprintf("select to_regclass(%s)", NValue(1)), tableName).Scan(&s))
return s != nil
}
// TableColumnExists - checks if a given table's has a given column
func TableColumnExists(con *sql.DB, ctx *Ctx, tableName, columnName string) bool {
var s *string
FatalOnError(
QueryRowSQL(
con,
ctx,
fmt.Sprintf(
"select column_name from information_schema.columns "+
"where table_name=%s and column_name=%s "+
"union select null limit 1",
NValue(1),
NValue(2),
),
tableName,
columnName,
).Scan(&s),
)
return s != nil
}
// PgConnErr Connects to Postgres database
func PgConnErr(ctx *Ctx) (*sql.DB, error) {
connectionString := "client_encoding=UTF8 sslmode='" + ctx.PgSSL + "' host='" + ctx.PgHost + "' port=" + ctx.PgPort + " dbname='" + ctx.PgDB + "' user='" + ctx.PgUser + "' password='" + ctx.PgPass + "'"
if ctx.QOut {
fmt.Printf("PgConnectString: %s\n", connectionString)
}
return sql.Open("postgres", connectionString)
}
// PgConn Connects to Postgres database
func PgConn(ctx *Ctx) *sql.DB {
connectionString := "client_encoding=UTF8 sslmode='" + ctx.PgSSL + "' host='" + ctx.PgHost + "' port=" + ctx.PgPort + " dbname='" + ctx.PgDB + "' user='" + ctx.PgUser + "' password='" + ctx.PgPass + "'"
if ctx.QOut {
// Use fmt.Printf (not lib.Printf that logs to DB) here
// Avoid trying to log something to DB while connecting
fmt.Printf("PgConnectString: %s\n", connectionString)
}
con, err := sql.Open("postgres", connectionString)
FatalOnError(err)
return con
}
// PgConnDB Connects to Postgres database (with specific DB name)
// uses database 'dbname' instead of 'PgDB'
func PgConnDB(ctx *Ctx, dbName string) *sql.DB {
connectionString := "client_encoding=UTF8 sslmode='" + ctx.PgSSL + "' host='" + ctx.PgHost + "' port=" + ctx.PgPort + " dbname='" + dbName + "' user='" + ctx.PgUser + "' password='" + ctx.PgPass + "'"
if ctx.QOut {
// Use fmt.Printf (not lib.Printf that logs to DB) here
// Avoid trying to log something to DB while connecting
fmt.Printf("ConnectString: %s\n", connectionString)
}
ctx.CanReconnect = false
con, err := sql.Open("postgres", connectionString)
FatalOnError(err)
return con
}
// CreateTable is used to replace DB specific parts of Create Table SQL statement
func CreateTable(tdef string) string {
tdef = strings.Replace(tdef, "{{ts}}", "timestamp", -1)
tdef = strings.Replace(tdef, "{{tsnow}}", "timestamp default now()", -1)
tdef = strings.Replace(tdef, "{{pkauto}}", "bigserial", -1)
return "create table " + tdef
}
// Outputs query info
func queryOut(query string, args ...interface{}) {
// Use fmt.Printf not lib.Printf here
// If we use lib.Printf (that logs to DB) while ouputting some query's parameters
// We would have infinite recurence
fmt.Printf("%s\n", query)
if len(args) > 0 {
s := ""
for vi, vv := range args {
switch v := vv.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128, string, bool, time.Time:
s += fmt.Sprintf("%d:%+v ", vi+1, v)
case []uint8:
s += fmt.Sprintf("%d:%v ", vi+1, FormatRawBytes(v))
case nil:
s += fmt.Sprintf("%d:(null) ", vi+1)
default:
s += fmt.Sprintf("%d:%T:%+v ", vi+1, vv, reflect.ValueOf(vv))
}
}
fmt.Printf("[%s]\n", s)
//fmt.Printf("%+v\n", args)
}
}
// QueryRowSQL executes given SQL on Postgres DB (and returns single row)
func QueryRowSQL(con *sql.DB, ctx *Ctx, query string, args ...interface{}) *sql.Row {
if ctx.QOut {
queryOut(query, args...)
}
return con.QueryRow(query, args...)
}
// QueryRowSQLTx executes given SQL on Postgres DB (and returns single row)
func QueryRowSQLTx(tx *sql.Tx, ctx *Ctx, query string, args ...interface{}) *sql.Row {
if ctx.QOut {
queryOut(query, args...)
}
return tx.QueryRow(query, args...)
}
// QuerySQL executes given SQL on Postgres DB (and returns rowset that needs to be closed)
func QuerySQL(con *sql.DB, ctx *Ctx, query string, args ...interface{}) (*sql.Rows, error) {
if ctx.QOut {
queryOut(query, args...)
}
return con.Query(query, args...)
}
// QuerySQLLogErr executes given SQL on Postgres DB (and returns rowset that needs to be closed)
func QuerySQLLogErr(con *sql.DB, ctx *Ctx, query string, args ...interface{}) (*sql.Rows, error) {
if ctx.QOut {
queryOut(query, args...)
}
rows, err := con.Query(query, args...)
if err != nil {
queryOut(query, args...)
}
return rows, err
}
// QuerySQLWithErr wrapper to QuerySQL that exists on error
func QuerySQLWithErr(con *sql.DB, ctx *Ctx, query string, args ...interface{}) *sql.Rows {
// Try to handle "too many connections" error
var (
status string
res *sql.Rows
err error
)
for _, try := range ctx.Trials {
res, err = QuerySQL(con, ctx, query, args...)
if err != nil {
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
fmt.Fprintf(os.Stderr, "Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
fmt.Fprintf(os.Stderr, "%d seconds passed, retrying...\n", try)
if status == Reconnect {
if ctx.CanReconnect {
fmt.Fprintf(os.Stderr, "Reconnect request after %d seconds\n", try)
_ = con.Close()
con = PgConn(ctx)
fmt.Fprintf(os.Stderr, "Reconnected after %d seconds\n", try)
} else {
Fatalf("returned reconnect request, but custom DB connect strings are in use")
}
}
}
if status != OK {
Fatalf("too many attempts, tried %d times", len(ctx.Trials))
}
return res
}
// QuerySQLTx executes given SQL on Postgres DB (and returns rowset that needs to be closed)
// It is for running inside transaction
func QuerySQLTx(con *sql.Tx, ctx *Ctx, query string, args ...interface{}) (*sql.Rows, error) {
if ctx.QOut {
queryOut(query, args...)
}
return con.Query(query, args...)
}
// QuerySQLTxWithErr wrapper to QuerySQLTx that exists on error
// It is for running inside transaction
func QuerySQLTxWithErr(con *sql.Tx, ctx *Ctx, query string, args ...interface{}) *sql.Rows {
// Try to handle "too many connections" error
var (
status string
res *sql.Rows
err error
db *sql.DB
)
for _, try := range ctx.Trials {
if db == nil {
res, err = QuerySQLTx(con, ctx, query, args...)
} else {
res, err = QuerySQL(db, ctx, query, args...)
}
if err != nil {
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
fmt.Fprintf(os.Stderr, "Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
fmt.Fprintf(os.Stderr, "%d seconds passed, retrying...\n", try)
if status == Reconnect {
fmt.Fprintf(os.Stderr, "Reconnect request after %d seconds, breaking transaction\n", try)
if ctx.CanReconnect {
//db = PgConn(ctx)
//fmt.Fprintf(os.Stderr, "Reconnected after %d seconds, breaking transaction\n", try)
Fatalf("reconnect request from within the transaction is not supported")
} else {
Fatalf("returned reconnect request, but custom DB connect strings are in use")
}
}
}
if status != OK {
Fatalf("too many attempts, tried %d times", len(ctx.Trials))
}
return res
}
// ExecSQLLogErr executes given SQL on Postgres DB (and return single state result, that doesn't need to be closed)
func ExecSQLLogErr(con *sql.DB, ctx *Ctx, query string, args ...interface{}) (sql.Result, error) {
if ctx.QOut {
queryOut(query, args...)
}
res, err := con.Exec(query, args...)
if err != nil {
queryOut(query, args...)
}
return res, err
}
// ExecSQL executes given SQL on Postgres DB (and return single state result, that doesn't need to be closed)
func ExecSQL(con *sql.DB, ctx *Ctx, query string, args ...interface{}) (sql.Result, error) {
if ctx.QOut {
queryOut(query, args...)
}
return con.Exec(query, args...)
}
// ExecSQLWithErr wrapper to ExecSQL that exists on error
func ExecSQLWithErr(con *sql.DB, ctx *Ctx, query string, args ...interface{}) sql.Result {
// Try to handle "too many connections" error
var (
status string
res sql.Result
err error
)
for _, try := range ctx.Trials {
res, err = ExecSQL(con, ctx, query, args...)
if err != nil {
fmt.Printf("Failed sql: ")
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
fmt.Fprintf(os.Stderr, "Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
fmt.Fprintf(os.Stderr, "%d seconds passed, retrying...\n", try)
if status == Reconnect {
fmt.Fprintf(os.Stderr, "Reconnect request after %d seconds\n", try)
if ctx.CanReconnect {
_ = con.Close()
con = PgConn(ctx)
fmt.Fprintf(os.Stderr, "Reconnected after %d seconds\n", try)
} else {
Fatalf("returned reconnect request, but custom DB connect strings are in use")
}
}
}
if status != OK {
Fatalf("too many attempts, tried %d times", len(ctx.Trials))
}
return res
}
// ExecSQLTx executes given SQL on Postgres DB (and return single state result, that doesn't need to be closed)
// It is for running inside transaction
func ExecSQLTx(con *sql.Tx, ctx *Ctx, query string, args ...interface{}) (sql.Result, error) {
if ctx.QOut {
queryOut(query, args...)
}
return con.Exec(query, args...)
}
// ExecSQLTxWithErr wrapper to ExecSQLTx that exists on error
// It is for running inside transaction
func ExecSQLTxWithErr(con *sql.Tx, ctx *Ctx, query string, args ...interface{}) sql.Result {
// Try to handle "too many connections" error
var (
status string
res sql.Result
err error
db *sql.DB
)
for _, try := range ctx.Trials {
if db == nil {
res, err = ExecSQLTx(con, ctx, query, args...)
} else {
res, err = ExecSQL(db, ctx, query, args...)
}
if err != nil {
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
fmt.Fprintf(os.Stderr, "Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
fmt.Fprintf(os.Stderr, "%d seconds passed, retrying...\n", try)
if status == Reconnect {
fmt.Fprintf(os.Stderr, "Reconnect request after %d seconds, breaking transaction\n", try)
if ctx.CanReconnect {
//db = PgConn(ctx)
//fmt.Fprintf(os.Stderr, "Reconnected after %d seconds, breaking transaction\n", try)
Fatalf("reconnect request from within the transaction is not supported")
} else {
Fatalf("returned reconnect request, but custom DB connect strings are in use")
}
}
}
if status != OK {
Fatalf("too many attempts, tried %d times", len(ctx.Trials))
}
return res
}
// NValues will return values($1, $2, .., $n)
func NValues(n int) string {
s := "values("
i := 1
for i <= n {
s += "$" + strconv.Itoa(i) + ", "
i++
}
return s[:len(s)-2] + ")"
}
// NArray will return values($1, $2, .., $n)
func NArray(n, offset int) string {
s := "("
i := 1 + offset
n += offset
for i <= n {
s += "$" + strconv.Itoa(i) + ", "
i++
}
return s[:len(s)-2] + ")"
}
// NValue will return $n
func NValue(index int) string {
return fmt.Sprintf("$%d", index)
}
// InsertIgnore - will return insert statement with ignore option specific for DB
func InsertIgnore(query string) string {
return fmt.Sprintf("insert %s on conflict do nothing", query)
}
// BoolOrNil - return either nil or value of boolPtr
func BoolOrNil(boolPtr *bool) interface{} {
if boolPtr == nil {
return nil
}
return *boolPtr
}
// NegatedBoolOrNil - return either nil or negated value of boolPtr
func NegatedBoolOrNil(boolPtr *bool) interface{} {
if boolPtr == nil {
return nil
}
return !*boolPtr
}
// TimeOrNil - return either nil or value of timePtr
func TimeOrNil(timePtr *time.Time) interface{} {
if timePtr == nil {
return nil
}
return *timePtr
}
// IntOrNil - return either nil or value of intPtr
func IntOrNil(intPtr *int) interface{} {
if intPtr == nil {
return nil
}
return *intPtr
}
// FirstIntOrNil - return either nil or value of intPtr
func FirstIntOrNil(intPtrs []*int) interface{} {
for _, intPtr := range intPtrs {
if intPtr != nil {
return *intPtr
}
}
return nil
}
// CleanUTF8 - clean UTF8 string to containg only Pq allowed runes
func CleanUTF8(str string) string {