forked from cncf/devstatscode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg_conn.go
842 lines (793 loc) · 25.2 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
package devstatscode
import (
"database/sql"
"fmt"
"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, mut *sync.Mutex) {
npts := len(*pts)
if ctx.Debug > 0 {
Printf("WriteTSPoints: writing %d points\n", len(*pts))
Printf("Points:\n%+v\n", pts.Str())
}
if npts == 0 {
return
}
merge := false
mergeS := ""
if mergeSeries != "" {
mergeS = makePsqlName("s"+mergeSeries, true)
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 {
name = makePsqlName("t"+p.name, true)
}
_, ok := tags[name]
if !ok {
tags[name] = make(map[string]struct{})
}
for tagName := range p.tags {
tName := makePsqlName(tagName, true)
tags[name][tName] = struct{}{}
}
}
if p.fields != nil {
name := p.name
if !merge {
name = makePsqlName("s"+p.name, true)
}
_, ok := fields[name]
if !ok {
fields[name] = make(map[string]int)
}
for fieldName, fieldValue := range p.fields {
fName := makePsqlName(fieldName, true)
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
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 += "\"" + col + "\" text, "
iname := makePsqlName("i"+name[1:]+col, false)
indices = append(indices, "create index if not exists \""+iname+"\" on \""+name+"\"(\""+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 {
colExists = TableColumnExists(con, ctx, name, col)
if !colExists {
sq := "alter table \"" + name + "\" add column if not exists \"" + col + "\" text"
sqls = append(sqls, sq)
iname := makePsqlName("i"+name[1:]+col, false)
sqls = append(sqls, "create index if not exists \""+iname+"\" on \""+name+"\"(\""+col+"\")")
}
}
}
}
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 {
if ty == 0 {
sq += "\"" + col + "\" double precision not null default 0.0, "
//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 '1970-01-01 00:00:00', "
} 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 {
_, 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")
//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 '1970-01-01 00:00:00'")
} 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 {
if ty == 0 {
sq += "\"" + col + "\" double precision not null default 0.0, "
//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 '1970-01-01 00:00:00', "
} 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 {
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")
//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 '1970-01-01 00:00:00'")
} 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 {
name := makePsqlName("t"+p.name, true)
namesI := []string{"time"}
argsI := []string{"$1"}
vals := []interface{}{p.t}
i := 2
for tagName, tagValue := range p.tags {
namesI = append(namesI, "\""+makePsqlName(tagName, true)+"\"")
argsI = append(argsI, "$"+strconv.Itoa(i))
vals = append(vals, tagValue)
i++
}
namesIA := strings.Join(namesI, ", ")
argsIA := strings.Join(argsI, ", ")
namesU := []string{}
argsU := []string{}
for tagName, tagValue := range p.tags {
namesU = append(namesU, "\""+makePsqlName(tagName, true)+"\"")
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 + ")"
}
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,
)
ExecSQLWithErr(con, ctx, q, vals...)
ns++
}
if p.fields != nil && !merge {
name := makePsqlName("s"+p.name, true)
namesI := []string{"time", "period"}
argsI := []string{"$1", "$2"}
vals := []interface{}{p.t, p.period}
i := 3
for fieldName, fieldValue := range p.fields {
namesI = append(namesI, "\""+makePsqlName(fieldName, true)+"\"")
argsI = append(argsI, "$"+strconv.Itoa(i))
vals = append(vals, fieldValue)
i++
}
namesIA := strings.Join(namesI, ", ")
argsIA := strings.Join(argsI, ", ")
namesU := []string{}
argsU := []string{}
for fieldName, fieldValue := range p.fields {
namesU = append(namesU, "\""+makePsqlName(fieldName, true)+"\"")
argsU = append(argsU, "$"+strconv.Itoa(i))
vals = append(vals, fieldValue)
i++
}
namesUA := strings.Join(namesU, ", ")
argsUA := strings.Join(argsU, ", ")
if len(namesU) > 1 {
namesUA = "(" + namesUA + ")"
argsUA = "(" + argsUA + ")"
}
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,
)
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 {
namesI = append(namesI, "\""+makePsqlName(fieldName, true)+"\"")
argsI = append(argsI, "$"+strconv.Itoa(i))
vals = append(vals, fieldValue)
i++
}
namesIA := strings.Join(namesI, ", ")
argsIA := strings.Join(argsI, ", ")
namesU := []string{}
argsU := []string{}
for fieldName, fieldValue := range p.fields {
namesU = append(namesU, "\""+makePsqlName(fieldName, true)+"\"")
argsU = append(argsU, "$"+strconv.Itoa(i))
vals = append(vals, fieldValue)
i++
}
namesUA := strings.Join(namesU, ", ")
argsUA := strings.Join(argsU, ", ")
if len(namesU) > 1 {
namesUA = "(" + namesUA + ")"
argsUA = "(" + argsUA + ")"
}
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,
)
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 amke it shorter - hence non-fatal
func makePsqlName(name string, fatal bool) string {
l := len(name)
if l > 63 {
if fatal {
Fatalf("postgresql identifier name too long (%d, %s)", l, name)
return name
}
Printf("Notice: postgresql identifier name too long (%d, %s)", l, name)
newName := name[:32] + name[l-31:]
return newName
}
return name
}
// 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
}
// 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)
}
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}}", "serial", -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
if len(args) > 0 {
fmt.Printf("%+v\n", args)
}
fmt.Printf("%s\n", query)
}
// 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...)
}
// 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
}
Printf("Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
Printf("%d seconds passed, retrying...\n", try)
}
if status == Retry {
Fatalf("too many connections used, 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
)
for _, try := range ctx.Trials {
res, err = QuerySQLTx(con, ctx, query, args...)
if err != nil {
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
Printf("Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
Printf("%d seconds passed, retrying...\n", try)
}
if status == Retry {
Fatalf("too many connections used, tried %d times", len(ctx.Trials))
}
return res
}
// 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 {
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
Printf("Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
Printf("%d seconds passed, retrying...\n", try)
}
if status == Retry {
Fatalf("too many connections used, 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
)
for _, try := range ctx.Trials {
res, err = ExecSQLTx(con, ctx, query, args...)
if err != nil {
queryOut(query, args...)
}
status = FatalOnError(err)
if status == "ok" {
break
}
Printf("Will retry after %d seconds...\n", try)
time.Sleep(time.Duration(try) * time.Second)
Printf("%d seconds passed, retrying...\n", try)
}
if status == Retry {
Fatalf("too many connections used, 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] + ")"
}
// 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 {
if strings.Contains(str, "\x00") {
return strings.Replace(str, "\x00", "", -1)
}
return str
}
// StringOrNil - return either nil or value of strPtr
func StringOrNil(strPtr *string) interface{} {
if strPtr == nil {
return nil
}
return CleanUTF8(*strPtr)
}
// TruncToBytes - truncates text to <= size bytes (note that this can be a lot less UTF-8 runes)
func TruncToBytes(str string, size int) string {
str = CleanUTF8(str)
length := len(str)
if length < size {
return str
}
res := ""
i := 0
for _, r := range str {
if len(res+string(r)) > size {
break
}
res += string(r)
i++
}
return res
}
// TruncStringOrNil - return either nil or value of strPtr truncated to maxLen chars
func TruncStringOrNil(strPtr *string, maxLen int) interface{} {
if strPtr == nil {
return nil
}
return TruncToBytes(*strPtr, maxLen)
}
// DatabaseExists - checks if database stored in context exists
// If closeConn is true - then it closes connection after checking if database exists
// If closeConn is false, then it returns open connection to default database "postgres"
func DatabaseExists(ctx *Ctx, closeConn bool) (exists bool, c *sql.DB) {
// We cannot connect to database stored in context, because it is possible it's not there
db := ctx.PgDB
ctx.PgDB = "postgres"
// Connect to Postgres DB using its default database "postgres"
c = PgConn(ctx)
if closeConn {
defer func() {
FatalOnError(c.Close())
c = nil
}()
}
// Try to get database name from `pg_database` - it will return row if database exists
rows := QuerySQLWithErr(c, ctx, "select 1 from pg_database where datname = $1", db)
defer func() { FatalOnError(rows.Close()) }()
for rows.Next() {
exists = true
}
FatalOnError(rows.Err())
// Restore original database name in the context
ctx.PgDB = db
return
}
// DropDatabaseIfExists - drops requested database if exists
// Returns true if database existed and was dropped
func DropDatabaseIfExists(ctx *Ctx) bool {
// Check if database exists
exists, c := DatabaseExists(ctx, false)
defer func() { FatalOnError(c.Close()) }()
// Drop database if exists
if exists {
ExecSQLWithErr(c, ctx, "drop database "+ctx.PgDB)
}
// Return whatever we created DB or not
return exists
}
// CreateDatabaseIfNeeded - creates requested database if not exists
// Returns true if database was not existing existed and created dropped
func CreateDatabaseIfNeeded(ctx *Ctx) bool {
// Check if database exists
exists, c := DatabaseExists(ctx, false)
defer func() { FatalOnError(c.Close()) }()
// Create database if not exists
if !exists {
ExecSQLWithErr(c, ctx, "create database "+ctx.PgDB)
}
// Return whatever we created DB or not
return !exists
}
// CreateDatabaseIfNeededExtended - creates requested database if not exists
// Returns true if database was not existing existed and created dropped
// Allows specifying additional database parameters
func CreateDatabaseIfNeededExtended(ctx *Ctx, extraParams string) bool {
// Check if database exists
exists, c := DatabaseExists(ctx, false)
defer func() { FatalOnError(c.Close()) }()
// Create database if not exists
if !exists {
ExecSQLWithErr(c, ctx, "create database "+ctx.PgDB+" "+extraParams)
}
// Return whatever we created DB or not
return !exists
}