-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgext.go
975 lines (872 loc) · 26 KB
/
pgext.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
// Package pgxs provides useful boilerplate code for making a PostgreSQL
// extension (pgxs). This file is almost exactly from the repository at
// gitlab.com/microo8/plgo. The changes made here are to allow it to be imported
// as a module from another project that wants to make an extension, as opposed
// to actually copying and rewriting portions of the source file into every
// extension package that uses it.
//
// The main things provided in this package are convenient helpers for
// converting to/from the PostgreSQL Datum type, reading and scanning values
// from the function call info struct used as the input to functions, types for
// reading and processing trigger data when a struct is called as a trigger, and
// writing messages to the error or notice logger.
package pgxs
// NOTE: the build command specified the postgres include path as opposed to:
// CGO_CFLAGS='-I"/usr/include/postgresql/16/server" -fpic' CGO_LDFLAGS='-shared' go build -v -buildmode=c-shared
/*
#cgo LDFLAGS: -shared
#cgo darwin LDFLAGS: -undefined dynamic_lookup
typedef unsigned int uint;
#include "stdlib.h"
#include "postgres.h"
#include "fmgr.h"
#include "pgtime.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/timestamp.h"
#include "utils/array.h"
#include "utils/elog.h"
#include "executor/spi.h"
#include "parser/parse_type.h"
#include "commands/trigger.h"
#include "utils/rel.h"
#include "utils/lsyscache.h"
#include "utils/jsonb.h"
int __varsize(void *var) {
return VARSIZE(var);
}
int __varsize_any(void *var) {
return VARSIZE_ANY_EXHDR(var);
}
void elog_notice(char* string) {
elog(NOTICE, string, "");
}
void elog_error(char* string) {
elog(ERROR, string, "");
}
short get_nargs(PG_FUNCTION_ARGS) {
return PG_NARGS();
}
Datum get_arg(PG_FUNCTION_ARGS, uint i) {
return PG_GETARG_DATUM(i);
}
HeapTuple get_heap_tuple(HeapTuple* ht, uint i) {
return ht[i];
}
Datum get_col_as_datum(HeapTuple ht, TupleDesc td, int colnumber) {
bool isNull;
Datum ret = SPI_getbinval(ht, td, colnumber + 1, &isNull);
if (isNull) PG_RETURN_VOID();
return ret;
}
bool called_as_trigger(PG_FUNCTION_ARGS) {
return CALLED_AS_TRIGGER(fcinfo);
}
Datum get_heap_getattr(HeapTuple ht, uint i, TupleDesc td) {
bool isNull;
Datum ret = heap_getattr(ht, i, td, &isNull);
if (isNull) PG_RETURN_VOID();
return ret;
}
// val to datum
Datum null_datum(PG_FUNCTION_ARGS) {
PG_RETURN_NULL();
}
Datum void_datum() {
PG_RETURN_VOID();
}
Datum bytes_to_datum(void *val, uint len) {
void *v = (void *)palloc(len + VARHDRSZ);
SET_VARSIZE(v, len + VARHDRSZ);
memcpy(VARDATA(v), val, len);
return PointerGetDatum(v);
}
Datum cstring_to_datum(char *val) {
return CStringGetDatum(cstring_to_text(val));
}
Datum date_to_datum(DateADT val){
return DateADTGetDatum(val);
}
Datum time_to_datum(TimeADT val){
return TimestampGetDatum(val);
}
Datum timetz_to_datum(TimestampTz val) {
return TimestampTzGetDatum(val);
}
Datum heap_tuple_to_datum(HeapTuple val) {
return PointerGetDatum(val);
}
Datum array_to_datum(Oid element_type, Datum* vals, int size) {
ArrayType *result;
bool* isnull = (bool *)palloc0(sizeof(bool)*size);
int dims[1];
int lbs[1];
int16 typlen;
bool typbyval;
char typalign;
dims[0] = size;
lbs[0] = 1;
// get required info about the element type
get_typlenbyvalalign(element_type, &typlen, &typbyval, &typalign);
result = construct_md_array(vals, isnull, 1, dims, lbs,
element_type, typlen, typbyval, typalign);
PG_RETURN_ARRAYTYPE_P(result);
}
Datum jsonb_to_datum(char* val) {
return (Datum) DatumGetJsonbP(DirectFunctionCall1(jsonb_in, (Datum) (char *) val));
}
// Datum to vals
char* datum_to_cstring(Datum val) {
return DatumGetCString(text_to_cstring((struct varlena *)val));
}
bytea* datum_to_byteap(Datum val) {
return DatumGetByteaPP((struct varlena *)val);
}
unsigned char * bytea_to_chars(bytea* val) {
return ((unsigned char *)VARDATA_ANY(val));
}
DateADT datum_to_date(Datum val) {
return DatumGetDateADT(val);
}
Timestamp datum_to_time(Datum val) {
return DatumGetTimestamp(val);
}
TimestampTz datum_to_timetz(Datum val) {
return DatumGetTimestampTz(val);
}
HeapTuple datum_to_heap_tuple(Datum val) {
return (HeapTuple) DatumGetPointer(val);
}
Datum* datum_to_array(Datum val, int* nelemsp) {
ArrayType* array = DatumGetArrayTypeP(val);
int16 typlen;
bool typbyval;
char typalign;
Datum *result;
bool *nullsp;
get_typlenbyvalalign(ARR_ELEMTYPE(array), &typlen, &typbyval, &typalign);
deconstruct_array(array, ARR_ELEMTYPE(array),
typlen, typbyval, typalign,
&result, &nullsp, nelemsp);
return result;
}
char* unknown_to_char(Datum val) {
return (char*)val;
}
char* datum_to_jsonb_cstring(Datum val) {
Jsonb *jsonb = DatumGetJsonbP(val);
return JsonbToCString(NULL, &jsonb->root, VARSIZE(jsonb));
}
// TriggerData functions
bool trigger_fired_before(TriggerEvent tg_event) {
return TRIGGER_FIRED_BEFORE(tg_event);
}
bool trigger_fired_after(TriggerEvent tg_event) {
return TRIGGER_FIRED_AFTER(tg_event);
}
bool trigger_fired_instead(TriggerEvent tg_event) {
return TRIGGER_FIRED_INSTEAD(tg_event);
}
bool trigger_fired_for_row(TriggerEvent tg_event) {
return TRIGGER_FIRED_FOR_ROW(tg_event);
}
bool trigger_fired_for_statement(TriggerEvent tg_event) {
return TRIGGER_FIRED_FOR_STATEMENT(tg_event);
}
bool trigger_fired_by_insert(TriggerEvent tg_event) {
return TRIGGER_FIRED_BY_INSERT(tg_event);
}
bool trigger_fired_by_update(TriggerEvent tg_event) {
return TRIGGER_FIRED_BY_UPDATE(tg_event);
}
bool trigger_fired_by_delete(TriggerEvent tg_event) {
return TRIGGER_FIRED_BY_DELETE(tg_event);
}
bool trigger_fired_by_truncate(TriggerEvent tg_event) {
return TRIGGER_FIRED_BY_TRUNCATE(tg_event);
}
*/
import "C"
import (
"encoding/json"
"errors"
"fmt"
"log"
"time"
"unsafe"
)
// Datum is the return type of postgresql
type Datum C.Datum
func scanVal(oid C.Oid, typeName string, val C.Datum, arg interface{}) error {
switch targ := arg.(type) {
case *string:
switch oid {
case C.TEXTOID:
*targ = C.GoString(C.datum_to_cstring(val))
case C.UNKNOWNOID:
*targ = C.GoString(C.unknown_to_char(val))
default:
return fmt.Errorf("Column type is not text %s", typeName)
}
case *int16:
switch oid {
case C.INT2OID:
*targ = int16(C.DatumGetInt16(val))
default:
return fmt.Errorf("Column type is not int16 %s", typeName)
}
case *uint16:
switch oid {
case C.INT2OID:
*targ = uint16(C.DatumGetInt16(val))
default:
return fmt.Errorf("Column type is not uint16 %s", typeName)
}
case *int32:
switch oid {
case C.INT4OID:
*targ = int32(C.DatumGetInt32(val))
default:
return fmt.Errorf("Column type is not int32 %s", typeName)
}
case *uint32:
switch oid {
case C.INT4OID:
*targ = uint32(C.DatumGetInt32(val))
default:
return fmt.Errorf("Column type is not uint32 %s", typeName)
}
case *int64:
switch oid {
case C.INT8OID:
*targ = int64(C.DatumGetInt64(val))
default:
return fmt.Errorf("Column type is not int64 %s", typeName)
}
case *int:
switch oid {
case C.INT2OID:
*targ = int(C.DatumGetInt16(val))
case C.INT4OID:
*targ = int(C.DatumGetInt32(val))
case C.INT8OID:
*targ = int(C.DatumGetInt64(val))
default:
return fmt.Errorf("Column type is not int %s", typeName)
}
case *uint:
switch oid {
case C.INT2OID:
*targ = uint(C.DatumGetInt16(val))
case C.INT4OID:
*targ = uint(C.DatumGetInt32(val))
case C.INT8OID:
*targ = uint(C.DatumGetInt64(val))
default:
return fmt.Errorf("Column type is not uint %s", typeName)
}
case *bool:
switch oid {
case C.BOOLOID:
*targ = C.DatumGetBool(val) == (C._Bool)(true)
default:
return fmt.Errorf("Column type is not bool %s", typeName)
}
case *float32:
switch oid {
case C.FLOAT4OID:
*targ = float32(C.DatumGetFloat4(val))
default:
return fmt.Errorf("Column type is not real %s", typeName)
}
case *float64:
switch oid {
case C.FLOAT8OID:
*targ = float64(C.DatumGetFloat8(val))
default:
return fmt.Errorf("Column type is not double precision %s", typeName)
}
case *[]uint8:
switch oid {
case C.BYTEAOID:
bytea := C.datum_to_byteap(val)
byteaPointer := unsafe.Pointer(bytea)
*targ = C.GoBytes(unsafe.Pointer(C.bytea_to_chars(bytea)), C.__varsize_any(byteaPointer))
default:
return fmt.Errorf("Column type is not bytea %s", typeName)
}
case *time.Time:
switch oid {
case C.DATEOID:
dateadt := C.datum_to_date(val)
*targ = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 0, int(dateadt))
case C.TIMESTAMPOID:
t := C.datum_to_time(val)
*targ = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Second * time.Duration(int64(t)/int64(C.USECS_PER_SEC)))
case C.TIMESTAMPTZOID:
t := C.datum_to_timetz(val)
*targ = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Second * time.Duration(int64(t)/int64(C.USECS_PER_SEC))).Local()
default:
return fmt.Errorf("Unsupported time type %s", typeName)
}
case *[]string:
slice := makeSlice(val)
*targ = make([]string, len(slice))
for i := range slice {
err := scanVal(C.TEXTOID, "Text", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]int16:
slice := makeSlice(val)
*targ = make([]int16, len(slice))
for i := range slice {
err := scanVal(C.INT2OID, "SMALLINT", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]uint16:
slice := makeSlice(val)
*targ = make([]uint16, len(slice))
for i := range slice {
err := scanVal(C.INT2OID, "SMALLINT", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]int32:
slice := makeSlice(val)
*targ = make([]int32, len(slice))
for i := range slice {
err := scanVal(C.INT4OID, "INT", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]uint32:
slice := makeSlice(val)
*targ = make([]uint32, len(slice))
for i := range slice {
err := scanVal(C.INT4OID, "INT", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]int64:
slice := makeSlice(val)
*targ = make([]int64, len(slice))
for i := range slice {
err := scanVal(C.INT8OID, "INT", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]int:
slice := makeSlice(val)
*targ = make([]int, len(slice))
for i := range slice {
err := scanVal(C.INT8OID, "INT", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]bool:
slice := makeSlice(val)
*targ = make([]bool, len(slice))
for i := range slice {
err := scanVal(C.BOOLOID, "BOOL", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]float32:
slice := makeSlice(val)
*targ = make([]float32, len(slice))
for i := range slice {
err := scanVal(C.FLOAT4OID, "REAL", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]float64:
slice := makeSlice(val)
*targ = make([]float64, len(slice))
for i := range slice {
err := scanVal(C.FLOAT8OID, "DOUBLE", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
case *[]time.Time:
slice := makeSlice(val)
*targ = make([]time.Time, len(slice))
for i := range slice {
err := scanVal(C.TIMESTAMPTZOID, "TIMETZ", slice[i], &((*targ)[i]))
if err != nil {
return err
}
}
default:
switch oid {
case C.JSONBOID:
jsonData := []byte(C.GoString(C.datum_to_jsonb_cstring(val)))
return json.Unmarshal(jsonData, arg)
case C.JSONOID:
jsonData := []byte(C.GoString(C.datum_to_cstring(val)))
return json.Unmarshal(jsonData, arg)
default:
return fmt.Errorf("Unsupported type in Scan (%T) %s", arg, typeName)
}
}
return nil
}
func makeArray[S ~[]E, E any](elemtype C.Oid, s S) Datum {
datums := make([]C.Datum, len(s))
for i := range s {
datums[i] = (C.Datum)(ToDatum(s[i]))
}
return (Datum)(C.array_to_datum(elemtype, &datums[0], C.int(len(s))))
}
func makeSlice(val C.Datum) []C.Datum {
var clength C.int
datumArray := C.datum_to_array(val, &clength)
return unsafe.Slice(datumArray, int(clength)) // old way: (*[1 << 30]C.Datum)(unsafe.Pointer(datumArray))[:length]
}
// ToDatum returns the Postgresql C type from Go type.
func ToDatum(val interface{}) Datum {
switch v := val.(type) {
case error:
s := C.CString(v.Error())
defer C.free(unsafe.Pointer(s))
return (Datum)(C.cstring_to_datum(s))
case string:
s := C.CString(v)
defer C.free(unsafe.Pointer(s))
return (Datum)(C.cstring_to_datum(s))
case []byte:
b := C.CBytes(v)
defer C.free(b)
return (Datum)(C.bytes_to_datum(b, C.uint(len(v))))
case int16:
return (Datum)(C.Int16GetDatum(C.int16(v)))
case uint16:
return (Datum)(C.UInt16GetDatum(C.uint16(v)))
case int32:
return (Datum)(C.Int32GetDatum(C.int32(v)))
case uint32:
return (Datum)(C.UInt32GetDatum(C.uint32(v)))
case int64:
return (Datum)(C.Int64GetDatum(C.int64(v)))
case int:
return (Datum)(C.Int64GetDatum(C.int64(v)))
case uint:
return (Datum)(C.UInt64GetDatum(C.uint64(v))) // or uint32?
case float32:
return (Datum)(C.Float4GetDatum(C.float(v)))
case float64:
return (Datum)(C.Float8GetDatum(C.double(v)))
case time.Time:
return (Datum)(C.timetz_to_datum(C.TimestampTz((v.UTC().Unix() - 946684800) * int64(C.USECS_PER_SEC)))) // January 1, 2000 UNIX time is 946684800
case bool:
return (Datum)(C.BoolGetDatum((C._Bool)(v)))
case []string:
return makeArray(C.TEXTOID, v)
case []int16:
return makeArray(C.INT2OID, v)
case []uint16:
return makeArray(C.INT2OID, v)
case []int32:
return makeArray(C.INT4OID, v)
case []uint32:
return makeArray(C.INT4OID, v)
case []int64:
return makeArray(C.INT8OID, v)
case []int:
return makeArray(C.INT8OID, v)
case []uint:
return makeArray(C.INT8OID, v)
case []float32:
return makeArray(C.FLOAT4OID, v)
case []float64:
return makeArray(C.FLOAT8OID, v)
case []bool:
return makeArray(C.BOOLOID, v)
case []time.Time:
return makeArray(C.TIMESTAMPTZOID, v)
case *TriggerRow:
if v == nil {
return (Datum)(0)
}
isNull := make([]C.bool, len(v.attrs))
for i, attr := range v.attrs {
if attr == 0 { // (C.Datum)(ToDatum(nil))
isNull[i] = (C._Bool)(true)
} else {
isNull[i] = (C._Bool)(false)
}
}
heapTuple := C.heap_form_tuple(v.tupleDesc, &v.attrs[0], &isNull[0])
return (Datum)(C.heap_tuple_to_datum(heapTuple))
default:
return (Datum)(C.void_datum())
}
}
// elogLevel Log level enum
type elogLevel int
// elogLevel constants
const (
noticeLevel elogLevel = iota
errorLevel
)
// elog represents the elog io.Writer to use with Logger
type elog struct {
Level elogLevel
}
// Write is an notify implemented as io.Writer
func (e *elog) Write(p []byte) (n int, err error) {
switch e.Level {
case noticeLevel:
cp := C.CString(string(p))
defer C.free(unsafe.Pointer(cp))
C.elog_notice(cp)
case errorLevel:
cp := C.CString(string(p))
defer C.free(unsafe.Pointer(cp))
C.elog_error(cp)
}
return len(p), nil
}
// NewNoticeLogger creates an logger that writes into NOTICE elog
func NewNoticeLogger(prefix string, flag int) *log.Logger {
return log.New(&elog{Level: noticeLevel}, prefix, flag)
}
// NewErrorLogger creates an logger that writes into ERROR elog
func NewErrorLogger(prefix string, flag int) *log.Logger {
return log.New(&elog{Level: errorLevel}, prefix, flag)
}
var globalErrorLogger = NewErrorLogger("", log.Ltime)
func LogError(msg string) {
globalErrorLogger.Print(msg)
}
var globalNoticeLogger = NewNoticeLogger("", log.Ltime)
func LogNotice(msg string) {
globalNoticeLogger.Print(msg)
}
// FuncInfo is the type of parameters that all functions get
type FuncInfo C.FunctionCallInfoBaseData
// CalledAsTrigger checks if the function is called as trigger
func (fcinfo *FuncInfo) CalledAsTrigger() bool {
return C.called_as_trigger((*C.struct_FunctionCallInfoBaseData)(unsafe.Pointer(fcinfo))) == (C._Bool)(true)
}
// TODO: Scan must return argument also if the function is called as trigger
// Scan sets the args to the function parameter values (converted from PostgreSQL types to Go types)
func (fcinfo *FuncInfo) Scan(args ...interface{}) error {
if int(fcinfo.nargs) != len(args) {
return errors.New("incorrect number of args")
}
for i, arg := range args {
funcArg := C.get_arg((*C.struct_FunctionCallInfoBaseData)(unsafe.Pointer(fcinfo)), C.uint(i))
argOid := C.get_call_expr_argtype(fcinfo.flinfo.fn_expr, C.int(i))
err := scanVal(argOid, "", funcArg, arg)
if err != nil {
return err
}
}
return nil
}
// TriggerData returns Trigger data, if the function was called as trigger, else nil
func (fcinfo *FuncInfo) TriggerData() *TriggerData {
if !fcinfo.CalledAsTrigger() {
return nil
}
cTriggerData := (*C.TriggerData)(unsafe.Pointer(fcinfo.context))
triggerData := &TriggerData{
tgEvent: cTriggerData.tg_event,
tgRelation: cTriggerData.tg_relation,
tgTrigger: cTriggerData.tg_trigger,
}
if triggerData.FiredByInsert() {
triggerData.OldRow = nil
triggerData.NewRow = newTriggerRow(cTriggerData.tg_relation.rd_att, cTriggerData.tg_trigtuple)
} else if triggerData.FiredByDelete() {
triggerData.OldRow = newTriggerRow(cTriggerData.tg_relation.rd_att, cTriggerData.tg_trigtuple)
triggerData.NewRow = nil
} else if triggerData.FiredByUpdate() {
triggerData.OldRow = newTriggerRow(cTriggerData.tg_relation.rd_att, cTriggerData.tg_trigtuple)
triggerData.NewRow = newTriggerRow(cTriggerData.tg_relation.rd_att, cTriggerData.tg_newtuple)
}
return triggerData
}
// TriggerData represents the data passed by the trigger manager
type TriggerData struct {
tgEvent C.TriggerEvent
tgRelation C.Relation
tgTrigger *C.Trigger
OldRow *TriggerRow
NewRow *TriggerRow
}
// FiredBefore returns true if the trigger fired before the operation.
func (td *TriggerData) FiredBefore() bool {
return bool(C.trigger_fired_before(td.tgEvent)) // == (C._Bool)(true)
}
// FiredAfter returns true if the trigger fired after the operation.
func (td *TriggerData) FiredAfter() bool {
return bool(C.trigger_fired_after(td.tgEvent)) // == (C._Bool)(true)
}
// FiredInstead returns true if the trigger fired instead of the operation.
func (td *TriggerData) FiredInstead() bool {
return bool(C.trigger_fired_instead(td.tgEvent)) // == (C._Bool)(true)
}
// FiredForRow returns true if the trigger fired for a row-level event.
func (td *TriggerData) FiredForRow() bool {
return bool(C.trigger_fired_for_row(td.tgEvent)) // == (C._Bool)(true)
}
// FiredForStatement returns true if the trigger fired for a statement-level event.
func (td *TriggerData) FiredForStatement() bool {
return bool(C.trigger_fired_for_statement(td.tgEvent)) // == (C._Bool)(true)
}
// FiredByInsert returns true if the trigger was fired by an INSERT command.
func (td *TriggerData) FiredByInsert() bool {
return bool(C.trigger_fired_by_insert(td.tgEvent)) // == (C._Bool)(true)
}
// FiredByUpdate returns true if the trigger was fired by an UPDATE command.
func (td *TriggerData) FiredByUpdate() bool {
return bool(C.trigger_fired_by_update(td.tgEvent)) // == (C._Bool)(true)
}
// FiredByDelete returns true if the trigger was fired by a DELETE command.
func (td *TriggerData) FiredByDelete() bool {
return bool(C.trigger_fired_by_delete(td.tgEvent)) // == (C._Bool)(true)
}
// FiredByTruncate returns true if the trigger was fired by a TRUNCATE command.
func (td *TriggerData) FiredByTruncate() bool {
return bool(C.trigger_fired_by_truncate(td.tgEvent)) // == (C._Bool)(true)
}
// TriggerRow is used in TriggerData as NewRow and OldRow
type TriggerRow struct {
tupleDesc C.TupleDesc
attrs []C.Datum
}
func newTriggerRow(tupleDesc C.TupleDesc, heapTuple C.HeapTuple) *TriggerRow {
row := &TriggerRow{tupleDesc, make([]C.Datum, int(tupleDesc.natts))}
if heapTuple == nil {
return nil
}
for i := 0; i < int(tupleDesc.natts); i++ {
row.attrs[i] = C.get_heap_getattr(heapTuple, C.uint(i+1), tupleDesc)
}
return row
}
// Scan sets the args from the TriggerRow
func (row *TriggerRow) Scan(args ...interface{}) error {
for i, arg := range args {
oid := C.SPI_gettypeid(row.tupleDesc, C.int(i+1))
typeName := C.SPI_gettype(row.tupleDesc, C.int(i+1))
err := scanVal(oid, C.GoString(typeName), row.attrs[i], arg)
if err != nil {
return err
}
}
return nil
}
// Set sets the i'th value in the row
func (row *TriggerRow) Set(i int, val interface{}) {
row.attrs[i] = (C.Datum)(ToDatum(val))
}
// DB represents the db connection, can be made only once
type DB struct{}
// Open returns DB connection and runs SPI_connect
func Open() (*DB, error) {
if C.SPI_connect() != C.SPI_OK_CONNECT {
return nil, errors.New("can't connect")
}
return new(DB), nil
}
// Close closes the DB connection
func (db *DB) Close() error {
if C.SPI_finish() != C.SPI_OK_FINISH {
return errors.New("Error closing DB")
}
return nil
}
// Stmt represents the prepared SQL statement
type Stmt struct {
spiPlan C.SPIPlanPtr
db *DB
typeIds []C.Oid
}
// Prepare prepares an SQL query and returns a Stmt that can be executed
// query - the SQL query
// types - an array of strings with type names from postgresql of the prepared query
func (db *DB) Prepare(query string, types []string) (*Stmt, error) {
var typeIds []C.Oid
var typeIdsP *C.Oid
if len(types) > 0 {
typeIds = make([]C.Oid, len(types))
var typmod C.int32
for i, t := range types {
ct := C.CString(t)
defer C.free(unsafe.Pointer(ct))
C.parseTypeString(ct, &typeIds[i], &typmod, nil)
}
typeIdsP = &typeIds[0]
}
cq := C.CString(query)
defer C.free(unsafe.Pointer(cq))
cplan := C.SPI_prepare(cq, C.int(len(types)), typeIdsP)
if cplan != nil {
return &Stmt{spiPlan: cplan, db: db, typeIds: typeIds}, nil
}
return nil, fmt.Errorf("Prepare failed: %s", C.GoString(C.SPI_result_code_string(C.SPI_result)))
}
// Query executes the prepared Stmt with the provided args and returns
// multiple Rows result, that can be iterated
func (stmt *Stmt) Query(args ...interface{}) (*Rows, error) {
valuesP, nullsP, err := stmt.spiArgs(args)
if err != nil {
return nil, err
}
rv := C.SPI_execute_plan(stmt.spiPlan, valuesP, nullsP, (C._Bool)(false), 0)
if rv == C.SPI_OK_SELECT && C.SPI_processed > 0 { // not a pointer?
return newRows(C.SPI_tuptable.vals, C.SPI_tuptable.tupdesc, C.uint64(C.SPI_processed)), nil
}
return nil, fmt.Errorf("Query failed: %s", C.GoString(C.SPI_result_code_string(C.SPI_result)))
}
// QueryRow executes the prepared Stmt with the provided args and returns one row result
func (stmt *Stmt) QueryRow(args ...interface{}) (*Row, error) {
valuesP, nullsP, err := stmt.spiArgs(args)
if err != nil {
return nil, err
}
rv := C.SPI_execute_plan(stmt.spiPlan, valuesP, nullsP, (C._Bool)(false), 1)
if rv >= C.int(0) && C.SPI_processed == 1 {
return &Row{
heapTuple: C.get_heap_tuple(C.SPI_tuptable.vals, C.uint(0)),
tupleDesc: C.SPI_tuptable.tupdesc,
}, nil
}
return nil, fmt.Errorf("QueryRow failed: %s", C.GoString(C.SPI_result_code_string(C.SPI_result)))
}
// Exec executes a prepared query Stmt with no result
func (stmt *Stmt) Exec(args ...interface{}) error {
valuesP, nullsP, err := stmt.spiArgs(args)
if err != nil {
return err
}
rv := C.SPI_execute_plan(stmt.spiPlan, valuesP, nullsP, (C._Bool)(false), 0)
if rv >= C.int(0) && C.SPI_processed == 0 {
return nil
}
if rv == C.SPI_OK_INSERT {
return nil
}
return fmt.Errorf("Exec failed: %s", C.GoString(C.SPI_result_code_string(C.SPI_result)))
}
func (stmt *Stmt) spiArgs(args []interface{}) (valuesP *C.Datum, nullsP *C.char, err error) {
if len(args) == 0 {
return
}
values := make([]Datum, len(args))
nulls := make([]C.char, len(args))
for i, arg := range args {
switch stmt.typeIds[i] {
case C.JSONBOID:
jsonData, err := json.Marshal(arg)
if err != nil {
return nil, nil, err
}
cjson := C.CString(string(jsonData))
defer C.free(unsafe.Pointer(cjson))
values[i] = (Datum)(C.jsonb_to_datum(cjson))
case C.JSONOID:
jsonData, err := json.Marshal(arg)
if err != nil {
return nil, nil, err
}
values[i] = ToDatum(string(jsonData))
default:
values[i] = ToDatum(arg)
}
nulls[i] = C.char(' ')
}
valuesP = (*C.Datum)(unsafe.Pointer(&values[0]))
nullsP = &nulls[0]
return
}
// Rows represents the result of running a prepared Stmt with Query
type Rows struct {
heapTuples []C.HeapTuple
tupleDesc C.TupleDesc
processed uint32
current C.HeapTuple
}
func newRows(heapTuples *C.HeapTuple, tupleDesc C.TupleDesc, processed C.uint64) *Rows {
rows := &Rows{
tupleDesc: tupleDesc,
processed: uint32(processed),
}
rows.heapTuples = make([]C.HeapTuple, rows.processed)
for i := 0; i < int(rows.processed); i++ {
rows.heapTuples[i] = C.get_heap_tuple(heapTuples, C.uint(i))
}
return rows
}
// Next sets the Rows to another row, returs false if there isn't another
// must be first called to set the Rows to the first row
func (rows *Rows) Next() bool {
if len(rows.heapTuples) == 0 {
return false
}
rows.current = rows.heapTuples[0]
rows.heapTuples = rows.heapTuples[1:]
return true
}
// Scan takes pointers to variables that will be filled with the values of the current row
func (rows *Rows) Scan(args ...interface{}) error {
for i, arg := range args {
val := C.get_col_as_datum(rows.current, rows.tupleDesc, C.int(i))
oid := C.SPI_gettypeid(rows.tupleDesc, C.int(i+1))
typeName := C.SPI_gettype(rows.tupleDesc, C.int(i+1))
err := scanVal(oid, C.GoString(typeName), val, arg)
if err != nil {
return err
}
}
return nil
}
// Columns returns the names of columns
func (rows *Rows) Columns() ([]string, error) {
var columns []string
for i := 1; ; i++ {
fname := C.SPI_fname(rows.tupleDesc, C.int(i))
if fname == nil {
break
}
if C.SPI_result == C.SPI_ERROR_NOATTRIBUTE {
return nil, fmt.Errorf("Error getting column names")
}
columns = append(columns, C.GoString(fname))
}
return columns, nil
}
// Row represents a single row from running a query
type Row struct {
tupleDesc C.TupleDesc
heapTuple C.HeapTuple
}
// Scan scans the args from Row
func (row *Row) Scan(args ...interface{}) error {
for i, arg := range args {
val := C.get_col_as_datum(row.heapTuple, row.tupleDesc, C.int(i))
oid := C.SPI_gettypeid(row.tupleDesc, C.int(i+1))
typeName := C.SPI_gettype(row.tupleDesc, C.int(i+1))
err := scanVal(oid, C.GoString(typeName), val, arg)
if err != nil {
return err
}
}
return nil
}