Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ All notable changes to pgclone are documented in this file.
- `"conflict": "ignore"` (discussion #24): if the target table already exists, keep its definition (skip table DDL, constraints, indexes, triggers) and still load the data. Works in the sync and async paths.

### Fixed
- **Partitioned tables clone correctly (issue #38).** `pgclone.schema()`, `schema_async()` (including the parallel pool) and `table_async()` used to create a partitioned parent as a plain table and then abort with `cannot copy from partitioned table`. A partitioned parent is now created with `PARTITION BY`, each partition with `PARTITION OF <parent> FOR VALUES ...` (sub-partitioning included), and rows are copied once, from leaf partitions only. Partitions inherit the parent's primary key / indexes / triggers instead of having them cloned twice, and the table list is ordered so parents exist before their partitions (a pool worker waits for the parent). `pgclone.table()` on a partitioned parent creates just the parent; clone the schema (or each partition) to get the partitions.
- **Generated columns stay generated, and COPY skips them.** `CREATE TABLE` reconstruction treated every `pg_attrdef` entry as a `DEFAULT`, so `GENERATED ALWAYS AS (...) STORED` columns (and PostgreSQL 18 `VIRTUAL` columns) were cloned as ordinary defaults. Once a column stays generated, a bare `COPY table` fails on the way in (`column "..." is a generated column`). Table DDL now emits `GENERATED ALWAYS AS (...) STORED` or `VIRTUAL`, and both the synchronous COPY path and the background worker omit generated columns so the target recomputes them. Ordinary defaults are unchanged. A generated column named in an explicit `"columns"` list is still rejected by the server; leave those columns out of the list. Virtual generated columns need PostgreSQL 18 on the target.

## [4.7.0]
Expand Down
4 changes: 4 additions & 0 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ SELECT pgclone.table(
);
```

### Partitioned tables

A partitioned table is cloned with its structure: the parent gets `PARTITION BY`, each partition is created with `PARTITION OF <parent> FOR VALUES ...` (sub-partitions included), and the parent's primary key, indexes and triggers are inherited by the partitions rather than cloned separately. Rows are copied once, from the leaf partitions. Use `pgclone.schema()` / `schema_async()` to clone a partitioned table together with its partitions. `pgclone.table()` on a partitioned parent creates only the parent; clone each partition (or the schema) to bring the partitions and data. With `"conflict": "skip"`, existing parents and partitions are skipped by name.

### Generated columns

`GENERATED ALWAYS AS (...) STORED` columns, and `VIRTUAL` generated columns on PostgreSQL 18, are cloned as generated columns rather than as defaults. COPY does not write them; the target computes each value from the generation expression. Omit generated columns from an explicit `"columns"` list — PostgreSQL rejects `COPY` into a generated column. A virtual generated column needs PostgreSQL 18 on the target. Generation expressions that call a function in the same schema still require that function to exist first, the same as a `DEFAULT` expression does.
Expand Down
84 changes: 81 additions & 3 deletions src/pgclone.c
Original file line number Diff line number Diff line change
Expand Up @@ -1936,6 +1936,12 @@ pgclone_indexes(PGconn *source_conn, PGconn *target_conn,
"AND NOT EXISTS ("
" SELECT 1 FROM pg_catalog.pg_constraint con "
" WHERE con.conindid = i.indexrelid"
") "
/* partition indexes inherited from the parent's index are created
* automatically when the partition is created / attached */
"AND NOT EXISTS ("
" SELECT 1 FROM pg_catalog.pg_inherits ih "
" WHERE ih.inhrelid = i.indexrelid"
")",
quote_literal_cstr(schema_name),
quote_literal_cstr(source_table));
Expand All @@ -1949,6 +1955,15 @@ pgclone_indexes(PGconn *source_conn, PGconn *target_conn,
char *idx_cols = PQgetvalue(res, i, 1);
StringInfoData final_def;

/* An index on a partitioned parent is dumped as "ON ONLY"; drop
* ONLY so it is created as a normal partitioned index and is
* inherited by every partition. */
{
char *only = strstr(indexdef, " ON ONLY ");
if (only != NULL)
memmove(only + 4, only + 9, strlen(only + 9) + 1);
}

/* If selective column clone, skip indexes on columns not in target */
if (opts != NULL && opts->num_columns > 0)
{
Expand Down Expand Up @@ -2080,6 +2095,7 @@ pgclone_constraints(PGconn *source_conn, PGconn *target_conn,
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"WHERE n.nspname = %s AND c.relname = %s "
"AND con.contype != 'n' " /* NOT NULL is handled by table DDL already */
"AND con.conparentid = 0 " /* partition-inherited: created via the parent */
"AND con.contype != 'f' " /* FK constraints handled separately after all tables created */
"ORDER BY "
" CASE contype "
Expand Down Expand Up @@ -2236,6 +2252,7 @@ pgclone_triggers(PGconn *source_conn, PGconn *target_conn,
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"WHERE n.nspname = %s AND c.relname = %s "
"AND NOT t.tgisinternal "
"AND t.tgparentid = 0 " /* partition-cloned triggers come from the parent */
"ORDER BY t.tgname",
quote_literal_cstr(schema_name),
quote_literal_cstr(source_table));
Expand Down Expand Up @@ -2469,6 +2486,9 @@ pgclone_table(PG_FUNCTION_ARGS)
StringInfoData buf;
PgcloneSyncConflictResult table_conflict;
bool ddl_exists = false;
bool is_partitioned = false; /* source is a partitioned parent */
char *partition_ddl = NULL; /* CREATE TABLE ... PARTITION OF ... */
char *partkey_def = NULL; /* PARTITION BY clause body */

/* Arg 4: target table name (optional) */
if (PG_NARGS() >= 5 && !PG_ARGISNULL(4))
Expand Down Expand Up @@ -2582,6 +2602,41 @@ pgclone_table(PG_FUNCTION_ARGS)
schema_name, table_name)));
}

/* ---- Step 1a2: partitioning info (issue #38) ----
* A partitioned parent must be created with PARTITION BY and must
* not be COPYed from (COPY of a partitioned table is rejected);
* a partition must be created as PARTITION OF its parent so rows
* are routed correctly and are not loaded twice. */
{
PGresult *pres;

resetStringInfo(&buf);
appendStringInfo(&buf,
"SELECT c.relkind::text, "
" pg_catalog.pg_get_partkeydef(c.oid), "
" CASE WHEN c.relispartition THEN "
" 'PARTITION OF ' || pg_catalog.quote_ident(pn.nspname) || '.' || "
" pg_catalog.quote_ident(pc.relname) || ' ' || "
" pg_catalog.pg_get_expr(c.relpartbound, c.oid) END "
"FROM pg_catalog.pg_class c "
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid AND c.relispartition "
"LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent "
"LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace "
"WHERE n.nspname = %s AND c.relname = %s",
quote_literal_cstr(schema_name), quote_literal_cstr(table_name));
pres = pgclone_exec(source_conn, buf.data);
if (PQntuples(pres) == 1)
{
is_partitioned = (strcmp(PQgetvalue(pres, 0, 0), "p") == 0);
if (!PQgetisnull(pres, 0, 1))
partkey_def = pstrdup(PQgetvalue(pres, 0, 1));
if (!PQgetisnull(pres, 0, 2))
partition_ddl = pstrdup(PQgetvalue(pres, 0, 2));
}
PQclear(pres);
}

/* Use loopback libpq connection for ALL local operations */
local_conn = pgclone_connect_local();

Expand Down Expand Up @@ -2674,7 +2729,22 @@ pgclone_table(PG_FUNCTION_ARGS)
PGresult *local_res;
char *ddl;

ddl = pstrdup(PQgetvalue(res, 0, 0));
if (partition_ddl != NULL)
{
/* Partition: columns come from the parent. A sub-partitioned
* partition also carries its own PARTITION BY. */
ddl = psprintf("CREATE TABLE IF NOT EXISTS %s.%s %s%s%s",
quote_identifier(schema_name),
quote_identifier(target_name),
partition_ddl,
partkey_def ? " PARTITION BY " : "",
partkey_def ? partkey_def : "");
}
else if (partkey_def != NULL)
ddl = psprintf("%s PARTITION BY %s",
PQgetvalue(res, 0, 0), partkey_def);
else
ddl = pstrdup(PQgetvalue(res, 0, 0));
PQclear(res);

local_res = PQexec(local_conn, ddl);
Expand All @@ -2695,6 +2765,11 @@ pgclone_table(PG_FUNCTION_ARGS)
pfree(ddl);
}

/* A partitioned parent holds no rows of its own; its partitions are
* cloned (and copied) individually. COPY of the parent is rejected. */
if (is_partitioned)
include_data = false;

/* ---- Step 3: Copy data if requested ---- */
if (include_data)
{
Expand Down Expand Up @@ -3166,7 +3241,10 @@ pgclone_schema(PG_FUNCTION_ARGS)
quote_literal_cstr(anchored));
pfree(anchored);
}
appendStringInfoString(&buf, " ORDER BY tablename");
/* Partitioned parents must exist before their partitions
* (CREATE TABLE ... PARTITION OF), so order by inheritance depth
* first, then name (issue #38). */
appendStringInfoString(&buf, " ORDER BY " PGCLONE_TABLE_DEPTH_SQL ", tablename");

res = pgclone_exec(source_conn, buf.data);

Expand Down Expand Up @@ -5909,7 +5987,7 @@ pgclone_schema_async(PG_FUNCTION_ARGS)
initStringInfo(&qbuf);
appendStringInfo(&qbuf,
"SELECT tablename FROM pg_catalog.pg_tables "
"WHERE schemaname = %s ORDER BY tablename",
"WHERE schemaname = %s ORDER BY " PGCLONE_TABLE_DEPTH_SQL ", tablename",
quote_literal_cstr(schema_name));

table_res = pgclone_exec(source_conn, qbuf.data);
Expand Down
151 changes: 144 additions & 7 deletions src/pgclone_bgw.c
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,93 @@ bgw_sync_table_sequences(PGconn *source_conn, PGconn *local_conn,
pfree(q.data);
}

/* ---------------------------------------------------------------
* Helper: partitioning info for a source table (issue #38).
* *is_partitioned true for a partitioned parent (no rows of its own)
* *partkey_def palloc'd "RANGE (d)" etc. for a partitioned table
* *partition_of palloc'd "PARTITION OF s.parent FOR VALUES ..." when
* the table is itself a partition
* *parent_qual palloc'd quoted "s.parent" when a partition
* --------------------------------------------------------------- */
static void
bgw_partition_info(PGconn *source_conn, const char *schema_name,
const char *table_name, bool *is_partitioned,
char **partkey_def, char **partition_of, char **parent_qual)
{
PGresult *pres;
StringInfoData q;

*is_partitioned = false;
*partkey_def = NULL;
*partition_of = NULL;
*parent_qual = NULL;

initStringInfo(&q);
appendStringInfo(&q,
"SELECT c.relkind::text, "
" pg_catalog.pg_get_partkeydef(c.oid), "
" CASE WHEN c.relispartition THEN "
" 'PARTITION OF ' || pg_catalog.quote_ident(pn.nspname) || '.' || "
" pg_catalog.quote_ident(pc.relname) || ' ' || "
" pg_catalog.pg_get_expr(c.relpartbound, c.oid) END, "
" CASE WHEN c.relispartition THEN "
" pg_catalog.quote_ident(pn.nspname) || '.' || "
" pg_catalog.quote_ident(pc.relname) END "
"FROM pg_catalog.pg_class c "
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid AND c.relispartition "
"LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent "
"LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace "
"WHERE n.nspname = %s AND c.relname = %s",
quote_literal_cstr(schema_name), quote_literal_cstr(table_name));

pres = PQexec(source_conn, q.data);
if (PQresultStatus(pres) == PGRES_TUPLES_OK && PQntuples(pres) == 1)
{
*is_partitioned = (strcmp(PQgetvalue(pres, 0, 0), "p") == 0);
if (!PQgetisnull(pres, 0, 1))
*partkey_def = pstrdup(PQgetvalue(pres, 0, 1));
if (!PQgetisnull(pres, 0, 2))
*partition_of = pstrdup(PQgetvalue(pres, 0, 2));
if (!PQgetisnull(pres, 0, 3))
*parent_qual = pstrdup(PQgetvalue(pres, 0, 3));
}
PQclear(pres);
pfree(q.data);
}

/* ---------------------------------------------------------------
* Helper: wait (up to ~60 s) for a partition's parent to exist on the
* target. In a parallel pool the parent is created by another worker.
* --------------------------------------------------------------- */
static bool
bgw_wait_for_parent(PGconn *local_conn, const char *parent_qual)
{
StringInfoData q;
int attempt;
bool found = false;

initStringInfo(&q);
appendStringInfo(&q, "SELECT to_regclass(%s) IS NOT NULL",
quote_literal_cstr(parent_qual));
for (attempt = 0; attempt < 300 && !found; attempt++)
{
PGresult *r = PQexec(local_conn, q.data);

found = (PQresultStatus(r) == PGRES_TUPLES_OK &&
PQntuples(r) == 1 &&
strcmp(PQgetvalue(r, 0, 0), "t") == 0);
PQclear(r);
if (!found)
{
PGCLONE_CHECK_SHUTDOWN();
pg_usleep(200000L);
}
}
pfree(q.data);
return found;
}

/* ---------------------------------------------------------------
* Helper: clone a single table (used by bgworker)
* --------------------------------------------------------------- */
Expand All @@ -774,6 +861,10 @@ bgw_clone_one_table(PGconn *source_conn, PGconn *local_conn,
const char *target;
int64 rows;
bool ddl_exists = false;
bool is_partitioned = false;
char *partkey_def = NULL;
char *partition_of = NULL;
char *parent_qual = NULL;

/* Use target_name if set and different from source table */
if (job->target_name[0] != '\0' && strcmp(job->target_name, table_name) != 0)
Expand Down Expand Up @@ -819,6 +910,9 @@ bgw_clone_one_table(PGconn *source_conn, PGconn *local_conn,
"GROUP BY c.relname",
job->schema_name, target, job->schema_name, table_name);

bgw_partition_info(source_conn, job->schema_name, table_name,
&is_partitioned, &partkey_def, &partition_of, &parent_qual);

if (!ddl_exists)
{
bgw_precreate_table_sequences(source_conn, local_conn,
Expand All @@ -832,13 +926,42 @@ bgw_clone_one_table(PGconn *source_conn, PGconn *local_conn,
return false;
}

bgw_exec(local_conn, PQgetvalue(res, 0, 0));
if (partition_of != NULL)
{
/* Partition: columns come from the parent, which another
* worker may still be creating. */
if (parent_qual != NULL && !bgw_wait_for_parent(local_conn, parent_qual))
{
elog(WARNING, "pgclone bgw: parent %s of partition %s.%s was not created in time",
parent_qual, job->schema_name, table_name);
PQclear(res);
pfree(buf.data);
return false;
}
resetStringInfo(&buf);
appendStringInfo(&buf, "CREATE TABLE IF NOT EXISTS %s.%s %s%s%s",
quote_identifier(job->schema_name),
quote_identifier(target),
partition_of,
partkey_def ? " PARTITION BY " : "",
partkey_def ? partkey_def : "");
bgw_exec(local_conn, buf.data);
}
else if (partkey_def != NULL)
{
resetStringInfo(&buf);
appendStringInfo(&buf, "%s PARTITION BY %s",
PQgetvalue(res, 0, 0), partkey_def);
bgw_exec(local_conn, buf.data);
}
else
bgw_exec(local_conn, PQgetvalue(res, 0, 0));
PQclear(res);
}


/* Copy data */
if (job->include_data)
/* Copy data (a partitioned parent has no rows of its own) */
if (job->include_data && !is_partitioned)
{
LWLockAcquire(pgclone_state->lock, LW_EXCLUSIVE);
strlcpy(job->current_phase, "copying data", 64);
Expand Down Expand Up @@ -872,6 +995,7 @@ bgw_clone_one_table(PGconn *source_conn, PGconn *local_conn,
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"WHERE n.nspname = '%s' AND c.relname = '%s' "
"AND con.contype != 'n' "
"AND con.conparentid = 0 "
"ORDER BY CASE contype WHEN 'p' THEN 1 WHEN 'u' THEN 2 "
"WHEN 'c' THEN 3 WHEN 'f' THEN 4 ELSE 5 END",
job->schema_name, table_name);
Expand Down Expand Up @@ -909,15 +1033,27 @@ bgw_clone_one_table(PGconn *source_conn, PGconn *local_conn,
"WHERE n.nspname = '%s' AND c.relname = '%s' "
"AND NOT i.indisprimary "
"AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_constraint con "
"WHERE con.conindid = i.indexrelid)",
"WHERE con.conindid = i.indexrelid) "
"AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_inherits ih "
"WHERE ih.inhrelid = i.indexrelid)",
job->schema_name, table_name);

res = PQexec(source_conn, buf.data);
if (PQresultStatus(res) == PGRES_TUPLES_OK)
{
int ii;
for (ii = 0; ii < PQntuples(res); ii++)
bgw_exec(local_conn, PQgetvalue(res, ii, 0));
{
char *idxdef = pstrdup(PQgetvalue(res, ii, 0));
char *only = strstr(idxdef, " ON ONLY ");

/* index on a partitioned parent: drop ONLY so it is
* inherited by every partition */
if (only != NULL)
memmove(only + 4, only + 9, strlen(only + 9) + 1);
bgw_exec(local_conn, idxdef);
pfree(idxdef);
}
}
PQclear(res);
}
Expand All @@ -936,7 +1072,8 @@ bgw_clone_one_table(PGconn *source_conn, PGconn *local_conn,
"JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid "
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"WHERE n.nspname = '%s' AND c.relname = '%s' "
"AND NOT t.tgisinternal",
"AND NOT t.tgisinternal "
"AND t.tgparentid = 0",
job->schema_name, table_name);

res = PQexec(source_conn, buf.data);
Expand Down Expand Up @@ -1286,7 +1423,7 @@ pgclone_bgw_main(Datum main_arg)
resetStringInfo(&buf);
appendStringInfo(&buf,
"SELECT tablename FROM pg_catalog.pg_tables "
"WHERE schemaname = '%s' ORDER BY tablename",
"WHERE schemaname = '%s' ORDER BY " PGCLONE_TABLE_DEPTH_SQL ", tablename",
job->schema_name);

table_res = PQexec(source_conn, buf.data);
Expand Down
Loading
Loading