Line data Source code
1 : /*-------------------------------------------------------------------------
2 : * sequencesync.c
3 : * PostgreSQL logical replication: sequence synchronization
4 : *
5 : * Copyright (c) 2025-2026, PostgreSQL Global Development Group
6 : *
7 : * IDENTIFICATION
8 : * src/backend/replication/logical/sequencesync.c
9 : *
10 : * NOTES
11 : * This file contains code for sequence synchronization for
12 : * logical replication.
13 : *
14 : * Sequences requiring synchronization are tracked in the pg_subscription_rel
15 : * catalog.
16 : *
17 : * Sequences to be synchronized will be added with state INIT when either of
18 : * the following commands is executed:
19 : * CREATE SUBSCRIPTION
20 : * ALTER SUBSCRIPTION ... REFRESH PUBLICATION
21 : *
22 : * Executing the following command resets all sequences in the subscription to
23 : * state INIT, triggering re-synchronization:
24 : * ALTER SUBSCRIPTION ... REFRESH SEQUENCES
25 : *
26 : * The apply worker periodically scans pg_subscription_rel for sequences in
27 : * INIT state. When such sequences are found, it spawns a sequencesync worker
28 : * to handle synchronization.
29 : *
30 : * A single sequencesync worker is responsible for synchronizing all sequences.
31 : * It begins by retrieving the list of sequences that are flagged for
32 : * synchronization, i.e., those in the INIT state. These sequences are then
33 : * processed in batches, allowing multiple entries to be synchronized within a
34 : * single transaction. The worker fetches the current sequence values and page
35 : * LSNs from the remote publisher, updates the corresponding sequences on the
36 : * local subscriber, and finally marks each sequence as READY upon successful
37 : * synchronization.
38 : *
39 : * Sequence state transitions follow this pattern:
40 : * INIT -> READY
41 : *
42 : * To avoid creating too many transactions, up to MAX_SEQUENCES_SYNC_PER_BATCH
43 : * sequences are synchronized per transaction. The locks on the sequence
44 : * relation will be periodically released at each transaction commit.
45 : *
46 : * XXX: We didn't choose launcher process to maintain the launch of sequencesync
47 : * worker as it didn't have database connection to access the sequences from the
48 : * pg_subscription_rel system catalog that need to be synchronized.
49 : *-------------------------------------------------------------------------
50 : */
51 :
52 : #include "postgres.h"
53 :
54 : #include "access/genam.h"
55 : #include "access/table.h"
56 : #include "catalog/pg_sequence.h"
57 : #include "catalog/pg_subscription_rel.h"
58 : #include "commands/sequence.h"
59 : #include "pgstat.h"
60 : #include "postmaster/interrupt.h"
61 : #include "replication/logicalworker.h"
62 : #include "replication/worker_internal.h"
63 : #include "storage/lwlock.h"
64 : #include "utils/acl.h"
65 : #include "utils/builtins.h"
66 : #include "utils/fmgroids.h"
67 : #include "utils/guc.h"
68 : #include "utils/inval.h"
69 : #include "utils/lsyscache.h"
70 : #include "utils/memutils.h"
71 : #include "utils/pg_lsn.h"
72 : #include "utils/syscache.h"
73 : #include "utils/usercontext.h"
74 :
75 : #define REMOTE_SEQ_COL_COUNT 10
76 :
77 : typedef enum CopySeqResult
78 : {
79 : COPYSEQ_SUCCESS,
80 : COPYSEQ_MISMATCH,
81 : COPYSEQ_INSUFFICIENT_PERM,
82 : COPYSEQ_SKIPPED
83 : } CopySeqResult;
84 :
85 : static List *seqinfos = NIL;
86 :
87 : /*
88 : * Apply worker determines if sequence synchronization is needed.
89 : *
90 : * Start a sequencesync worker if one is not already running. The active
91 : * sequencesync worker will handle all pending sequence synchronization. If any
92 : * sequences remain unsynchronized after it exits, a new worker can be started
93 : * in the next iteration.
94 : */
95 : void
96 8544 : ProcessSequencesForSync(void)
97 : {
98 : LogicalRepWorker *sequencesync_worker;
99 : int nsyncworkers;
100 : bool has_pending_sequences;
101 : bool started_tx;
102 :
103 8544 : FetchRelationStates(NULL, &has_pending_sequences, &started_tx);
104 :
105 8544 : if (started_tx)
106 : {
107 191 : CommitTransactionCommand();
108 191 : pgstat_report_stat(true);
109 : }
110 :
111 8544 : if (!has_pending_sequences)
112 8529 : return;
113 :
114 27 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
115 :
116 : /* Check if there is a sequencesync worker already running? */
117 27 : sequencesync_worker = logicalrep_worker_find(WORKERTYPE_SEQUENCESYNC,
118 27 : MyLogicalRepWorker->subid,
119 : InvalidOid, true);
120 27 : if (sequencesync_worker)
121 : {
122 12 : LWLockRelease(LogicalRepWorkerLock);
123 12 : return;
124 : }
125 :
126 : /*
127 : * Count running sync workers for this subscription, while we have the
128 : * lock.
129 : */
130 15 : nsyncworkers = logicalrep_sync_worker_count(MyLogicalRepWorker->subid);
131 15 : LWLockRelease(LogicalRepWorkerLock);
132 :
133 : /*
134 : * It is okay to read/update last_seqsync_start_time here in apply worker
135 : * as we have already ensured that sync worker doesn't exist.
136 : */
137 15 : launch_sync_worker(WORKERTYPE_SEQUENCESYNC, nsyncworkers, InvalidOid,
138 15 : &MyLogicalRepWorker->last_seqsync_start_time);
139 : }
140 :
141 : /*
142 : * get_sequences_string
143 : *
144 : * Build a comma-separated string of schema-qualified sequence names
145 : * for the given list of sequence indexes.
146 : */
147 : static void
148 4 : get_sequences_string(List *seqindexes, StringInfo buf)
149 : {
150 4 : resetStringInfo(buf);
151 12 : foreach_int(seqidx, seqindexes)
152 : {
153 : LogicalRepSequenceInfo *seqinfo =
154 4 : (LogicalRepSequenceInfo *) list_nth(seqinfos, seqidx);
155 :
156 4 : if (buf->len > 0)
157 0 : appendStringInfoString(buf, ", ");
158 :
159 4 : appendStringInfo(buf, "\"%s.%s\"", seqinfo->nspname, seqinfo->seqname);
160 : }
161 4 : }
162 :
163 : /*
164 : * report_sequence_errors
165 : *
166 : * Report discrepancies found during sequence synchronization between
167 : * the publisher and subscriber. Emits warnings for:
168 : * a) mismatched definitions or concurrent rename
169 : * b) insufficient privileges
170 : * c) missing sequences on the subscriber
171 : * Then raises an ERROR to indicate synchronization failure.
172 : */
173 : static void
174 9 : report_sequence_errors(List *mismatched_seqs_idx, List *insuffperm_seqs_idx,
175 : List *missing_seqs_idx)
176 : {
177 : StringInfoData seqstr;
178 :
179 : /* Quick exit if there are no errors to report */
180 9 : if (!mismatched_seqs_idx && !insuffperm_seqs_idx && !missing_seqs_idx)
181 5 : return;
182 :
183 4 : initStringInfo(&seqstr);
184 :
185 4 : if (mismatched_seqs_idx)
186 : {
187 3 : get_sequences_string(mismatched_seqs_idx, &seqstr);
188 3 : ereport(WARNING,
189 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
190 : errmsg_plural("mismatched or renamed sequence on subscriber (%s)",
191 : "mismatched or renamed sequences on subscriber (%s)",
192 : list_length(mismatched_seqs_idx),
193 : seqstr.data));
194 : }
195 :
196 4 : if (insuffperm_seqs_idx)
197 : {
198 0 : get_sequences_string(insuffperm_seqs_idx, &seqstr);
199 0 : ereport(WARNING,
200 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
201 : errmsg_plural("insufficient privileges on sequence (%s)",
202 : "insufficient privileges on sequences (%s)",
203 : list_length(insuffperm_seqs_idx),
204 : seqstr.data));
205 : }
206 :
207 4 : if (missing_seqs_idx)
208 : {
209 1 : get_sequences_string(missing_seqs_idx, &seqstr);
210 1 : ereport(WARNING,
211 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
212 : errmsg_plural("missing sequence on publisher (%s)",
213 : "missing sequences on publisher (%s)",
214 : list_length(missing_seqs_idx),
215 : seqstr.data));
216 : }
217 :
218 4 : ereport(ERROR,
219 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
220 : errmsg("logical replication sequence synchronization failed for subscription \"%s\"",
221 : MySubscription->name));
222 : }
223 :
224 : /*
225 : * get_and_validate_seq_info
226 : *
227 : * Extracts remote sequence information from the tuple slot received from the
228 : * publisher, and validates it against the corresponding local sequence
229 : * definition.
230 : */
231 : static CopySeqResult
232 12 : get_and_validate_seq_info(TupleTableSlot *slot, Relation *sequence_rel,
233 : LogicalRepSequenceInfo **seqinfo, int *seqidx)
234 : {
235 : bool isnull;
236 12 : int col = 0;
237 : Datum datum;
238 : Oid remote_typid;
239 : int64 remote_start;
240 : int64 remote_increment;
241 : int64 remote_min;
242 : int64 remote_max;
243 : bool remote_cycle;
244 12 : CopySeqResult result = COPYSEQ_SUCCESS;
245 : HeapTuple tup;
246 : Form_pg_sequence local_seq;
247 : LogicalRepSequenceInfo *seqinfo_local;
248 :
249 12 : *seqidx = DatumGetInt32(slot_getattr(slot, ++col, &isnull));
250 : Assert(!isnull);
251 :
252 : /* Identify the corresponding local sequence for the given index. */
253 12 : *seqinfo = seqinfo_local =
254 12 : (LogicalRepSequenceInfo *) list_nth(seqinfos, *seqidx);
255 :
256 : /*
257 : * last_value can be NULL if the sequence was dropped concurrently (see
258 : * pg_get_sequence_data()).
259 : */
260 12 : datum = slot_getattr(slot, ++col, &isnull);
261 12 : if (isnull)
262 0 : return COPYSEQ_SKIPPED;
263 12 : seqinfo_local->last_value = DatumGetInt64(datum);
264 :
265 12 : seqinfo_local->is_called = DatumGetBool(slot_getattr(slot, ++col, &isnull));
266 : Assert(!isnull);
267 :
268 12 : seqinfo_local->page_lsn = DatumGetLSN(slot_getattr(slot, ++col, &isnull));
269 : Assert(!isnull);
270 :
271 12 : remote_typid = DatumGetObjectId(slot_getattr(slot, ++col, &isnull));
272 : Assert(!isnull);
273 :
274 12 : remote_start = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
275 : Assert(!isnull);
276 :
277 12 : remote_increment = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
278 : Assert(!isnull);
279 :
280 12 : remote_min = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
281 : Assert(!isnull);
282 :
283 12 : remote_max = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
284 : Assert(!isnull);
285 :
286 12 : remote_cycle = DatumGetBool(slot_getattr(slot, ++col, &isnull));
287 : Assert(!isnull);
288 :
289 : /* Sanity check */
290 : Assert(col == REMOTE_SEQ_COL_COUNT);
291 :
292 12 : seqinfo_local->found_on_pub = true;
293 :
294 12 : *sequence_rel = try_table_open(seqinfo_local->localrelid, RowExclusiveLock);
295 :
296 : /* Sequence was concurrently dropped? */
297 12 : if (!*sequence_rel)
298 0 : return COPYSEQ_SKIPPED;
299 :
300 12 : tup = SearchSysCache1(SEQRELID, ObjectIdGetDatum(seqinfo_local->localrelid));
301 :
302 : /* Sequence was concurrently dropped? */
303 12 : if (!HeapTupleIsValid(tup))
304 0 : elog(ERROR, "cache lookup failed for sequence %u",
305 : seqinfo_local->localrelid);
306 :
307 12 : local_seq = (Form_pg_sequence) GETSTRUCT(tup);
308 :
309 : /* Sequence parameters for remote/local are the same? */
310 12 : if (local_seq->seqtypid != remote_typid ||
311 12 : local_seq->seqstart != remote_start ||
312 11 : local_seq->seqincrement != remote_increment ||
313 9 : local_seq->seqmin != remote_min ||
314 9 : local_seq->seqmax != remote_max ||
315 9 : local_seq->seqcycle != remote_cycle)
316 3 : result = COPYSEQ_MISMATCH;
317 :
318 : /* Sequence was concurrently renamed? */
319 12 : if (strcmp(seqinfo_local->nspname,
320 12 : get_namespace_name(RelationGetNamespace(*sequence_rel))) ||
321 12 : strcmp(seqinfo_local->seqname, RelationGetRelationName(*sequence_rel)))
322 0 : result = COPYSEQ_MISMATCH;
323 :
324 12 : ReleaseSysCache(tup);
325 12 : return result;
326 : }
327 :
328 : /*
329 : * Apply remote sequence state to local sequence and mark it as
330 : * synchronized (READY).
331 : */
332 : static CopySeqResult
333 9 : copy_sequence(LogicalRepSequenceInfo *seqinfo, Oid seqowner)
334 : {
335 : UserContext ucxt;
336 : AclResult aclresult;
337 9 : bool run_as_owner = MySubscription->runasowner;
338 9 : Oid seqoid = seqinfo->localrelid;
339 :
340 : /*
341 : * If the user did not opt to run as the owner of the subscription
342 : * ('run_as_owner'), then copy the sequence as the owner of the sequence.
343 : */
344 9 : if (!run_as_owner)
345 9 : SwitchToUntrustedUser(seqowner, &ucxt);
346 :
347 9 : aclresult = pg_class_aclcheck(seqoid, GetUserId(), ACL_UPDATE);
348 :
349 9 : if (aclresult != ACLCHECK_OK)
350 : {
351 0 : if (!run_as_owner)
352 0 : RestoreUserContext(&ucxt);
353 :
354 0 : return COPYSEQ_INSUFFICIENT_PERM;
355 : }
356 :
357 : /*
358 : * The log counter (log_cnt) tracks how many sequence values are still
359 : * unused locally. It is only relevant to the local node and managed
360 : * internally by nextval() when allocating new ranges. Since log_cnt does
361 : * not affect the visible sequence state (like last_value or is_called)
362 : * and is only used for local caching, it need not be copied to the
363 : * subscriber during synchronization.
364 : */
365 9 : SetSequence(seqoid, seqinfo->last_value, seqinfo->is_called);
366 :
367 9 : if (!run_as_owner)
368 9 : RestoreUserContext(&ucxt);
369 :
370 : /*
371 : * Record the remote sequence's LSN in pg_subscription_rel and mark the
372 : * sequence as READY.
373 : */
374 9 : UpdateSubscriptionRelState(MySubscription->oid, seqoid, SUBREL_STATE_READY,
375 : seqinfo->page_lsn, false);
376 :
377 9 : return COPYSEQ_SUCCESS;
378 : }
379 :
380 : /*
381 : * Copy existing data of sequences from the publisher.
382 : */
383 : static void
384 9 : copy_sequences(WalReceiverConn *conn)
385 : {
386 9 : int cur_batch_base_index = 0;
387 9 : int n_seqinfos = list_length(seqinfos);
388 9 : List *mismatched_seqs_idx = NIL;
389 9 : List *missing_seqs_idx = NIL;
390 9 : List *insuffperm_seqs_idx = NIL;
391 : StringInfoData seqstr;
392 : StringInfoData cmd;
393 : MemoryContext oldctx;
394 :
395 9 : initStringInfo(&seqstr);
396 9 : initStringInfo(&cmd);
397 :
398 : #define MAX_SEQUENCES_SYNC_PER_BATCH 100
399 :
400 9 : elog(DEBUG1,
401 : "logical replication sequence synchronization for subscription \"%s\" - total unsynchronized: %d",
402 : MySubscription->name, n_seqinfos);
403 :
404 18 : while (cur_batch_base_index < n_seqinfos)
405 : {
406 9 : Oid seqRow[REMOTE_SEQ_COL_COUNT] = {INT8OID, INT8OID,
407 : BOOLOID, LSNOID, OIDOID, INT8OID, INT8OID, INT8OID, INT8OID, BOOLOID};
408 9 : int batch_size = 0;
409 9 : int batch_succeeded_count = 0;
410 9 : int batch_mismatched_count = 0;
411 9 : int batch_skipped_count = 0;
412 9 : int batch_insuffperm_count = 0;
413 : int batch_missing_count;
414 9 : Relation sequence_rel = NULL;
415 :
416 : WalRcvExecResult *res;
417 : TupleTableSlot *slot;
418 :
419 9 : StartTransactionCommand();
420 :
421 22 : for (int idx = cur_batch_base_index; idx < n_seqinfos; idx++)
422 : {
423 : char *nspname_literal;
424 : char *seqname_literal;
425 :
426 : LogicalRepSequenceInfo *seqinfo =
427 13 : (LogicalRepSequenceInfo *) list_nth(seqinfos, idx);
428 :
429 13 : if (seqstr.len > 0)
430 4 : appendStringInfoString(&seqstr, ", ");
431 :
432 13 : nspname_literal = quote_literal_cstr(seqinfo->nspname);
433 13 : seqname_literal = quote_literal_cstr(seqinfo->seqname);
434 :
435 13 : appendStringInfo(&seqstr, "(%s, %s, %d)",
436 : nspname_literal, seqname_literal, idx);
437 :
438 13 : if (++batch_size == MAX_SEQUENCES_SYNC_PER_BATCH)
439 0 : break;
440 : }
441 :
442 : /*
443 : * We deliberately avoid acquiring a local lock on the sequence before
444 : * querying the publisher to prevent potential distributed deadlocks
445 : * in bi-directional replication setups.
446 : *
447 : * Example scenario:
448 : *
449 : * - On each node, a background worker acquires a lock on a sequence
450 : * as part of a sync operation.
451 : *
452 : * - Concurrently, a user transaction attempts to alter the same
453 : * sequence, waiting on the background worker's lock.
454 : *
455 : * - Meanwhile, a query from the other node tries to access metadata
456 : * that depends on the completion of the alter operation.
457 : *
458 : * - This creates a circular wait across nodes:
459 : *
460 : * Node-1: Query -> waits on Alter -> waits on Sync Worker
461 : *
462 : * Node-2: Query -> waits on Alter -> waits on Sync Worker
463 : *
464 : * Since each node only sees part of the wait graph, the deadlock may
465 : * go undetected, leading to indefinite blocking.
466 : *
467 : * Note: Each entry in VALUES includes an index 'seqidx' that
468 : * represents the sequence's position in the local 'seqinfos' list.
469 : * This index is propagated to the query results and later used to
470 : * directly map the fetched publisher sequence rows back to their
471 : * corresponding local entries without relying on result order or name
472 : * matching.
473 : */
474 9 : appendStringInfo(&cmd,
475 : "SELECT s.seqidx, ps.*, seq.seqtypid,\n"
476 : " seq.seqstart, seq.seqincrement, seq.seqmin,\n"
477 : " seq.seqmax, seq.seqcycle\n"
478 : "FROM ( VALUES %s ) AS s (schname, seqname, seqidx)\n"
479 : "JOIN pg_namespace n ON n.nspname = s.schname\n"
480 : "JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = s.seqname\n"
481 : "JOIN pg_sequence seq ON seq.seqrelid = c.oid\n"
482 : "JOIN LATERAL pg_get_sequence_data(seq.seqrelid) AS ps ON true\n",
483 : seqstr.data);
484 :
485 9 : res = walrcv_exec(conn, cmd.data, lengthof(seqRow), seqRow);
486 9 : if (res->status != WALRCV_OK_TUPLES)
487 0 : ereport(ERROR,
488 : errcode(ERRCODE_CONNECTION_FAILURE),
489 : errmsg("could not fetch sequence information from the publisher: %s",
490 : res->err));
491 :
492 9 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
493 21 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
494 : {
495 : CopySeqResult sync_status;
496 : LogicalRepSequenceInfo *seqinfo;
497 : int seqidx;
498 :
499 12 : CHECK_FOR_INTERRUPTS();
500 :
501 12 : if (ConfigReloadPending)
502 : {
503 0 : ConfigReloadPending = false;
504 0 : ProcessConfigFile(PGC_SIGHUP);
505 : }
506 :
507 12 : sync_status = get_and_validate_seq_info(slot, &sequence_rel,
508 : &seqinfo, &seqidx);
509 12 : if (sync_status == COPYSEQ_SUCCESS)
510 9 : sync_status = copy_sequence(seqinfo,
511 9 : sequence_rel->rd_rel->relowner);
512 :
513 12 : switch (sync_status)
514 : {
515 9 : case COPYSEQ_SUCCESS:
516 9 : elog(DEBUG1,
517 : "logical replication synchronization for subscription \"%s\", sequence \"%s.%s\" has finished",
518 : MySubscription->name, seqinfo->nspname,
519 : seqinfo->seqname);
520 9 : batch_succeeded_count++;
521 9 : break;
522 3 : case COPYSEQ_MISMATCH:
523 :
524 : /*
525 : * Remember mismatched sequences in a long-lived memory
526 : * context since these will be used after the transaction
527 : * is committed.
528 : */
529 3 : oldctx = MemoryContextSwitchTo(ApplyContext);
530 3 : mismatched_seqs_idx = lappend_int(mismatched_seqs_idx,
531 : seqidx);
532 3 : MemoryContextSwitchTo(oldctx);
533 3 : batch_mismatched_count++;
534 3 : break;
535 0 : case COPYSEQ_INSUFFICIENT_PERM:
536 :
537 : /*
538 : * Remember sequences with insufficient privileges in a
539 : * long-lived memory context since these will be used
540 : * after the transaction is committed.
541 : */
542 0 : oldctx = MemoryContextSwitchTo(ApplyContext);
543 0 : insuffperm_seqs_idx = lappend_int(insuffperm_seqs_idx,
544 : seqidx);
545 0 : MemoryContextSwitchTo(oldctx);
546 0 : batch_insuffperm_count++;
547 0 : break;
548 0 : case COPYSEQ_SKIPPED:
549 :
550 : /*
551 : * Concurrent removal of a sequence on the subscriber is
552 : * treated as success, since the only viable action is to
553 : * skip the corresponding sequence data. Missing sequences
554 : * on the publisher are treated as ERROR.
555 : */
556 0 : if (seqinfo->found_on_pub)
557 : {
558 0 : ereport(LOG,
559 : errmsg("skip synchronization of sequence \"%s.%s\" because it has been dropped concurrently",
560 : seqinfo->nspname,
561 : seqinfo->seqname));
562 0 : batch_skipped_count++;
563 : }
564 0 : break;
565 : }
566 :
567 12 : if (sequence_rel)
568 12 : table_close(sequence_rel, NoLock);
569 : }
570 :
571 9 : ExecDropSingleTupleTableSlot(slot);
572 9 : walrcv_clear_result(res);
573 9 : resetStringInfo(&seqstr);
574 9 : resetStringInfo(&cmd);
575 :
576 9 : batch_missing_count = batch_size - (batch_succeeded_count +
577 9 : batch_mismatched_count +
578 9 : batch_insuffperm_count +
579 : batch_skipped_count);
580 :
581 9 : elog(DEBUG1,
582 : "logical replication sequence synchronization for subscription \"%s\" - batch #%d = %d attempted, %d succeeded, %d mismatched, %d insufficient permission, %d missing from publisher, %d skipped",
583 : MySubscription->name,
584 : (cur_batch_base_index / MAX_SEQUENCES_SYNC_PER_BATCH) + 1,
585 : batch_size, batch_succeeded_count, batch_mismatched_count,
586 : batch_insuffperm_count, batch_missing_count, batch_skipped_count);
587 :
588 : /* Commit this batch, and prepare for next batch */
589 9 : CommitTransactionCommand();
590 :
591 9 : if (batch_missing_count)
592 : {
593 2 : for (int idx = cur_batch_base_index; idx < cur_batch_base_index + batch_size; idx++)
594 : {
595 : LogicalRepSequenceInfo *seqinfo =
596 1 : (LogicalRepSequenceInfo *) list_nth(seqinfos, idx);
597 :
598 : /* If the sequence was not found on publisher, record it */
599 1 : if (!seqinfo->found_on_pub)
600 1 : missing_seqs_idx = lappend_int(missing_seqs_idx, idx);
601 : }
602 : }
603 :
604 : /*
605 : * cur_batch_base_index is not incremented sequentially because some
606 : * sequences may be missing, and the number of fetched rows may not
607 : * match the batch size.
608 : */
609 9 : cur_batch_base_index += batch_size;
610 : }
611 :
612 : /* Report mismatches, permission issues, or missing sequences */
613 9 : report_sequence_errors(mismatched_seqs_idx, insuffperm_seqs_idx,
614 : missing_seqs_idx);
615 5 : }
616 :
617 : /*
618 : * Identifies sequences that require synchronization and initiates the
619 : * synchronization process.
620 : */
621 : static void
622 9 : LogicalRepSyncSequences(void)
623 : {
624 : char *err;
625 : bool must_use_password;
626 : Relation rel;
627 : HeapTuple tup;
628 : ScanKeyData skey[2];
629 : SysScanDesc scan;
630 9 : Oid subid = MyLogicalRepWorker->subid;
631 : StringInfoData app_name;
632 :
633 9 : StartTransactionCommand();
634 :
635 9 : rel = table_open(SubscriptionRelRelationId, AccessShareLock);
636 :
637 9 : ScanKeyInit(&skey[0],
638 : Anum_pg_subscription_rel_srsubid,
639 : BTEqualStrategyNumber, F_OIDEQ,
640 : ObjectIdGetDatum(subid));
641 :
642 9 : ScanKeyInit(&skey[1],
643 : Anum_pg_subscription_rel_srsubstate,
644 : BTEqualStrategyNumber, F_CHAREQ,
645 : CharGetDatum(SUBREL_STATE_INIT));
646 :
647 9 : scan = systable_beginscan(rel, InvalidOid, false,
648 : NULL, 2, skey);
649 23 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
650 : {
651 : Form_pg_subscription_rel subrel;
652 : LogicalRepSequenceInfo *seq;
653 : Relation sequence_rel;
654 : MemoryContext oldctx;
655 :
656 14 : CHECK_FOR_INTERRUPTS();
657 :
658 14 : subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
659 :
660 14 : sequence_rel = try_table_open(subrel->srrelid, RowExclusiveLock);
661 :
662 : /* Skip if sequence was dropped concurrently */
663 14 : if (!sequence_rel)
664 0 : continue;
665 :
666 : /* Skip if the relation is not a sequence */
667 14 : if (sequence_rel->rd_rel->relkind != RELKIND_SEQUENCE)
668 : {
669 1 : table_close(sequence_rel, NoLock);
670 1 : continue;
671 : }
672 :
673 : /*
674 : * Worker needs to process sequences across transaction boundary, so
675 : * allocate them under long-lived context.
676 : */
677 13 : oldctx = MemoryContextSwitchTo(ApplyContext);
678 :
679 13 : seq = palloc0_object(LogicalRepSequenceInfo);
680 13 : seq->localrelid = subrel->srrelid;
681 13 : seq->nspname = get_namespace_name(RelationGetNamespace(sequence_rel));
682 13 : seq->seqname = pstrdup(RelationGetRelationName(sequence_rel));
683 13 : seqinfos = lappend(seqinfos, seq);
684 :
685 13 : MemoryContextSwitchTo(oldctx);
686 :
687 13 : table_close(sequence_rel, NoLock);
688 : }
689 :
690 : /* Cleanup */
691 9 : systable_endscan(scan);
692 9 : table_close(rel, AccessShareLock);
693 :
694 9 : CommitTransactionCommand();
695 :
696 : /*
697 : * Exit early if no catalog entries found, likely due to concurrent drops.
698 : */
699 9 : if (!seqinfos)
700 0 : return;
701 :
702 : /* Is the use of a password mandatory? */
703 18 : must_use_password = MySubscription->passwordrequired &&
704 9 : !MySubscription->ownersuperuser;
705 :
706 9 : initStringInfo(&app_name);
707 9 : appendStringInfo(&app_name, "pg_%u_sequence_sync_" UINT64_FORMAT,
708 9 : MySubscription->oid, GetSystemIdentifier());
709 :
710 : /*
711 : * Establish the connection to the publisher for sequence synchronization.
712 : */
713 9 : LogRepWorkerWalRcvConn =
714 9 : walrcv_connect(MySubscription->conninfo, true, true,
715 : must_use_password,
716 : app_name.data, &err);
717 9 : if (LogRepWorkerWalRcvConn == NULL)
718 0 : ereport(ERROR,
719 : errcode(ERRCODE_CONNECTION_FAILURE),
720 : errmsg("sequencesync worker for subscription \"%s\" could not connect to the publisher: %s",
721 : MySubscription->name, err));
722 :
723 9 : pfree(app_name.data);
724 :
725 9 : copy_sequences(LogRepWorkerWalRcvConn);
726 : }
727 :
728 : /*
729 : * Execute the initial sync with error handling. Disable the subscription,
730 : * if required.
731 : *
732 : * Note that we don't handle FATAL errors which are probably because of system
733 : * resource error and are not repeatable.
734 : */
735 : static void
736 9 : start_sequence_sync(void)
737 : {
738 : Assert(am_sequencesync_worker());
739 :
740 9 : PG_TRY();
741 : {
742 : /* Call initial sync. */
743 9 : LogicalRepSyncSequences();
744 : }
745 4 : PG_CATCH();
746 : {
747 4 : if (MySubscription->disableonerr)
748 0 : DisableSubscriptionAndExit();
749 : else
750 : {
751 : /*
752 : * Report the worker failed during sequence synchronization. Abort
753 : * the current transaction so that the stats message is sent in an
754 : * idle state.
755 : */
756 4 : AbortOutOfAnyTransaction();
757 4 : pgstat_report_subscription_error(MySubscription->oid);
758 :
759 4 : PG_RE_THROW();
760 : }
761 : }
762 5 : PG_END_TRY();
763 5 : }
764 :
765 : /* Logical Replication sequencesync worker entry point */
766 : void
767 9 : SequenceSyncWorkerMain(Datum main_arg)
768 : {
769 9 : int worker_slot = DatumGetInt32(main_arg);
770 :
771 9 : SetupApplyOrSyncWorker(worker_slot);
772 :
773 9 : start_sequence_sync();
774 :
775 5 : FinishSyncWorker();
776 : }
|