-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpg_rewrite.c
More file actions
3788 lines (3315 loc) · 105 KB
/
pg_rewrite.c
File metadata and controls
3788 lines (3315 loc) · 105 KB
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-2025, 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_depend.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 "executor/spi.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "nodes/primnodes.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.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 "rewrite/rewriteHandler.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"
#if PG_VERSION_NUM >= 170000
#include "utils/injection_point.h"
#endif
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
#ifdef PG_MODULE_MAGIC_EXT
PG_MODULE_MAGIC_EXT(.name = "pg_rewrite", .version = "2.1");
#else
PG_MODULE_MAGIC;
#endif
#define REPL_SLOT_BASE_NAME "pg_rewrite_slot_"
#define REPL_PLUGIN_NAME "pg_rewrite"
/*
* Information needed to set sequences belonging the destination table
* according to the corresponding sequences of the source table.
*/
typedef struct SequenceValue
{
NameData attname;
int64 last_value;
} SequenceValue;
static void rewrite_table_impl(char *relschema_src, char *relname_src,
char *relname_new, char *relschema_dst,
char *relname_dst);
static Relation get_identity_index(Relation rel_dst, Relation rel_src);
static partitions_hash *get_partitions(Relation rel_src, Relation rel_dst,
int *nparts,
Relation **parts_dst_p,
ScanKey *ident_key_p,
int *ident_key_nentries);
static List *get_sequences(Relation rel);
static List *getOwnedSequences_internal(Oid relid, AttrNumber attnum,
char deptype);
static void set_sequences(Relation rel, List *seqs_src);
/* The WAL segment being decoded. */
XLogSegNo rewrite_current_segment = 0;
static void worker_shmem_request(void);
static void worker_shmem_startup(void);
static void worker_shmem_shutdown(int code, Datum arg);
static void relation_rewrite_get_args(PG_FUNCTION_ARGS, RangeVar **rv_src_p,
RangeVar **rv_src_new_p,
RangeVar **rv_dst_p);
static WorkerTask *get_task(int *idx, char *relschema, char *relname,
bool nowait);
static void initialize_worker(BackgroundWorker *worker, int task_idx);
static void run_worker(BackgroundWorker *worker, WorkerTask *task,
bool nowait);
static void send_message(WorkerTask *task, int elevel, const char *message,
const char *detail);
static void check_prerequisites(Relation rel);
static LogicalDecodingContext *setup_decoding(Relation rel);
static void decoding_cleanup(LogicalDecodingContext *ctx);
static ModifyTableState *get_modify_table_state(EState *estate, Relation rel,
CmdType operation);
static void free_modify_table_state(ModifyTableState *mtstate);
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,
TupleConversionMapExt *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,
Relation rel_src,
ScanKey ident_key,
int ident_key_nentries,
Relation ident_index,
TupleTableSlot *slot_dst_ind,
LogicalDecodingContext *ctx,
partitions_hash *ident_indexes,
TupleConversionMapExt *conv_map);
static void close_partitions(partitions_hash *partitions);
static AttrMapExt *make_attrmap_ext(int maplen);
static void free_attrmap_ext(AttrMapExt *map);
static TupleConversionMapExt *convert_tuples_by_name_ext(Relation rel_src,
Relation rel_dst);
static AttrMapExt *build_attrmap_by_name_if_req_ext(Relation rel_src,
Relation rel_dst);
static AttrMapExt *build_attrmap_by_name_ext(Relation rel_src,
Relation rel_dst);
static bool check_attrmap_match_ext(TupleDesc indesc, TupleDesc outdesc,
AttrMapExt *attrMap);
static TupleConversionMapExt *convert_tuples_by_name_attrmap_ext(TupleDesc indesc,
TupleDesc outdesc,
AttrMapExt *attrMap);
static void free_conversion_map_ext(TupleConversionMapExt *map);
static void copy_constraints(Oid relid_dst, const char *relname_dst,
Oid relid_src);
static void dump_fk_constraint(HeapTuple tup, Oid relid_dst,
const char *relname_dst, Oid relid_src,
StringInfo buf);
static void dump_check_constraint(Oid relid_dst, const char *relname_dst,
HeapTuple tup, StringInfo buf);
#if PG_VERSION_NUM >= 180000
static void dump_null_constraint(Oid relid_dst, const char *relname_dst,
HeapTuple tup, StringInfo buf);
static bool is_notnull_in_pk(Form_pg_constraint notnull, Oid relid);
#endif
static void dump_constraint_common(const char *nsp, const char *relname,
Form_pg_constraint con, StringInfo buf);
static int decompile_column_index_array(Datum column_index_array, Oid relId,
StringInfo buf);
static Node *build_generation_expression_ext(Relation rel, int attrno);
/*
* 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.
*/
static int rewrite_max_xlock_time = 0;
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
static 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;
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);
}
#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. We
* keep the symbol in the library so that the upgrade path works.
*/
extern Datum partition_table(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(partition_table);
Datum
partition_table(PG_FUNCTION_ARGS)
{
ereport(ERROR, (errmsg("the function is no longer supported"),
errhint("please run \"ALTER EXTENSION pg_rewrite UPDATE\"")));
PG_RETURN_VOID();
}
/*
* Likewise, keep the symbol because the upgrade path to 1.3 (or higher)
* requires that.
*/
extern Datum partition_table_new(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(partition_table_new);
Datum
partition_table_new(PG_FUNCTION_ARGS)
{
ereport(ERROR, (errmsg("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 worker 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, bool worker)
{
if (worker)
{
SpinLockAcquire(&task->mutex);
/*
* First, handle special case that can happen in regression tests. If
* rewrite_table_nowait() gets cancelled before the worker got its
* MyDatabaseId assigned, 'task' slot can leak (note that
* rewrite_table_nowait() does not release the task in this case). We
* can release the task regardless of MyDatabaseId because
* pg_rewrite_concurrent.spec should not launch a new worker (and thus
* reuse the task) before the existing one exited.
*/
if (task->nowait)
task->dbid = InvalidOid;
/*
* Otherwise, worker must not release the task because the backend can
* be interested in its contents.
*/
/*
* However, the worker always should clear the fields it set.
*/
task->pid = InvalidPid;
task->exit_requested = false;
SpinLockRelease(&task->mutex);
return;
}
/*
* The following should only be performed by the backend, after the worker
* has exited.
*/
SpinLockAcquire(&task->mutex);
Assert(OidIsValid(task->dbid));
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)
release_task(MyWorkerTask, true);
}
static void
relation_rewrite_get_args(PG_FUNCTION_ARGS, RangeVar **rv_src_p,
RangeVar **rv_src_new_p, RangeVar **rv_dst_p)
{
text *rel_src_t, *rel_src_new_t, *rel_dst_t;
RangeVar *rv_src, *rv_src_new, *rv_dst;
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"))));
*rv_src_p = rv_src;
*rv_src_new_p = rv_src_new;
*rv_dst_p = rv_dst;
}
/*
* Find a free task structure and initialize the common fields.
*/
static WorkerTask *
get_task(int *idx, char *relschema, char *relname, bool nowait)
{
int i;
WorkerTask *task = NULL;
bool found = false;
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")));
/* Finalize the task. */
task->roleid = GetUserId();
task->exit_requested = false;
if (relschema)
namestrcpy(&task->relschema, relschema);
else
NameStr(task->relschema)[0] = '\0';
namestrcpy(&task->relname, relname);
task->msg[0] = '\0';
task->msg_detail[0] = '\0';
task->elevel = -1;
task->nowait = nowait;
task->max_xlock_time = rewrite_max_xlock_time;
*idx = i;
return task;
}
static void
initialize_worker(BackgroundWorker *worker, int task_idx)
{
char *dbname;
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(MyDatabaseId);
snprintf(worker->bgw_name, BGW_MAXLEN,
"pg_rewrite worker for database %s", dbname);
snprintf(worker->bgw_type, BGW_MAXLEN, "pg_rewrite worker");
worker->bgw_main_arg = (Datum) task_idx;
worker->bgw_notify_pid = MyProcPid;
}
static void
run_worker(BackgroundWorker *worker, WorkerTask *task, bool nowait)
{
BackgroundWorkerHandle *handle;
BgwHandleStatus status;
pid_t pid;
char *msg = NULL;
char *msg_detail = NULL;
int elevel = -1;
/*
* 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, false);
PG_RE_THROW();
}
PG_END_TRY();
if (status == BGWH_STOPPED)
{
/* Work already done? */
goto done;
}
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);
if (nowait)
/* The worker should take care of releasing the task. */
return;
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, false);
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);
done:
if (strlen(task->msg) > 0)
{
msg = pstrdup(task->msg);
elevel = task->elevel;
}
if (strlen(task->msg_detail) > 0)
msg_detail = pstrdup(task->msg_detail);
release_task(task, false);
/* Report the worker's ERROR in the backend. */
if (msg)
{
if (msg_detail)
ereport(elevel, (errmsg("%s", msg),
errdetail("%s", msg_detail)));
else
ereport(elevel, (errmsg("%s", msg)));
}
}
/*
* Send log message from the worker to the backend that launched it.
*
* Currently we only copy 'message' and 'detail. More fields can be added to
* WorkerTask if needed. Another limitation is that if the worker sends
* multiple messages, the backend only receives the last one.
*
* (Ideally we should use the message queue like parallel workers do, but the
* related PG core functions have some parallel worker specific arguments.)
*/
static void
send_message(WorkerTask *task, int elevel, const char *message,
const char *detail)
{
strlcpy(task->msg, message, MAX_ERR_MSG_LEN);
task->elevel = elevel;
if (detail && strlen(detail) > 0)
strlcpy(task->msg_detail, detail, MAX_ERR_MSG_LEN);
else
/*
* Message with elevel < ERROR could already have been written here.
*/
task->msg_detail[0] = '\0';
}
/* 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 rewrite_table(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(rewrite_table);
Datum
rewrite_table(PG_FUNCTION_ARGS)
{
RangeVar *rv_src, *rv_src_new, *rv_dst;
BackgroundWorker worker;
WorkerTask *task;
int task_idx;
relation_rewrite_get_args(fcinfo, &rv_src, &rv_src_new, &rv_dst);
task = get_task(&task_idx, rv_src->schemaname, rv_src->relname, false);
Assert(task_idx < MAX_TASKS);
/* Specify the relation to be processed. */
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_new, rv_src_new->relname);
initialize_worker(&worker, task_idx);
run_worker(&worker, task, false);
PG_RETURN_VOID();
}
/*
* See pg_rewrite_concurrent.spec for information why this function is needed.
*/
extern Datum rewrite_table_nowait(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(rewrite_table_nowait);
Datum
rewrite_table_nowait(PG_FUNCTION_ARGS)
{
RangeVar *rv_src, *rv_src_new, *rv_dst;
BackgroundWorker worker;
WorkerTask *task;
int task_idx;
relation_rewrite_get_args(fcinfo, &rv_src, &rv_src_new, &rv_dst);
task = get_task(&task_idx, rv_src->schemaname, rv_src->relname, true);
Assert(task_idx < MAX_TASKS);
/* Specify the relation to be processed. */
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_new, rv_src_new->relname);
initialize_worker(&worker, task_idx);
run_worker(&worker, task, true);
PG_RETURN_VOID();
}
void
rewrite_worker_main(Datum main_arg)
{
Datum arg;
int i;
Oid dbid, roleid;
char *relschema, *relname, *relname_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 = NameStr(task->relschema);
relschema = *relschema != '\0' ? pstrdup(relschema) : NULL;
relname = pstrdup(NameStr(task->relname));
relname_new = pstrdup(NameStr(task->relname_new));
relschema_dst = NameStr(task->relschema_dst);
relschema_dst = *relschema_dst != '\0' ? pstrdup(relschema_dst) : NULL;
relname_dst = pstrdup(NameStr(task->relname_dst));
/*
* Get the information provided by the backend and set our pid.
*/
SpinLockAcquire(&MyWorkerTask->mutex);
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();
{
rewrite_table_impl(relschema, relname, relname_new, relschema_dst,
relname_dst);
CommitTransactionCommand();
/*
* In regression tests, use this injection point to check that
* the changes are visible by other transactions.
*/
#if PG_VERSION_NUM >= 180000
INJECTION_POINT("pg_rewrite-after-commit", NULL);
#elif PG_VERSION_NUM >= 170000
INJECTION_POINT("pg_rewrite-after-commit");
#endif
}
PG_CATCH();
{
MemoryContext old_context = CurrentMemoryContext;
ErrorData *edata;
/*
* If the backend is not waiting for our exit, make sure the error is
* logged.
*/
if (MyWorkerTask->nowait)
PG_RE_THROW();
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();
send_message(task, ERROR, edata->message, edata->detail);
FreeErrorData(edata);
}
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")));
}
/*
* Perform the rewriting.
*
* 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
rewrite_table_impl(char *relschema_src, char *relname_src,
char *relname_new, char *relschema_dst,
char *relname_dst)
{
RangeVar *relrv;
Relation rel_src,
rel_dst;
Oid relid_dst;
Oid ident_idx_src;
Oid relid_src;
Relation ident_index = NULL;
ScanKey ident_key;
TupleTableSlot *slot_dst_ind = NULL;
int i,
ident_key_nentries = 0;
LogicalDecodingContext *ctx;
ReplicationSlot *slot;
Snapshot snap_hist;
XLogRecPtr end_of_wal;
XLogRecPtr xlog_insert_ptr;
bool source_finalized;
Relation *parts_dst = NULL;
int nparts;
partitions_hash *partitions = NULL;
TupleConversionMapExt *conv_map;
EState *estate;
ModifyTableState *mtstate;
struct PartitionTupleRouting *proute = NULL;
List *seqs_src;
/*
* Use ShareUpdateExclusiveLock as it allows DML commands but does block
* most of DDLs (including CREATE INDEX).
*/
relrv = makeRangeVar(relschema_src, relname_src, -1);
rel_src = table_openrv(relrv, ShareUpdateExclusiveLock);
relid_src = RelationGetRelid(rel_src);
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.
*
* 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))));
/* Prepare for decoding of "concurrent data changes". */
ctx = setup_decoding(rel_src);
/*
* No one should need to access the destination table during our
* processing. We will eventually need AccessExclusiveLock for renaming,
* so acquire it right away.
*
* This should not be done before the call of setup_decoding() as the
* exclusive lock does assign XID. (setup_decoding() would then wait for
* our transaction to complete.)
*/
relrv = makeRangeVar(relschema_dst, relname_dst, -1);
rel_dst = table_openrv(relrv, AccessExclusiveLock);
relid_dst = RelationGetRelid(rel_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)));
/*
* 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);
/*
* Cope with commit 706054b11b in PG core.
*
* If we did this earlier, earlier SnapBuildInitialSnapshot() would raise
* ERROR. We shouldn't have called heap_insert|update|delete by now
* anyway.
*/
PushActiveSnapshot(GetTransactionSnapshot());
/*
* Create a conversion map so that we can handle difference(s) in the
* tuple descriptor.