forked from psoo/table_log
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtable_log.c
2053 lines (1734 loc) · 49.5 KB
/
table_log.c
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
/*
* table_log () -- log changes to another table
*
*
* see README.md for details
*
*
* written by Andreas ' ads' Scherbaum (ads@pgug.de)
*
*/
#include "table_log.h"
#include <ctype.h> /* tolower () */
#include <string.h> /* strlen() */
#include "postgres.h"
#include "fmgr.h"
#include "executor/spi.h" /* this is what you need to work with SPI */
#include "catalog/namespace.h"
#include "commands/trigger.h" /* -"- and triggers */
#include "mb/pg_wchar.h" /* support for the quoting functions */
#include "miscadmin.h"
#include "lib/stringinfo.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/guc.h"
#include <utils/lsyscache.h>
#include <utils/rel.h>
#include <utils/timestamp.h>
#include <utils/syscache.h>
#include "funcapi.h"
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
#if PG_VERSION_NUM >= 100000
#include "utils/varlena.h" /* SplitIdentifierString */
#endif
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#if PG_VERSION_NUM < 100000
/* from src/include/access/tupdesc.h, introduced in 2cd708452 */
#define TupleDescAttr(tupdesc, i) ((tupdesc)->attrs[(i)])
#endif
/* for PostgreSQL >= 8.2.x */
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
#ifndef PG_NARGS
/*
* Get number of arguments passed to function.
* this macro isnt defined in 7.2.x
*/
#define PG_NARGS() (fcinfo->nargs)
#endif
/*
* Current active log table partition. Default is always zero.
*/
TableLogPartitionId tableLogActivePartitionId = 0;
/*
* table_log restore descriptor.
*
* Carries all information to restore data from a table_log table
*/
typedef struct
{
char *schema;
char *relname;
} TableLogRelIdent;
/*
* table_log logging descriptor for log triggers.
*/
typedef struct
{
/*
* Pointer to trigger data
*/
TriggerData *trigdata;
/*
* Number of columns of source table (excludes
* dropped columns!)
*/
int number_columns;
/*
* Number of columns of log table (excludes
* dropped columns!)
*/
int number_columns_log;
/*
* Name/schema of the log table
*/
TableLogRelIdent ident_log;
/*
* Log session user
*/
int use_session_user;
} TableLogDescr;
/*
* table_log restore descriptor structure.
*/
typedef struct
{
/* Non-qualified relation name
* of original table.
*/
char *orig_relname;
/*
* OID of original table, saved
* for cache lookup.
*/
Oid orig_relid;
/*
* List of attnums of original table part
* of the primary key or unique constraint. Only
* used in case of no explicit specified pk column.
* (see relationGetPrimaryKeyColumns() for details).
*/
AttrNumber *orig_pk_attnum;
/*
* Number of pk attributes in original tables.
*/
int orig_num_pk_attnums;
/*
* List of attribute names. The list index matches
* the attribute number stored in the orig_pk_attnum
* array.
*/
List *orig_pk_attr_names;
/*
* OID of log table.
*/
Oid log_relid;
/*
* Possible schema qualified relation name
* of log table.
*/
bool use_schema_log;
union
{
TableLogRelIdent ident_log;
char *relname_log;
};
/*
* Primary key column name of the log table.
*/
char *pkey_log;
/*
* OID of restore table.
*/
Oid restore_relid;
/*
* Possible schema qualified relation name
* of restore table.
*/
bool use_schema_restore;
union
{
TableLogRelIdent ident_restore;
char *relname_restore;
};
} TableLogRestoreDescr;
#define DESCR_TRIGDATA(a) \
(a).trigdata
#define DESCR_TRIGDATA_GET_TUPDESC(a) \
(a).trigdata->tg_relation->rd_att
#define DESCR_TRIGDATA_GET_RELATION(a) \
(a).trigdata->tg_relation
#define DESCR_TRIGDATA_GETARG(a, index) \
(a).trigdata->tg_trigger->tgargs[(index)]
#define DESCR_TRIGDATA_NARGS(a) \
(a).trigdata->tg_trigger->tgnargs
#define DESCR_TRIGDATA_GET_TUPLE(a) \
(a).trigdata->tg_trigtuple
#define DESCR_TRIGDATA_GET_NEWTUPLE(a) \
(a).trigdata->tg_newtuple
#define DESCR_TRIGDATA_LOG_SCHEMA(a) \
(a).trigdata->tg_trigger->tgargs[2]
#define DESCR_TRIGDATA_LOG_SESSION_USER(a) \
(a).trigdata->tg_trigger->tgargs[1]
#define RESTORE_TABLE_IDENT(a, type) \
((a.use_schema_##type ) \
? quote_qualified_identifier(a.ident_##type.schema, \
a.ident_##type.relname)\
: quote_identifier(a.relname_##type))
#if PG_VERSION_NUM < 90300
#define TABLE_LOG_NSPOID(a) LookupExplicitNamespace((a));
#else
#define TABLE_LOG_NSPOID(a) LookupExplicitNamespace((a), false);
#endif
void _PG_init(void);
Datum table_log(PG_FUNCTION_ARGS);
Datum table_log_basic(PG_FUNCTION_ARGS);
Datum table_log_restore_table(PG_FUNCTION_ARGS);
static char *do_quote_ident(char *iptr);
static char *do_quote_literal(char *iptr);
static void __table_log (TableLogDescr *descr,
char *changed_mode,
char *changed_tuple,
HeapTuple tuple);
static void table_log_prepare(TableLogDescr *descr);
static void table_log_finalize(void);
static void __table_log_restore_table_insert(SPITupleTable *spi_tuptable,
char *table_restore,
char *table_orig_pkey,
char *col_query_start,
int col_pkey,
int number_columns,
int i);
static void __table_log_restore_table_update(SPITupleTable *spi_tuptable,
char *table_restore,
char *table_orig_pkey,
char *col_query_start,
int col_pkey,
int number_columns,
int i,
char *old_key_string);
static void __table_log_restore_table_delete(SPITupleTable *spi_tuptable,
char *table_restore,
char *table_orig_pkey,
char *col_query_start,
int col_pkey,
int number_columns,
int i);
static char *__table_log_varcharout(VarChar *s);
static int count_columns (TupleDesc tupleDesc);
static void mapPrimaryKeyColumnNames(TableLogRestoreDescr *restore_descr);
static void setTableLogRestoreDescr(TableLogRestoreDescr *restore_descr,
char *table_orig,
char *table_orig_pkey,
char *table_log,
char *table_log_pkey,
char *table_restore);
static void getRelationPrimaryKeyColumns(TableLogRestoreDescr *restore_descr);
/* this is a V1 (new) function */
/* the trigger function */
PG_FUNCTION_INFO_V1(table_log);
PG_FUNCTION_INFO_V1(table_log_basic);
PG_FUNCTION_INFO_V1(table_log_forward);
/* build only, if the 'Table Function API' is available */
#ifdef FUNCAPI_H_not_implemented
/* restore one single column */
PG_FUNCTION_INFO_V1(table_log_show_column);
#endif /* FUNCAPI_H */
/* restore a full table */
PG_FUNCTION_INFO_V1(table_log_restore_table);
/*
* Initialize table_log module and various internal
* settings like customer variables.
*/
void _PG_init(void)
{
DefineCustomIntVariable("table_log.active_partition",
"Sets the current active partition identifier.",
NULL,
&tableLogActivePartitionId,
0,
0,
MAX_TABLE_LOG_PARTITIONS - 1,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
}
/*
* Returns a fully formatted log table relation name
* of the current active log table partition.
*
* The table_name argument is adjusted to match either a single
* table or a partitioned log table with _n appended, where n matches
* the current selected active partition id
* (see tableLogActivePartitionId).
*/
static inline char *getActiveLogTable(TriggerData *tg_data)
{
bool use_partitions = false;
StringInfo buf = makeStringInfo();
/*
* If we use several partitions for the log table, append
* the partition id.
*/
if (tg_data->tg_trigger->tgnargs == 4)
{
/*
* Examine trigger argument list. We expect the
* partition mode to be the 4th argument to the table_log()
* trigger. In case no argument was specified, we know that
* we are operating on an old version, so assume
* a non-partitioned installation automatically.
*/
if (strcmp(tg_data->tg_trigger->tgargs[3], "PARTITION") == 0)
{
/* Partition support enabled */
use_partitions = true;
}
}
if (tg_data->tg_trigger->tgnargs > 0)
{
appendStringInfoString(buf, tg_data->tg_trigger->tgargs[0]);
}
else
{
/*
* We must deal with no arguments given to the trigger. In this
* case the log table name is the same like the table we are
* called on, plus the _log appended...
*/
appendStringInfo(buf, "%s_log", SPI_getrelname(tg_data->tg_relation));
}
if (use_partitions)
{
/*
* Append the current active partition id, if partitioning
* support is used.
*/
appendStringInfo(buf, "_%u", tableLogActivePartitionId);
}
/* ...and we're done */
return buf->data;
}
/*
* count_columns (TupleDesc tupleDesc)
* Will count and return the number of columns in the table described by
* tupleDesc. It needs to ignore dropped columns.
*/
static int count_columns (TupleDesc tupleDesc)
{
int count = 0;
int i;
for (i = 0; i < tupleDesc->natts; ++i)
{
if (!TupleDescAttr(tupleDesc, i)->attisdropped)
{
++count;
}
}
return count;
}
/*
* Initialize a TableLogDescr descriptor structure.
*/
static void initTableLogDescr(TableLogDescr *descr,
TriggerData *trigdata)
{
Assert(descr != NULL);
descr->trigdata = trigdata;
descr->number_columns = -1;
descr->number_columns_log = -1;
descr->ident_log.schema = NULL;
descr->ident_log.relname = NULL;
descr->use_session_user = 0;
}
/*
* table_log_internal()
*
* Internal function to initialize all required stuff
* for table_log() or table_log_basic().
*
* Requires a TableLogDescr structure previously
* initialized via initTableLogDescr().
*/
static void table_log_prepare(TableLogDescr *descr)
{
int ret;
StringInfo query;
/* must only be called for ROW trigger */
if (TRIGGER_FIRED_FOR_STATEMENT(descr->trigdata->tg_event))
{
elog(ERROR, "table_log: can't process STATEMENT events");
}
/* must only be called AFTER */
if (TRIGGER_FIRED_BEFORE(descr->trigdata->tg_event))
{
elog(ERROR, "table_log: must be fired after event");
}
/* now connect to SPI manager */
ret = SPI_connect();
if (ret != SPI_OK_CONNECT)
{
elog(ERROR, "table_log: SPI_connect returned %d", ret);
}
elog(DEBUG2, "prechecks done, now getting original table attributes");
descr->number_columns = count_columns(DESCR_TRIGDATA_GET_TUPDESC((*descr)));
if (descr->number_columns < 1)
{
elog(ERROR, "table_log: number of columns in table is < 1, can this happen?");
}
elog(DEBUG2, "number columns in orig table: %i", descr->number_columns);
if (DESCR_TRIGDATA_NARGS((*descr)) > 4)
{
elog(ERROR, "table_log: too many arguments to trigger");
}
/* name of the log schema */
if (DESCR_TRIGDATA_NARGS((*descr)) <= 2)
{
/* if no explicit schema specified, use source table schema */
descr->ident_log.schema = get_namespace_name(RelationGetNamespace(DESCR_TRIGDATA_GET_RELATION((*descr))));
}
else
{
descr->ident_log.schema = DESCR_TRIGDATA_LOG_SCHEMA((*descr));
}
/* name of the log table */
descr->ident_log.relname = getActiveLogTable(DESCR_TRIGDATA((*descr)));
/* should we write the current user? */
if (DESCR_TRIGDATA_NARGS((*descr)) > 1)
{
/*
* check if a second argument is given
* if yes, use it, if it is true
*/
if (atoi(DESCR_TRIGDATA_LOG_SESSION_USER((*descr))) == 1)
{
descr->use_session_user = 1;
elog(DEBUG2, "will write session user to 'trigger_user'");
}
}
elog(DEBUG2, "log table: %s.%s",
quote_identifier(descr->ident_log.schema),
quote_identifier(descr->ident_log.relname));
/* get the number columns in the table */
query = makeStringInfo();
appendStringInfo(query, "%s.%s",
do_quote_ident(descr->ident_log.schema),
do_quote_ident(descr->ident_log.relname));
descr->number_columns_log = count_columns(RelationNameGetTupleDesc(query->data));
if (descr->number_columns_log < 1)
{
elog(ERROR, "could not get number columns in relation %s.%s",
quote_identifier(descr->ident_log.schema),
quote_identifier(descr->ident_log.relname));
}
elog(DEBUG2, "number columns in log table: %i",
descr->number_columns_log);
/*
* check if the logtable has 3 (or now 4) columns more than our table
* +1 if we should write the session user
*/
if (descr->use_session_user == 0)
{
/* without session user */
if ((descr->number_columns_log != descr->number_columns + 3)
&& (descr->number_columns_log != descr->number_columns + 4))
{
elog(ERROR, "number colums in relation %s(%d) does not match columns in %s.%s(%d)",
SPI_getrelname(DESCR_TRIGDATA_GET_RELATION((*descr))),
descr->number_columns,
quote_identifier(descr->ident_log.schema),
quote_identifier(descr->ident_log.relname),
descr->number_columns_log);
}
}
else
{
/* with session user */
if ((descr->number_columns_log != descr->number_columns + 3 + 1)
&& (descr->number_columns_log != descr->number_columns + 4 + 1))
{
elog(ERROR, "number colums in relation %s does not match columns in %s.%s",
SPI_getrelname(DESCR_TRIGDATA_GET_RELATION((*descr))),
quote_identifier(descr->ident_log.schema),
quote_identifier(descr->ident_log.relname));
}
}
elog(DEBUG2, "log table OK");
/* For each column in key ... */
elog(DEBUG2, "copy data ...");
}
static void table_log_finalize()
{
/* ...for now only SPI needs to be cleaned up. */
SPI_finish();
}
/*
* table_log_forward
*
* Trigger function with the same core functionality
* than table_log(), but without the possibility to do
* backward log replay. This means that NEW tuples for UPDATE
* actions aren't logged, which makes the log table much smaller
* in case someone have a heavy updated source table.
*/
Datum table_log_basic(PG_FUNCTION_ARGS)
{
TableLogDescr log_descr;
/*
* Some checks first...
*/
elog(DEBUG2, "start table_log()");
/* called by trigger manager? */
if (!CALLED_AS_TRIGGER(fcinfo))
{
elog(ERROR, "table_log: not fired by trigger manager");
}
/*
* Assign trigger data structure to table log descriptor.
*/
initTableLogDescr(&log_descr,
(TriggerData *) fcinfo->context);
/*
* Do all the preparing leg work...
*/
table_log_prepare(&log_descr);
if (TRIGGER_FIRED_BY_INSERT(DESCR_TRIGDATA(log_descr)->tg_event))
{
/* trigger called from INSERT */
elog(DEBUG2, "mode: INSERT -> new");
__table_log(&log_descr,
"INSERT",
"new",
DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
else if (TRIGGER_FIRED_BY_UPDATE(DESCR_TRIGDATA(log_descr)->tg_event))
{
elog(DEBUG2, "mode: UPDATE -> old");
__table_log(&log_descr,
"UPDATE",
"old",
DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
else if (TRIGGER_FIRED_BY_DELETE(DESCR_TRIGDATA(log_descr)->tg_event))
{
/* trigger called from DELETE */
elog(DEBUG2, "mode: DELETE -> old");
__table_log(&log_descr,
"DELETE",
"old",
DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
else
{
elog(ERROR, "trigger fired by unknown event");
}
elog(DEBUG2, "cleanup, trigger done");
table_log_finalize();
/* return trigger data */
return PointerGetDatum(DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
/*
table_log()
trigger function for logging table changes
parameter:
- log table name (optional)
return:
- trigger data (for Pg)
*/
Datum table_log(PG_FUNCTION_ARGS)
{
TableLogDescr log_descr;
/*
* Some checks first...
*/
elog(DEBUG2, "start table_log()");
/* called by trigger manager? */
if (!CALLED_AS_TRIGGER(fcinfo))
{
elog(ERROR, "table_log: not fired by trigger manager");
}
/*
* Assign trigger data structure to table log descriptor.
*/
initTableLogDescr(&log_descr,
(TriggerData *) fcinfo->context);
/*
* Do all the preparing leg work...
*/
table_log_prepare(&log_descr);
if (TRIGGER_FIRED_BY_INSERT(DESCR_TRIGDATA(log_descr)->tg_event))
{
/* trigger called from INSERT */
elog(DEBUG2, "mode: INSERT -> new");
__table_log(&log_descr,
"INSERT",
"new",
DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
else if (TRIGGER_FIRED_BY_UPDATE(DESCR_TRIGDATA(log_descr)->tg_event))
{
/* trigger called from UPDATE */
elog(DEBUG2, "mode: UPDATE -> old");
__table_log(&log_descr,
"UPDATE",
"old",
DESCR_TRIGDATA_GET_TUPLE(log_descr));
elog(DEBUG2, "mode: UPDATE -> new");
__table_log(&log_descr,
"UPDATE",
"new",
DESCR_TRIGDATA_GET_NEWTUPLE(log_descr));
}
else if (TRIGGER_FIRED_BY_DELETE(DESCR_TRIGDATA(log_descr)->tg_event))
{
/* trigger called from DELETE */
elog(DEBUG2, "mode: DELETE -> old");
__table_log(&log_descr,
"DELETE",
"old",
DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
else
{
elog(ERROR, "trigger fired by unknown event");
}
elog(DEBUG2, "cleanup, trigger done");
table_log_finalize();
/* return trigger data */
return PointerGetDatum(DESCR_TRIGDATA_GET_TUPLE(log_descr));
}
/*
__table_log()
helper function for table_log()
parameter:
- trigger data
- change mode (INSERT, UPDATE, DELETE)
- tuple to log (old, new)
- pointer to tuple
- number columns in table
- logging table
- flag for writing session user
return:
none
*/
static void __table_log (TableLogDescr *descr,
char *changed_mode,
char *changed_tuple,
HeapTuple tuple)
{
StringInfo query;
char *before_char;
int i;
int col_nr;
int found_col;
int ret;
elog(DEBUG2, "build query");
/* allocate memory */
query = makeStringInfo();
/* build query */
appendStringInfo(query, "INSERT INTO %s.%s (",
do_quote_ident(descr->ident_log.schema),
do_quote_ident(descr->ident_log.relname));
/* add colum names */
col_nr = 0;
for (i = 1; i <= descr->number_columns; i++)
{
col_nr++;
found_col = 0;
do
{
if (TupleDescAttr(DESCR_TRIGDATA_GET_TUPDESC(*descr), col_nr - 1)->attisdropped)
{
/* this column is dropped, skip it */
col_nr++;
continue;
}
else
{
found_col++;
}
}
while (found_col == 0);
appendStringInfo(query,
"%s, ",
do_quote_ident(SPI_fname(DESCR_TRIGDATA_GET_TUPDESC((*descr)), col_nr)));
}
/* add session user */
if (descr->use_session_user == 1)
appendStringInfo(query, "trigger_user, ");
/* add the 3 extra colum names */
appendStringInfo(query, "trigger_mode, trigger_tuple, trigger_changed) VALUES (");
/* add values */
col_nr = 0;
for (i = 1; i <= descr->number_columns; i++)
{
col_nr++;
found_col = 0;
do
{
if (TupleDescAttr(DESCR_TRIGDATA_GET_TUPDESC(*descr), col_nr - 1)->attisdropped)
{
/* this column is dropped, skip it */
col_nr++;
continue;
}
else
{
found_col++;
}
}
while (found_col == 0);
before_char = SPI_getvalue(tuple,
DESCR_TRIGDATA_GET_TUPDESC((*descr)),
col_nr);
if (before_char == NULL)
{
appendStringInfo(query, "NULL, ");
}
else
{
appendStringInfo(query, "%s, ",
do_quote_literal(before_char));
}
}
/* add session user */
if (descr->use_session_user == 1)
appendStringInfo(query, "SESSION_USER, ");
/* add the 3 extra values */
appendStringInfo(query, "%s, %s, NOW());",
do_quote_literal(changed_mode),
do_quote_literal(changed_tuple));
elog(DEBUG3, "query: %s", query->data);
elog(DEBUG2, "execute query");
/* execute insert */
ret = SPI_exec(query->data, 0);
if (ret != SPI_OK_INSERT)
{
elog(ERROR, "could not insert log information into relation %s.%s (error: %d)",
quote_identifier(descr->ident_log.schema),
quote_identifier(descr->ident_log.relname),
ret);
}
/* clean up */
pfree(query->data);
pfree(query);
elog(DEBUG2, "done");
}
#ifdef FUNCAPI_H_not_implemented
/*
table_log_show_column()
show a single column on a date in the past
parameter:
not yet defined
return:
not yet defined
*/
Datum table_log_show_column(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
int ret;
/*
* Some checks first...
*/
elog(DEBUG2, "start table_log_show_column()");
/* Connect to SPI manager */
ret = SPI_connect();
if (ret != SPI_OK_CONNECT)
{
elog(ERROR, "table_log_show_column: SPI_connect returned %d", ret);
}
elog(DEBUG2, "this function isnt available yet");
/* close SPI connection */
SPI_finish();
return PG_RETURN_NULL;
}
#endif /* FUNCAPI_H */
/*
* Retrieves the columns of the primary key the original
* table has and stores their attribute numbers in the
* specified TableLogRestoreDescr descriptor. The caller is responsible
* to pass a valid descriptor initialized by initTableLogRestoreDescr().
*/
static void getRelationPrimaryKeyColumns(TableLogRestoreDescr *restore_descr)
{
Relation origRel;
List *indexOidList;
ListCell *indexOidScan;
Assert((restore_descr != NULL)
&& (restore_descr->orig_relname != NULL));
restore_descr->orig_pk_attnum = NULL;
/*
* Get all indexes for the relation, take care to
* request a share lock before.
*/
#if PG_VERSION_NUM >= 120000
origRel = table_open(restore_descr->orig_relid, AccessShareLock);
#else
origRel = heap_open(restore_descr->orig_relid, AccessShareLock);
#endif
indexOidList = RelationGetIndexList(origRel);
foreach(indexOidScan, indexOidList)
{
Oid indexOid = lfirst_oid(indexOidScan);
Form_pg_index indexStruct;
HeapTuple indexTuple;
int i;
/*
* Lookup the key via syscache, extract the key columns
* from this index in case we have found a primary key.
*/
indexTuple = SearchSysCache1(INDEXRELID,
ObjectIdGetDatum(indexOid));
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "cache lookup failed for index %u", indexOid);
indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
/*
* Next one if this is not a primary key or
* unique constraint.
*/
if (!indexStruct->indisprimary)
{
ReleaseSysCache(indexTuple);
continue;
}
/*
* Okay, looks like this is a PK let's
* get the attnums from it and store them
* in the TableLogRestoreDescr descriptor.
*/
restore_descr->orig_num_pk_attnums = indexStruct->indnatts;
restore_descr->orig_pk_attnum = (AttrNumber *) palloc(indexStruct->indnatts
* sizeof(AttrNumber));
for (i = 0; i < indexStruct->indnatts; i++)
{
restore_descr->orig_pk_attnum[i] = indexStruct->indkey.values[i];
}
ReleaseSysCache(indexTuple);
}
/*
* Okay, we're done. Cleanup and exit.
*/
#if PG_VERSION_NUM >= 120000
table_close(origRel, AccessShareLock);
#else
heap_close(origRel, AccessShareLock);
#endif
}
static void setTableLogRestoreDescr(TableLogRestoreDescr *restore_descr,
char *table_orig,
char *table_orig_pkey,
char *table_log,
char *table_log_pkey,
char *table_restore)
{
List *logIdentList;
List *restoreIdentList;
int i;
Assert(restore_descr != NULL);
/*
* Setup some stuff...
*/
restore_descr->orig_num_pk_attnums = 0;
restore_descr->orig_pk_attr_names = NIL;
restore_descr->orig_pk_attnum = NULL;
restore_descr->orig_relname = pstrdup(table_orig);
/*
* Keep gcc quiet.
* In table_log_restore_table() we call RESTORE_TABLE_IDENT,
* which lets gcc guess that we might get into trouble if
* the restore descriptor was not fully initialized.*
*
* However, we already make sure that RESTORE_TABLE_IDENT
* won't be called with ident_[restore|log].relname unless
* use_schema_log or use_schema_restore is set to false.
*/