-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.go
1311 lines (1043 loc) · 27.2 KB
/
db.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 pitchfork
import (
"bufio"
"database/sql"
"errors"
"fmt"
pq "github.com/lib/pq"
"os"
"runtime/debug"
"strconv"
"strings"
)
var ErrNoRows = sql.ErrNoRows
type DB_AndOr int
const (
DB_OP_AND DB_AndOr = iota
DB_OP_OR
)
type DB_Op int
const (
DB_OP_LIKE DB_Op = iota
DB_OP_ILIKE
DB_OP_EQ
DB_OP_NE
DB_OP_LE
DB_OP_GE
)
type PfDB struct {
sql *sql.DB
version int
appversion int
username string
verbosity bool
silence bool
}
type PfQuery struct {
query string
desc string
failok bool
failstr string
}
type Tx struct {
*sql.Tx
}
type Rows struct {
q string
p []interface{}
rows *sql.Rows
db *PfDB
}
type Row struct {
q string
p []interface{}
row *sql.Row
db *PfDB
}
/* Global database variable - there can only be one */
var DB PfDB
func DB_Init(verbosity bool) {
DB.Init(verbosity)
}
func DB_SetAppVersion(ver int) {
DB.SetAppVersion(ver)
}
/*
* Check for a Unique Violation
*
* "duplicate key value violates unique constraint"
*/
func DB_IsPQErrorConstraint(err error) bool {
/* Attempt to cast to a libpq error */
pqerr, ok := err.(*pq.Error)
/*
* From https://github.com/lib/pq/blob/master/error.go
* "23505": "unique_violation"
*/
if ok && pqerr.Code == "23505" {
return true
}
return false
}
func (db *PfDB) Init(verbosity bool) {
db.sql = nil
/* Current portal_schema_version -- must match schema.sql! */
db.version = 21
/* No configured App DB */
db.appversion = -1
/* Query Logging? */
db.verbosity = verbosity
}
func (db *PfDB) SetAppVersion(version int) {
db.appversion = version
}
func (db *PfDB) Silence(braaf bool) {
db.silence = braaf
}
func (db *PfDB) Verb(message string) {
if db.verbosity {
OutA(Where(2) + " DB." + message)
}
}
func (db *PfDB) Verbf(format string, arg ...interface{}) {
if db.verbosity {
OutA(Where(2)+" DB."+format, arg...)
}
}
func (db *PfDB) Err(message string) {
OutA(Where(2) + " DB." + message)
}
func (db *PfDB) Errf(format string, arg ...interface{}) {
OutA(Where(2)+" DB."+format, arg...)
}
func ToNullString(s string) sql.NullString {
return sql.NullString{String: s, Valid: s != ""}
}
func ToNullInt64(v int64) sql.NullInt64 {
return sql.NullInt64{Int64: v, Valid: true}
}
/* Connect to the database */
func (db *PfDB) connect(dbname string, host string, port string, username string, password string) (err error) {
/* Already connected, then don't do it again */
if db.sql != nil {
return nil
}
if dbname == "" {
return errors.New("No database name provided")
}
var str string
if host != "" {
str += "host=" + host + " "
}
if port != "" {
str += "port=" + port + " "
}
if username != "" {
str += "user=" + username + " "
}
if password != "" {
str += "password=" + password + " "
}
str += "dbname=" + dbname + " "
/* Don't require SSL */
str += "sslmode=" + Config.Db_ssl_mode + " "
db.Verbf("connect: %s", str)
/* "postgres" here is the driver */
db.sql, err = sql.Open("postgres", str)
/*
* If no errors, record the username we connected as
* Used to test if providing no context to exec() is correct
*/
if err != nil {
db.username = username
}
return err
}
func (db *PfDB) disconnect() {
if db.sql != nil {
db.sql.Close()
db.sql = nil
}
}
func (db *PfDB) Connect_def() (err error) {
return db.connect(Config.Db_name, Config.Db_host, Config.Db_port, Config.Db_user, Config.Db_pass)
}
func (db *PfDB) connect_pg(dbname string) (err error) {
db.disconnect()
return db.connect(dbname, Config.Db_host, Config.Db_port, Config.Db_admin_user, Config.Db_admin_pass)
}
func (db *PfDB) TxBegin(ctx PfCtx) (err error) {
err = db.Connect_def()
if err != nil {
return err
}
var stx *sql.Tx
stx, err = db.sql.Begin()
if err != nil {
ctx.SetTx(nil)
db.Errf("TxBegin() failed: %s", err.Error())
} else {
ctx.SetTx(&Tx{stx})
db.Verb("TxBegin()")
}
return err
}
func (db *PfDB) TxRollback(ctx PfCtx) {
tx := ctx.GetTx()
if tx == nil {
panic("TxRollback() Transaction was not open")
}
err := tx.Rollback()
if err != nil {
db.Errf("TxRollback() failed: %s", err.Error())
} else {
db.Verb("TxRollback() Ok")
}
/* No Transaction anymore */
ctx.SetTx(nil)
return
}
func (db *PfDB) TxCommit(ctx PfCtx) (err error) {
tx := ctx.GetTx()
if tx == nil {
err = errors.New("Transaction was not open")
return
}
err = tx.Commit()
ctx.SetTx(nil)
if err != nil {
db.Verbf("TxCommit() %s", err.Error())
} else {
db.Verb("TxCommit() Ok")
}
return
}
func (db *PfDB) QI(name string) string {
return pq.QuoteIdentifier(name)
}
func (db *PfDB) IsSelect(query string) (ok bool) {
if len(query) >= 6 && query[0:6] != "SELECT" {
return false
}
return true
}
func (db *PfDB) audit(ctx PfCtx, audittxt string, query string, args ...interface{}) (err error) {
/*
* No context is available when using tsetup
* which means we are executing as the 'postgres' user
*/
if ctx == nil {
/*
* We do not audit changes in this situation
* Users with 'postgres' access can modify the tables directly
*/
return
}
/* Require an audittxt when we get here */
if audittxt == "" {
panic("No audittxt provided")
}
/* Format the Audit String */
logmsg, aerr := db.formatQuery(audittxt, args...)
if aerr != nil {
ctx.Errf("DB.audit: Could not format audit string: '%s': %s", audittxt, aerr.Error())
return
}
var member interface{}
var user_name interface{}
var tg_name interface{}
var remote string
member = nil
user_name = nil
tg_name = nil
remote = ""
if ctx != nil {
if ctx.IsLoggedIn() {
member = ctx.TheUser().GetUserName()
}
if ctx.HasSelectedUser() {
user_name = ctx.SelectedUser().GetUserName()
}
if ctx.HasSelectedGroup() {
tg_name = ctx.SelectedGroup().GetGroupName()
}
remote = ctx.GetRemote()
}
q := "INSERT INTO audit_history " +
"(member, what, username, trustgroup, remote) " +
"VALUES($1, $2, $3, $4, $5)"
err = db.exec(ctx, true, 1, q, member, logmsg, user_name, tg_name, remote)
/* Note: audit insertion errors are logged, not reported to the user */
if err != nil {
if Debug {
db.Errf("exec(%s)[%v] audit error: %s", query, args, err.Error())
}
err = errors.New("Auditing error, please check the logs")
}
return
}
/* Wrapper functions, ensuring database is connected */
func (db *PfDB) Query(query string, args ...interface{}) (trows *Rows, err error) {
var rows *sql.Rows
if !db.IsSelect(query) {
/* Software mistake -- crash and burn */
Errf("Audittxt not set; query: %q, args %#v", query, args)
panic("Non-select queries require an audit message")
}
err = db.Connect_def()
if err != nil {
return nil, err
}
db.Verbf("QueryA: %s %#v", query, args)
rows, err = db.sql.Query(query, args...)
if err != nil {
db.Errf("Query(%s)[%#v] error: %s", query, args, err.Error())
/* When in debug mode, dump & exit, so we can trace it */
if Debug {
debug.PrintStack()
os.Exit(-1)
}
err = errors.New("SQL Query failed")
}
return &Rows{query, args, rows, db}, err
}
func (db *PfDB) queryrow(ctx PfCtx, audittxt string, query string, args ...interface{}) (trow *Row) {
var row *sql.Row
err := db.Connect_def()
if err != nil {
/* Does not report error */
return nil
}
/* Transaction already in progress? */
local_tx := false
if audittxt != "" && ctx != nil && ctx.GetTx() == nil {
/* Create a local one */
local_tx = true
err = db.TxBegin(ctx)
if err != nil {
return
}
}
if db.verbosity && !db.silence {
db.Verbf("QueryRow: %s [%v]", query, args)
}
row = db.sql.QueryRow(query, args...)
if audittxt != "" {
err = db.audit(ctx, audittxt, query, args...)
}
/* Commit the Tx if we opened it */
if local_tx {
if err != nil {
db.TxRollback(ctx)
} else {
err = db.TxCommit(ctx)
}
}
return &Row{query, args, row, db}
}
/* Query for a Row, without Audittxt; use with care */
func (db *PfDB) QueryRowNA(query string, args ...interface{}) (trow *Row) {
return db.queryrow(nil, "", query, args...)
}
/* Query for a Row, with an Audittxt for situations where the query is an INSERT/UPDATE with RETURNING */
func (db *PfDB) QueryRowA(ctx PfCtx, audittxt string, query string, args ...interface{}) (trow *Row) {
if audittxt == "" && !db.IsSelect(query) {
/* Software mistake -- crash and burn */
panic("Non-select queries require an audit message")
}
return db.queryrow(ctx, audittxt, query, args...)
}
/* Query for a Row, SELECT() only; thus no audittxt needed as nothing changes */
func (db *PfDB) QueryRow(query string, args ...interface{}) (trow *Row) {
return db.QueryRowA(nil, "", query, args...)
}
func (rows *Rows) Scan(args ...interface{}) (err error) {
err = rows.rows.Scan(args...)
switch {
case err == ErrNoRows:
break
case err != nil:
rows.db.Errf("Rows.Scan(%s)[%v] error: %s", rows.q, rows.p, err.Error())
break
default:
err = nil
break
}
return err
}
func (rows *Rows) Next() bool {
return rows.rows.Next()
}
func (rows *Rows) Close() {
if rows != nil && rows.rows != nil {
rows.rows.Close()
}
}
func (row *Row) Scan(args ...interface{}) (err error) {
if row.row == nil {
return ErrNoRows
}
err = row.row.Scan(args...)
switch {
case err == ErrNoRows:
break
case err != nil:
row.db.Errf("Row.Scan(%s)[%v] error: %s", row.q, row.p, err.Error())
break
default:
err = nil
break
}
return
}
func (db *PfDB) formatQuery(q string, args ...interface{}) (str string, err error) {
str = ""
for i := 0; i < len(q); i++ {
/* Find a dollar */
if q[i] != '$' {
str += string(q[i])
continue
}
/* Double $ ($$) thus skip it */
if q[i+1] == '$' {
str += string(q[i])
i++
continue
}
argnum_s := ""
argnum := 0
i++ /* Start looking at the char after '$' */
for i < len(q) && q[i] >= '0' && q[i] <= '9' {
argnum_s += string(q[i])
i++
}
i-- /* Back up one car, it was not part of the argnum */
/* Convert the argnum string to int */
argnum, err = strconv.Atoi(argnum_s)
if err != nil {
return
}
if argnum == 0 {
str = ""
err = errors.New("Invalid argument number 0")
return
}
/* Arguments start count at 1, array at 0 */
argnum--
if argnum > len(args) {
str = ""
err = errors.New("Argument " + strconv.Itoa(argnum) + " not provided")
return
}
/* Replace the variable with an argument */
str += ToString(args[argnum])
}
return
}
/* PfCtx contains selected User & group, the changed object matches these */
func (db *PfDB) exec(ctx PfCtx, report bool, affected int64, query string, args ...interface{}) (err error) {
err = db.Connect_def()
if err != nil {
return err
}
var res sql.Result
if ctx != nil && ctx.GetTx() != nil {
db.Verbf("exec(%s) Tx args: %v", query, args)
res, err = ctx.GetTx().Exec(query, args...)
} else {
db.Verbf("exec(%s) args: %v", query, args)
res, err = db.sql.Exec(query, args...)
}
/* When in debug mode, dump & exit, so we can trace it */
if err != nil && Debug {
db.Errf("exec(%s)[%v] error: %s", query, args, err.Error())
debug.PrintStack()
db.Errf("exec(%s) error: %s", query, err.Error())
os.Exit(-1)
}
if report && err != nil {
db.Errf("exec(%s)[%v] error: %s", query, args, err.Error())
/*
* Callers should never show raw SQL error messages
* these are logged, with the above in the log.
*
* The below message should never been by a user.
*
* Callers should replace the error message with a
* message like "XYZ did not work" instead.
*
* To avoid accidental leakage, we'll replace the message
* here already.
*/
err = errors.New("Please check the server log for the exact error message")
}
/* Check the number of affected rows */
if err == nil && affected != -1 {
chg, _ := res.RowsAffected()
if chg != affected {
/* Return "no rows changed" error */
if affected == 1 && chg == 0 {
err = ErrNoRows
return
}
/*
* Current this only generate a log entry, no golang error
*
* TODO: when all code has been properly tested, change this to returning an error
*/
db.Errf("exec(%s)[%#v] expected %d row(s) changed, but %d changed", query, args, affected, chg)
return
}
}
return
}
/* Exec that does not require audittxt */
func (db *PfDB) execA(ctx PfCtx, audittxt string, affected int64, query string, args ...interface{}) (err error) {
/* Transaction already in progress? */
local_tx := false
if ctx != nil && ctx.GetTx() == nil {
/* Create a local one */
local_tx = true
err = db.TxBegin(ctx)
if err != nil {
return
}
}
/* Attempt to execute the query */
err = db.exec(ctx, true, affected, query, args...)
if err != nil {
/* Exec failed, thus nothing to log either as nothing changed */
if local_tx {
db.TxRollback(ctx)
}
return
}
if audittxt != "" {
err = db.audit(ctx, audittxt, query, args...)
}
/* Commit the Tx if we opened it */
if local_tx {
if err != nil {
db.TxRollback(ctx)
} else {
err = db.TxCommit(ctx)
}
}
return
}
func (db *PfDB) ExecNA(affected int64, query string, args ...interface{}) (err error) {
return db.execA(nil, "", affected, query, args...)
}
/* Exec() with forced requirement for audit message */
func (db *PfDB) Exec(ctx PfCtx, audittxt string, affected int64, query string, args ...interface{}) (err error) {
if audittxt == "" {
panic("db.Exec() given no audittxt")
}
return db.execA(ctx, audittxt, affected, query, args...)
}
func (db *PfDB) Increase(ctx PfCtx, audittxt, table string, ident string, what string) (err error) {
if audittxt == "" {
audittxt = "Increased " + table + "." + what
}
q := "UPDATE " + db.QI(table) + " " +
"SET " + db.QI(what) + " = " + db.QI(what) + " + 1 " +
"WHERE ident = $1"
err = db.Exec(ctx, audittxt, 1, q, ident)
return
}
func (db *PfDB) set(ctx PfCtx, audittxt string, obj interface{}, table string, idents map[string]string, what string, val interface{}) (updated bool, err error) {
var args []interface{}
q := "UPDATE " + db.QI(table) + " " +
"SET " + db.QI(what) + " = "
db.Q_AddArg(&q, &args, val)
for key, value := range idents {
db.Q_AddWhere(&q, &args, key, "=", value, true, false, 1)
}
err = db.Exec(ctx, audittxt, -1, q, args...)
if err == nil {
updated = true
err = StructMod(STRUCTOP_SET, obj, what, val)
}
return
}
func (db *PfDB) UpdateFieldMulti(ctx PfCtx, obj interface{}, idents map[string]string, table string, what string, val string, checkperms bool) (updated bool, err error) {
var ftype string
var fname string
var fval string
/* Not updated yet */
updated = false
/* Get the details of what we are updating and check if the field exists */
ftype, fname, fval, err = StructDetails(ctx, obj, what, SD_Tags_Require)
if err != nil {
return
}
/* Normalize booleans */
if ftype == "bool" {
fval = NormalizeBoolean(fval)
val = NormalizeBoolean(val)
}
/* Is the value still the same? */
if fval == val {
return
}
audittxt := "Update " + table + ": "
/* build ident structure */
for key, value := range idents {
audittxt += key + " = " + value + " "
}
audittxt += " property " + fname
/* Log the new value unless it is a password or an image */
switch fname {
case "password", "passwd_chat", "passwd_jabber", "image":
break
default:
audittxt += " from '" + fval + "' to '" + val + "'"
break
}
switch ftype {
case "string":
return db.set(ctx, audittxt, obj, table, idents, fname, val)
case "int":
var v int
v, err = strconv.Atoi(val)
if err != nil {
return
}
return db.set(ctx, audittxt, obj, table, idents, fname, v)
case "bool":
v := IsTrue(val)
return db.set(ctx, audittxt, obj, table, idents, fname, v)
default:
break
}
err = errors.New("Unknown Type: " + ftype)
return
}
func (db *PfDB) UpdateFieldNP(ctx PfCtx, obj interface{}, ident string, table string, what string, val string) (updated bool, err error) {
idents := make(map[string]string)
idents["ident"] = ident
return db.UpdateFieldMulti(ctx, obj, idents, table, what, val, false)
}
func (db *PfDB) UpdateField(ctx PfCtx, obj interface{}, ident string, table string, what string, val string) (updated bool, err error) {
idents := make(map[string]string)
idents["ident"] = ident
return db.UpdateFieldMulti(ctx, obj, idents, table, what, val, true)
}
func (db *PfDB) UpdateFieldMsg(ctx PfCtx, obj interface{}, ident string, table string, what string, val string) (err error) {
idents := make(map[string]string)
idents["ident"] = ident
return db.UpdateFieldMultiMsg(ctx, obj, idents, table, what, val)
}
func (db *PfDB) UpdateFieldMultiMsg(ctx PfCtx, obj interface{}, set map[string]string, table string, what string, val string) (err error) {
var updated bool
updated, err = db.UpdateFieldMulti(ctx, obj, set, table, what, val, true)
if err == nil {
/* These strings are parsed by handleForm() for counting updated fields */
if updated {
ctx.OutLn("Updated %s", what)
} else {
ctx.OutLn("Value for %s was already the requested value", what)
}
}
return
}
func (db *PfDB) GetSchemaVersion() (version int, err error) {
q := "SELECT value " +
"FROM schema_metadata " +
"WHERE key = 'portal_schema_version'"
DB.Silence(true)
err = DB.QueryRow(q).Scan(&version)
DB.Silence(false)
return
}
func (db *PfDB) GetAppSchemaVersion() (version int, err error) {
q := "SELECT value " +
"FROM schema_metadata " +
"WHERE key = 'app_schema_version'"
DB.Silence(true)
err = DB.QueryRow(q).Scan(&version)
DB.Silence(false)
return
}
/* Checks that our schema version is matching what we expect */
func (db *PfDB) Check() (msg string, err error) {
msg = ""
ver, err := db.GetSchemaVersion()
if err != nil {
err = errors.New("System Schema Version: " + err.Error())
return
}
run_ver := strconv.Itoa(ver)
req_ver := strconv.Itoa(db.version)
msg = "Pitchfork Database schema versions: "
msg += "running: " + run_ver + ", "
msg += "required: " + req_ver + "\n"
err = nil
if ver > db.version {
err = errors.New("Futuristic System Database schema already in place (" + run_ver + " > " + req_ver + ")")
} else if ver < db.version {
err = errors.New("System Database is outdated (" + run_ver + " > " + req_ver + ")")
}
if err != nil {
return
}
/* No configured App DB version? */
if db.appversion == -1 {
return
}
appver, err := db.GetAppSchemaVersion()
if err == ErrNoRows {
/* No AppSchema, thus nothing to report */
err = nil
return
}
if err != nil {
err = errors.New("App Schema Version: " + err.Error())
return
}
run_ver = strconv.Itoa(appver)
req_ver = strconv.Itoa(db.appversion)
msg += "App Database schema versions: "
msg += "running: " + run_ver + ", "
msg += "required: " + req_ver + "\n"
if appver > db.appversion {
err = errors.New("Futuristic App Database schema already in place (" + run_ver + " > " + req_ver + ")")
} else if appver < db.appversion {
err = errors.New("App Database is outdated (" + run_ver + " > " + req_ver + ")")
}
return
}
func (db *PfDB) SizeReport(num int) (sizes [][]string, err error) {
sizes = nil
q := "SELECT relname, " +
"pg_size_pretty(pg_total_relation_size(C.oid)) " +
"FROM pg_class C " +
"LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) " +
"WHERE nspname NOT IN ('pg_catalog', 'information_schema') " +
"AND C.relkind <> 'i' " +
"AND nspname !~ '^pg_toast' " +
"ORDER BY pg_total_relation_size(C.oid) DESC " +
"LIMIT $1"
rows, err := DB.Query(q, num)
if err != nil {
return
}
defer rows.rows.Close()
for rows.rows.Next() {
var s = []string{"", ""}
err = rows.rows.Scan(&s[0], &s[1])
if err != nil {
sizes = nil
return
}
sizes = append(sizes, s)
}
return
}
func (db *PfDB) QueryFix(q string) (f string) {
f = q
f = strings.Replace(f, "<<DB>>", db.QI(Config.Db_name), -1)
f = strings.Replace(f, "<<USER>>", db.QI(Config.Db_user), -1)
f = strings.Replace(f, "<<PASS>>", Config.Db_pass, -1)
return f
}
/*
* Execute series of queries while replacing variables
*
* These queries are *NOT* audit-logged
* Only code that should call this are DB upgrade scripts
*/
func (db *PfDB) queries(f string, qs []PfQuery) (err error) {
for _, o := range qs {
q := db.QueryFix(o.query)
fmt.Println(f + " * " + o.desc)
err = db.exec(nil, false, -1, q)
/* Some things are expected to go wrong */
if err != nil {
e := err.Error()
f := db.QueryFix(o.failstr)
// fmt.Println(f + " - error: " + e)
if o.failok {
/* Ignore the failure */
} else if f != "" && e == f {
/* Ignore the failure */
} else {
/* Fail */
return
}
}
}
/* All okay */
err = nil
return
}
func (db *PfDB) Cleanup_psql() (err error) {
f := "Cleanup_psql"
fmt.Println(f + " - Connecting to database named 'postgres'")
/* Connect to the *postgres* database as postgres user, as we are cleaning up */
err = DB.connect_pg(Config.Db_admin_db)
if err != nil {
return
}
var qs = []PfQuery{
{"DROP DATABASE <<DB>>",
"Destroying database",
false, "pq: database <<DB>> does not exist"},
{"DROP USER <<USER>>",
"Destroying users",
false, "pq: role <<USER>> does not exist"},
}
err = DB.queries(f, qs)
if err != nil {
fmt.Printf("Error: %s", err.Error())
}
return
}