-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpg_rewrite.c
4024 lines (3514 loc) · 114 KB
/
pg_rewrite.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
/*------------------------------------------------------------
*
* pg_rewrite.c
* Tools for maintenance that requires table rewriting.
*
* Copyright (c) 2021-2023, Cybertec PostgreSQL International GmbH
*
*------------------------------------------------------------
*/
#include "pg_rewrite.h"
#if PG_VERSION_NUM < 130000
#error "PostgreSQL version 13 or higher is required"
#endif
#include "access/heaptoast.h"
#include "access/multixact.h"
#include "access/sysattr.h"
#include "access/tupdesc_details.h"
#if PG_VERSION_NUM >= 150000
#include "access/xloginsert.h"
#endif
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/objectaddress.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_am.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_control.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_type.h"
#include "catalog/pg_tablespace.h"
#include "catalog/toasting.h"
#include "commands/dbcommands.h"
#include "commands/extension.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "executor/executor.h"
#include "executor/execPartition.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "nodes/primnodes.h"
#include "nodes/makefuncs.h"
#include "optimizer/optimizer.h"
#include "replication/snapbuild.h"
#include "partitioning/partdesc.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/smgr.h"
#include "storage/standbydefs.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
PG_MODULE_MAGIC;
#define REPL_SLOT_BASE_NAME "pg_rewrite_slot_"
#define REPL_PLUGIN_NAME "pg_rewrite"
static void partition_table_impl(Oid dbid, Oid roleid, char *relschema_src,
char *relname_src, char *relname_src_new,
char *relschema_dst, char *relname_dst);
static int index_cat_info_compare(const void *arg1, const void *arg2);
/* The WAL segment being decoded. */
XLogSegNo part_current_segment = 0;
/*
* Information on a single constraint, needed to compare constraints of the
* source and the destination relations.
*/
typedef struct ConstraintInfo
{
char contype;
bool convalidated;
char *conbin;
NameData conname;
Bitmapset *attnos;
Oid confrelid;
int numfks;
AttrNumber conkey[INDEX_MAX_KEYS];
AttrNumber confkey[INDEX_MAX_KEYS];
Oid pf_eq_oprs[INDEX_MAX_KEYS];
Oid pp_eq_oprs[INDEX_MAX_KEYS];
Oid ff_eq_oprs[INDEX_MAX_KEYS];
#if PG_VERSION_NUM >= 150000
int num_fk_del_set_cols;
AttrNumber fk_del_set_cols[INDEX_MAX_KEYS];
#endif
} ConstraintInfo;
static void worker_shmem_request(void);
static void worker_shmem_startup(void);
static void worker_shmem_shutdown(int code, Datum arg);
static void check_prerequisites(Relation rel);
static LogicalDecodingContext *setup_decoding(Oid relid, TupleDesc tup_desc);
static void decoding_cleanup(LogicalDecodingContext *ctx);
static CatalogState *get_catalog_state(Oid relid);
static void get_pg_class_info(Oid relid, TransactionId *xmin,
Form_pg_class *form_p, TupleDesc *desc_p);
static void get_attribute_info(Oid relid, int relnatts,
TransactionId **xmins_p,
CatalogState *cat_state);
static void cache_composite_type_info(CatalogState *cat_state, Oid typid);
static void get_composite_type_info(TypeCatInfo *tinfo);
static IndexCatInfo *get_index_info(Oid relid, int *relninds,
bool *found_invalid,
bool invalid_check_only,
bool *found_pk);
static void check_tup_descs_match(TupleDesc tupdesc_src, char *tabname_src,
TupleDesc tupdesc_dst, char *tabname_dst);
static bool equal_op_expressions(char *expr_str1, char *expr_str2);
static bool is_rel_referenced(Relation rel);
static void compare_constraints(Relation rel1, Relation rel2);
static List *get_relation_constraints(Relation rel, int *ncheck,
int *nunique, int *nfk);
static void free_relation_constraints(List *l);
static ConstraintInfo **get_relation_constraints_array(List *all,
char contype,
int n);
static bool equal_dest_descs(TupleDesc tupdesc1, TupleDesc tupdesc2);
static void report_tupdesc_mismatch(const char *desc,
char *attname, char *tabname_src,
bool has_src, char *tabname_dst,
bool has_dst);
static TupleDesc get_index_tuple_desc(Oid ind_oid);
static ModifyTableState *get_modify_table_state(EState *estate, Relation rel,
CmdType operation);
static void free_modify_table_state(ModifyTableState *mtstate);
static void check_attribute_changes(CatalogState *cat_state);
static void check_index_changes(CatalogState *state);
static void check_composite_type_changes(CatalogState *cat_state);
static void free_catalog_state(CatalogState *state);
static void check_pg_class_changes(CatalogState *state);
static Snapshot build_historic_snapshot(SnapBuild *builder);
static void perform_initial_load(EState *estate, ModifyTableState *mtstate,
struct PartitionTupleRouting *proute,
Relation rel_src, Snapshot snap_hist,
Relation rel_dst,
partitions_hash *partitions,
LogicalDecodingContext *ctx,
TupleConversionMap *conv_map);
static ScanKey build_identity_key(Relation ident_idx_rel, int *nentries);
static bool perform_final_merge(EState *estate,
ModifyTableState *mtstate,
struct PartitionTupleRouting *proute,
Oid relid_src, Oid *indexes_src, int nindexes,
Relation rel_dst, ScanKey ident_key,
int ident_key_nentries,
CatalogState *cat_state,
LogicalDecodingContext *ctx,
partitions_hash *ident_indexes,
TupleConversionMap *conv_map);
static void close_partitions(partitions_hash *partitions);
/*
* Should it be checked whether constraints on the destination table match
* constraints on the source table?
*/
bool rewrite_check_constraints = true;
/*
* The maximum time to hold AccessExclusiveLock on the source table during the
* final processing. Note that it only pg_rewrite_process_concurrent_changes()
* execution time is included here.
*/
int rewrite_max_xlock_time = 0;
/*
* Time (in seconds) to wait after the initial load has completed and before
* we start decoding of data changes introduced by other transactions. This
* helps to ensure defined order of steps when we test processing of the
* concurrent changes.
*/
int rewrite_wait_after_load = 0;
#if PG_VERSION_NUM >= 150000
shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
shmem_startup_hook_type prev_shmem_startup_hook = NULL;
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
ereport(ERROR,
(errmsg("pg_rewrite must be loaded via shared_preload_libraries")));
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = worker_shmem_request;
#else
worker_shmem_request();
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = worker_shmem_startup;
DefineCustomBoolVariable("rewrite.check_constraints",
"Should constraints on the destination table be checked?",
"Should it be checked whether constraints on the destination table match those "
"on the source table?",
&rewrite_check_constraints,
true,
PGC_USERSET,
0,
NULL, NULL, NULL);
DefineCustomIntVariable("rewrite.max_xlock_time",
"The maximum time the processed table may be locked exclusively.",
"The source table is locked exclusively during the final stage of "
"processing. If the lock time should exceed this value, the lock is "
"released and the final stage is retried a few more times.",
&rewrite_max_xlock_time,
0, 0, INT_MAX,
PGC_USERSET,
GUC_UNIT_MS,
NULL, NULL, NULL);
DefineCustomIntVariable("rewrite.wait_after_load",
"Time to wait after the initial load.",
"Time to wait after the initial load, so that a concurrent session "
"can perform data changes before processing goes on. This is useful "
"for regression tests.",
&rewrite_wait_after_load,
0, 0, 10,
PGC_USERSET,
GUC_UNIT_S,
NULL, NULL, NULL);
}
#define REPLORIGIN_NAME_PATTERN "pg_rewrite_%u"
/*
* The original implementation would certainly fail on PG 16 and higher, due
* to the commit 240e0dbacd (in the master branch) - this commit makes it
* impossible to invoke our functionality via the PG executor. It's not worth
* supporting lower versions of pg_rewrite on lower versions of PG server.
*/
extern Datum partition_table(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(partition_table);
Datum
partition_table(PG_FUNCTION_ARGS)
{
ereport(ERROR, (errmsg("the old implementation of the function is no longer supported"),
errhint("please run \"ALTER EXTENSION pg_rewrite UPDATE\"")));
PG_RETURN_VOID();
}
/* Pointer to task array in the shared memory, available in all backends. */
static WorkerTask *workerTasks = NULL;
/* Each backend stores here the pointer to its task in the shared memory. */
WorkerTask *MyWorkerTask = NULL;
static void
interrupt_worker(WorkerTask *task)
{
SpinLockAcquire(&task->mutex);
task->exit_requested = true;
SpinLockRelease(&task->mutex);
}
static void
release_task(WorkerTask *task)
{
SpinLockAcquire(&task->mutex);
Assert(task->dbid != InvalidOid);
task->dbid = InvalidOid;
SpinLockRelease(&task->mutex);
}
static Size
worker_shmem_size(void)
{
return MAX_TASKS * sizeof(WorkerTask);
}
static void
worker_shmem_request(void)
{
/* With lower PG versions this function is called from _PG_init(). */
#if PG_VERSION_NUM >= 150000
if (prev_shmem_request_hook)
prev_shmem_request_hook();
#endif /* PG_VERSION_NUM >= 150000 */
RequestAddinShmemSpace(worker_shmem_size());
}
static void
worker_shmem_startup(void)
{
bool found;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
workerTasks = ShmemInitStruct("pg_rewrite",
worker_shmem_size(),
&found);
if (!found)
{
int i;
for (i = 0; i < MAX_TASKS; i++)
{
WorkerTask *task = &workerTasks[i];
task->dbid = InvalidOid;
task->roleid = InvalidOid;
task->pid = InvalidPid;
task->exit_requested = false;
SpinLockInit(&task->mutex);
}
}
LWLockRelease(AddinShmemInitLock);
}
static void
worker_shmem_shutdown(int code, Datum arg)
{
if (MyWorkerTask)
{
SpinLockAcquire(&MyWorkerTask->mutex);
MyWorkerTask->pid = InvalidPid;
MyWorkerTask->exit_requested = false;
SpinLockRelease(&MyWorkerTask->mutex);
}
}
/* PG >= 14 does define this macro. */
#if PG_VERSION_NUM < 140000
#define RelationIsPermanent(relation) \
((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
#endif
/*
* Start the background worker and wait until it exits.
*/
extern Datum partition_table_new(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(partition_table_new);
Datum
partition_table_new(PG_FUNCTION_ARGS)
{
text *rel_src_t, *rel_src_new_t, *rel_dst_t;
RangeVar *rv_src, *rv_src_new, *rv_dst;
BackgroundWorker worker;
BackgroundWorkerHandle *handle;
pid_t pid;
BgwHandleStatus status;
Oid dbid, roleid;
char *dbname;
int i;
WorkerTask *task = NULL;
bool found = false;
char *msg = NULL;
rel_src_t = PG_GETARG_TEXT_PP(0);
rv_src = makeRangeVarFromNameList(textToQualifiedNameList(rel_src_t));
rel_dst_t = PG_GETARG_TEXT_PP(1);
rv_dst = makeRangeVarFromNameList(textToQualifiedNameList(rel_dst_t));
rel_src_new_t = PG_GETARG_TEXT_PP(2);
rv_src_new = makeRangeVarFromNameList(textToQualifiedNameList(rel_src_new_t));
if (rv_src->catalogname || rv_dst->catalogname || rv_src_new->catalogname)
ereport(ERROR,
(errmsg("relation may only be qualified by schema, not by database")));
/*
* Technically it's possible to move the source relation to another schema
* but don't bother for this version.
*/
if (rv_src_new->schemaname)
ereport(ERROR,
(errcode(ERRCODE_INVALID_NAME),
(errmsg("the new source relation name may not be qualified"))));
dbid = MyDatabaseId;
roleid = GetUserId();
/* Find free task structure. */
for (i = 0; i < MAX_TASKS; i++)
{
task = &workerTasks[i];
SpinLockAcquire(&task->mutex);
if (task->dbid == InvalidOid && task->pid == InvalidPid)
{
TaskProgress *progress = &task->progress;
/* Make sure that no other backend can use the task. */
task->dbid = MyDatabaseId;
progress->ins_initial = 0;
progress->ins = 0;
progress->upd = 0;
progress->del = 0;
found = true;
}
SpinLockRelease(&task->mutex);
if (found)
break;
}
if (!found)
ereport(ERROR, (errmsg("too many concurrent tasks in progress")));
worker.bgw_flags = BGWORKER_SHMEM_ACCESS |
BGWORKER_BACKEND_DATABASE_CONNECTION;
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
worker.bgw_restart_time = BGW_NEVER_RESTART;
sprintf(worker.bgw_library_name, "pg_rewrite");
sprintf(worker.bgw_function_name, "rewrite_worker_main");
/*
* XXX The function can throw ERROR but the database should really exist,
* so no need to put this code in the PG_TRY block.
*/
dbname = get_database_name(dbid);
snprintf(worker.bgw_name, BGW_MAXLEN,
"pg_rewrite worker for database %s", dbname);
snprintf(worker.bgw_type, BGW_MAXLEN, "pg_rewrite worker");
Assert(i < MAX_TASKS);
worker.bgw_main_arg = (Datum) i;
worker.bgw_notify_pid = MyProcPid;
/* Finalize the task. */
task->roleid = roleid;
task->exit_requested = false;
if (rv_src->schemaname)
namestrcpy(&task->relschema_src, rv_src->schemaname);
else
NameStr(task->relschema_src)[0] = '\0';
namestrcpy(&task->relname_src, rv_src->relname);
if (rv_dst->schemaname)
namestrcpy(&task->relschema_dst, rv_dst->schemaname);
else
NameStr(task->relschema_dst)[0] = '\0';
namestrcpy(&task->relname_dst, rv_dst->relname);
namestrcpy(&task->relname_src_new, rv_src_new->relname);
task->msg[0] = '\0';
/*
* The worker does not reload the configuration, so we pass these GUC
* setting via the shared memory.
*/
task->wait_after_load = rewrite_wait_after_load;
task->check_constraints = rewrite_check_constraints;
/*
* Start the worker. Avoid leaking the task if the function ends due to
* ERROR.
*/
PG_TRY();
{
if (!RegisterDynamicBackgroundWorker(&worker, &handle))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
errmsg("could not register background process"),
errhint("More details may be available in the server log.")));
status = WaitForBackgroundWorkerStartup(handle, &pid);
}
PG_CATCH();
{
/*
* It seems possible that the worker is trying to start even if we end
* up here - at least when WaitForBackgroundWorkerStartup() got
* interrupted.
*/
interrupt_worker(task);
release_task(task);
PG_RE_THROW();
}
PG_END_TRY();
if (status == BGWH_STOPPED)
{
/* Work already done? */
release_task(task);
PG_RETURN_VOID();
}
else if (status == BGWH_POSTMASTER_DIED)
{
ereport(ERROR,
(errmsg("could not start background worker because the postmaster died"),
errhint("More details may be available in the server log.")));
/* No need to release the task in the shared memory. */
}
/*
* WaitForBackgroundWorkerStartup() should not return
* BGWH_NOT_YET_STARTED.
*/
Assert(status == BGWH_STARTED);
PG_TRY();
{
status = WaitForBackgroundWorkerShutdown(handle);
}
PG_CATCH();
{
/*
* Make sure the worker stops. Interrupt received from the user is the
* typical use case.
*/
interrupt_worker(task);
release_task(task);
PG_RE_THROW();
}
PG_END_TRY();
if (status == BGWH_POSTMASTER_DIED)
{
ereport(ERROR,
(errmsg("the postmaster died before the background worker could finish"),
errhint("More details may be available in the server log.")));
/* No need to release the task in the shared memory. */
}
/*
* WaitForBackgroundWorkerShutdown() should not return anything else.
*/
Assert(status == BGWH_STOPPED);
if (strlen(task->msg) > 0)
msg = pstrdup(task->msg);
release_task(task);
/* Report the worker's ERROR in the backend. */
if (msg)
ereport(ERROR, (errmsg("%s", msg)));
PG_RETURN_VOID();
}
void
rewrite_worker_main(Datum main_arg)
{
Datum arg;
int i;
Oid dbid, roleid;
char *relschema_src, *relname_src, *relname_src_new, *relschema_dst,
*relname_dst;
WorkerTask *task;
/* The worker should do its cleanup when exiting. */
before_shmem_exit(worker_shmem_shutdown, (Datum) 0);
/*
* The standard handlers for SIGTERM and SIGQUIT are fine, see
* bgworker.c.
*/
BackgroundWorkerUnblockSignals();
/* Retrieve task index. */
Assert(MyBgworkerEntry != NULL);
arg = MyBgworkerEntry->bgw_main_arg;
i = DatumGetInt32(arg);
Assert(i >= 0 && i < MAX_TASKS);
Assert(MyWorkerTask == NULL);
task = MyWorkerTask = &workerTasks[i];
/*
* The task should be fully initialized before the backend registers the
* worker. Let's copy the arguments so that we have a consistent view -
* see the explanation below.
*/
relschema_src = NameStr(task->relschema_src);
relschema_src = *relschema_src != '\0' ? pstrdup(relschema_src) : NULL;
relname_src = pstrdup(NameStr(task->relname_src));
relname_src_new = pstrdup(NameStr(task->relname_src_new));
relschema_dst = NameStr(task->relschema_dst);
relschema_dst = *relschema_dst != '\0' ? pstrdup(relschema_dst) : NULL;
relname_dst = pstrdup(NameStr(task->relname_dst));
rewrite_wait_after_load = task->wait_after_load;
rewrite_check_constraints = task->check_constraints;
/*
* Get the information provided by the backend and set our pid.
*/
SpinLockAcquire(&MyWorkerTask->mutex);
Assert(MyWorkerTask->dbid != InvalidOid);
dbid = MyWorkerTask->dbid;
Assert(MyWorkerTask->roleid != InvalidOid);
roleid = MyWorkerTask->roleid;
task->pid = MyProcPid;
SpinLockRelease(&MyWorkerTask->mutex);
/*
* Has the "owning" backend of this worker exited too early?
*/
if (!OidIsValid(dbid))
{
ereport(DEBUG1,
(errmsg("task cancelled before the worker could start")));
return;
}
/*
* If the backend exits later (w/o waiting for the worker's exit), that
* backend's ERRORs (which include interrupts) should make the worker stop
* (via interrupt_worker()).
*/
BackgroundWorkerInitializeConnectionByOid(dbid, roleid, 0);
/* Do the actual work. */
StartTransactionCommand();
PG_TRY();
{
partition_table_impl(dbid, roleid, relschema_src, relname_src,
relname_src_new, relschema_dst, relname_dst);
CommitTransactionCommand();
}
PG_CATCH();
{
MemoryContext old_context = CurrentMemoryContext;
ErrorData *edata;
HOLD_INTERRUPTS();
/*
* CopyErrorData() requires the context to be different from
* ErrorContext.
*/
MemoryContextSwitchTo(TopMemoryContext);
edata = CopyErrorData();
MemoryContextSwitchTo(old_context);
/*
* The following shouldn't be necessary because the worker isn't going
* to do anything else, but cleanup is just a good practice.
*
* XXX Should we re-throw the error instead of doing the cleanup? Not
* sure, the error message would then appear twice in the log.
*/
FlushErrorState();
/* Not done by AbortTransaction(). */
if (MyReplicationSlot != NULL)
ReplicationSlotRelease();
/*
* Likewise, there seems to be no automatic cleanup of the origin, so
* do it here. The insertion into the ReplicationOriginRelationId
* catalog will be rolled back due to the transaction abort.
*/
if (replorigin_session_origin != InvalidRepOriginId)
replorigin_session_origin = InvalidRepOriginId;
AbortOutOfAnyTransaction();
/*
* Currently we only copy the error message, more fields, more
* information can be added if needed. (Ideally we'd use the message
* queue like parallel workers do, but the related PG core functions
* have some parallel worker specific arguments.)
*/
strlcpy(task->msg, edata->message, MAX_ERR_MSG_LEN);
FreeErrorData(edata);
RESUME_INTERRUPTS();
}
PG_END_TRY();
}
/*
* A substitute for CHECK_FOR_INTERRUPRS.
*
* procsignal_sigusr1_handler does not support signaling from a backend to a
* non-parallel worker (see the values of ProcSignalReason), so the worker
* cannot use CHECK_FOR_INTERRUPTS. Let's use shared memory to tell the worker
* that it should exit. (SIGTERM would terminate the worker easily, but due
* to race conditions we could terminate another backend / worker which
* already managed to reuse this worker's PID.)
*/
void
pg_rewrite_exit_if_requested(void)
{
bool exit_requested;
SpinLockAcquire(&MyWorkerTask->mutex);
exit_requested = MyWorkerTask->exit_requested;
SpinLockRelease(&MyWorkerTask->mutex);
if (!exit_requested)
return;
/*
* There seems to be no automatic cleanup of the origin, so do it here.
* The insertion into the ReplicationOriginRelationId catalog will be
* rolled back due to the transaction abort.
*/
if (replorigin_session_origin != InvalidRepOriginId)
replorigin_session_origin = InvalidRepOriginId;
/*
* Message similar to that in ProcessInterrupts(), but ERROR is
* sufficient here. rewrite_worker_main() should catch it.
*/
ereport(ERROR,
(errcode(ERRCODE_ADMIN_SHUTDOWN),
errmsg("terminating pg_rewrite background worker due to administrator command")));
}
/*
* Introduced in pg_rewrite 1.1, to be called directly as opposed to calling
* via the postgres executor.
*
* The function is executed by a background worker. We do not catch ERRORs
* here, they will simply make the worker rollback any transaction and exit.
*/
static void
partition_table_impl(Oid dbid, Oid roleid, char *relschema_src,
char *relname_src, char *relname_src_new,
char *relschema_dst, char *relname_dst)
{
RangeVar *relrv;
Relation rel_src,
rel_dst;
PartitionDesc part_desc;
Oid ident_idx_src;
Oid relid_src;
ScanKey ident_key = NULL;
int i,
ident_key_nentries = 0;
LogicalDecodingContext *ctx;
ReplicationSlot *slot;
Snapshot snap_hist;
TupleDesc tup_desc_src,
ident_src_tupdesc;
CatalogState *cat_state;
XLogRecPtr end_of_wal;
XLogRecPtr xlog_insert_ptr;
int nindexes;
Oid *indexes_src = NULL;
bool invalid_index = false;
IndexCatInfo *ind_info;
bool source_finalized;
Relation *parts_dst;
partitions_hash *partitions;
TupleConversionMap *conv_map;
EState *estate;
ModifyTableState *mtstate;
struct PartitionTupleRouting *proute;
relrv = makeRangeVar(relschema_src, relname_src, -1);
rel_src = table_openrv(relrv, AccessShareLock);
check_prerequisites(rel_src);
/*
* Retrieve the useful info while holding lock on the relation.
*/
ident_idx_src = RelationGetReplicaIndex(rel_src);
/* The table can have PK although the replica identity is FULL. */
if (ident_idx_src == InvalidOid && rel_src->rd_pkindex != InvalidOid)
ident_idx_src = rel_src->rd_pkindex;
/*
* Check if we're ready to capture changes that possibly take place during
* the initial load.
*
* Concurrent DDL causes ERROR in any case, so don't worry about validity
* of this test during the next steps.
*
* Note: we let the plugin do this check on per-change basis, and allow
* processing of tables with no identity if only INSERT changes are
* decoded. However it seems inconsistent.
*
* XXX Although ERRCODE_UNIQUE_VIOLATION is no actual "unique violation",
* this error code seems to be the best match.
* (ERRCODE_TRIGGERED_ACTION_EXCEPTION might be worth consideration as
* well.)
*/
if (!OidIsValid(ident_idx_src))
ereport(ERROR,
(errcode(ERRCODE_UNIQUE_VIOLATION),
(errmsg("Table \"%s\" has no identity index",
relname_src))));
relid_src = RelationGetRelid(rel_src);
/*
* Info to initialize the tuplestore we'll use during logical decoding.
*/
tup_desc_src = CreateTupleDescCopyConstr(RelationGetDescr(rel_src));
/*
* Get ready for the subsequent calls of
* pg_rewrite_check_catalog_changes().
*
* Not all index changes do conflict with the AccessShareLock - see
* get_index_info() for explanation.
*
* XXX It'd still be correct to start the check a bit later, i.e. just
* before CreateInitDecodingContext(), but the gain is not worth making
* the code less readable.
*/
cat_state = get_catalog_state(relid_src);
/* Give up if it's clear enough to do so. */
if (cat_state->invalid_index)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
(errmsg("At least one index is invalid"))));
/*
* The relation shouldn't be locked during the call of setup_decoding(),
* otherwise another transaction could write XLOG records before the
* slots' data.restart_lsn and we'd have to wait for it to finish. If such
* a transaction requested exclusive lock on our relation (e.g. ALTER
* TABLE), it'd result in a deadlock.
*
* We can't keep the lock till the end of transaction anyway - that's why
* pg_rewrite_check_catalog_changes() exists.
*/
table_close(rel_src, AccessShareLock);
nindexes = cat_state->relninds;
/*
* Existence of identity index was checked above, so number of indexes and
* attributes are both non-zero.
*/
Assert(cat_state->form_class->relnatts >= 1);
Assert(nindexes > 0);
/* Copy the OIDs into a separate array, for convenient use later. */
indexes_src = (Oid *) palloc(nindexes * sizeof(Oid));
for (i = 0; i < nindexes; i++)
indexes_src[i] = cat_state->indexes[i].oid;
ctx = setup_decoding(relid_src, tup_desc_src);
/*
* The destination table should not be accessed by anyone during our
* processing. We're especially worried about DDLs because those might
* make us crash during data insertion. So lock the table in exclusive
* mode. Thus the checks for catalog changes we perform below stay valid
* until the processing is done.
*
* This cannot be done before the call of setup_decoding() as the
* exclusive lock does assign XID.
*/
relrv = makeRangeVar(relschema_dst, relname_dst, -1);
rel_dst = table_openrv(relrv, AccessExclusiveLock);
/* We're going to distribute data into partitions. */
if (rel_dst->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a partitioned table", relname_dst)));
/*
* If the destination table is temporary, user probably messed things up
* and a lot of data would be lost at the end of the session. Unlogged
* table might be o.k. but let's allow only permanent so far.
*/
if (!RelationIsPermanent(rel_dst))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a permanent table", relname_dst)));
#if PG_VERSION_NUM >= 140000
part_desc = RelationGetPartitionDesc(rel_dst, true);
#else
part_desc = RelationGetPartitionDesc(rel_dst);
#endif
if (part_desc->nparts == 0)
ereport(ERROR,
(errmsg("table \"%s\" has no partitions", relname_dst)));
/*
* It's probably not necessary to lock the partitions in exclusive mode,
* but we'll need to open them later. Simply use the exclusive lock
* instead of trying to determine the minimum lock level needed.
*/
parts_dst = (Relation *) palloc(part_desc->nparts * sizeof(Relation));
for (i = 0; i < part_desc->nparts; i++)
parts_dst[i] = table_open(part_desc->oids[i], AccessExclusiveLock);
/*
* Build a "historic snapshot", i.e. one that reflect the table state at
* the moment the snapshot builder reached SNAPBUILD_CONSISTENT state.
*/
snap_hist = build_historic_snapshot(ctx->snapshot_builder);
/* The source relation will be needed for the initial load. */
rel_src = table_open(relid_src, AccessShareLock);
/*
* Check if the source and destination table have compatible type. This is
* needed because ExecFindPartition() needs the (root) destination table
* tuple.
*/
check_tup_descs_match(tup_desc_src, RelationGetRelationName(rel_src),
RelationGetDescr(rel_dst),
RelationGetRelationName(rel_dst));
conv_map = convert_tuples_by_position(tup_desc_src,
RelationGetDescr(rel_dst),
/*
* XXX Better log message? User
* shouldn't see this anyway.
*/
"cannot map tuples");
/*
* Check if the source table has all the constraints that the destination
* has. Since we copy tuples from the source table w/o performing any
* checks, we can only accept constraints that the source table already
* enforced.
*
* Note: we do not check triggers since existence of a (non-constraint)
* trigger does not guarantee that it has been executed on all the
* existing rows of a table.
*/
compare_constraints(rel_src, rel_dst);
/*
* Also check if the source table is referenced by any FK. Since the
* destination table is initially empty, user should not be able to create
* the corresponding FKs referencing it. A "workaround" to omit the FKs to
* the destination table should not be allowed by default.
*/
if (rewrite_check_constraints)
{
if (is_rel_referenced(rel_src))
ereport(ERROR,
(errmsg("table \"%s\" is referenced by a foreign key",
RelationGetRelationName(rel_src))));
}
/*
* Store the identity of the source relation, in order to check that of
* the destination table partitions.
*/
ident_src_tupdesc = get_index_tuple_desc(ident_idx_src);
/*
* Pointers to identity indexes will be looked up by the partition
* relation OID.
*/
partitions = partitions_create(CurrentMemoryContext, 8, NULL);
/*
* Gather partition information that we'll need later. It happens here
* because it's a good opportunity to check the partition tuple
* descriptors and identity indexes before the initial load starts. (The
* load does not need those indexes, but it'd be unfortunate to find out
* incorrect or missing identity index after the initial load has been
* performed.)
*/
for (i = 0; i < part_desc->nparts; i++)
{
Oid ident_idx_dst;
Relation partition = parts_dst[i];
Relation ident_idx_rel;
TupleDesc ident_dst_tupdesc;
PartitionEntry *entry;
bool found;
/* Info on partitions. */
entry = partitions_insert(partitions, RelationGetRelid(partition),