@ultimat3/db 30.9.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +17 -9
- package/README.md +71 -22
- package/package.json +3 -2
- package/src/adapter.ts +9 -0
- package/src/attribution.ts +8 -9
- package/src/branch-errors.ts +24 -0
- package/src/branch.ts +2 -1
- package/src/check-ddl.ts +2 -2
- package/src/client.ts +7 -1
- package/src/db-diagnostics.ts +15 -4
- package/src/entity-shape.ts +20 -0
- package/src/errors.ts +4 -22
- package/src/expected-loop.ts +3 -3
- package/src/generate-partition-run.ts +97 -0
- package/src/generate-partition.ts +190 -0
- package/src/generate-snapshot.ts +9 -0
- package/src/generate.ts +6 -1
- package/src/index.ts +30 -99
- package/src/introspect.ts +23 -16
- package/src/invariant-ddl.ts +11 -10
- package/src/keyset.ts +26 -1
- package/src/pglite-branch.ts +2 -1
- package/src/pglite.ts +22 -55
- package/src/pool-sweep.ts +2 -3
- package/src/primary-key.ts +1 -2
- package/src/readonly-role.ts +41 -1
- package/src/same-tenant.ts +1 -1
- package/src/snapshot-parse.ts +12 -0
- package/src/sql.ts +21 -3
- package/src/statement-cancel.ts +86 -0
- package/src/statement-funnel.ts +8 -53
- package/src/statement-shape.ts +5 -3
- package/src/statement-span.ts +74 -18
- package/src/observe.ts +0 -90
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Single responsibility: one partitioned table's maintenance, run — create ahead under a bounded
|
|
2
|
+
// `lock_timeout`, then retire each expired partition without blocking the parent: mark it, `detach
|
|
3
|
+
// … concurrently` (outside any transaction, as Postgres requires), drop it. A `55P03` is
|
|
4
|
+
// `X_DB_LOCK_TIMEOUT`, retryable: the caller's retry absorbs a long report query, never the table.
|
|
5
|
+
|
|
6
|
+
import { finiteCount } from '@ultimat3/core';
|
|
7
|
+
import type { DbClient } from './client';
|
|
8
|
+
import type { EntityDescriptionLike } from './entity-shape';
|
|
9
|
+
import {
|
|
10
|
+
type PartitionMaintenanceOptions,
|
|
11
|
+
partitionMaintenance,
|
|
12
|
+
RETIRING_COMMENT,
|
|
13
|
+
} from './generate-partition';
|
|
14
|
+
import { identifier, literal, raw } from './sql';
|
|
15
|
+
import { withTransaction } from './transaction';
|
|
16
|
+
import type { DbTx } from './transaction-options';
|
|
17
|
+
|
|
18
|
+
/** How long one maintenance statement waits for a lock on the parent before giving up. */
|
|
19
|
+
export const PARTITION_LOCK_TIMEOUT_MS = 5000;
|
|
20
|
+
|
|
21
|
+
export interface PartitionRunOptions extends PartitionMaintenanceOptions {
|
|
22
|
+
readonly lockTimeoutMs?: number | undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface PartitionRun {
|
|
26
|
+
readonly created: readonly string[];
|
|
27
|
+
readonly dropped: readonly string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type Expired = { readonly name: string; readonly state: 'attached' | 'pending' | 'detached' };
|
|
31
|
+
const RETIREMENT_STATES: readonly string[] = ['attached', 'pending', 'detached'];
|
|
32
|
+
|
|
33
|
+
const names = (value: unknown): readonly string[] =>
|
|
34
|
+
Array.isArray(value) ? value.filter((each): each is string => typeof each === 'string') : [];
|
|
35
|
+
|
|
36
|
+
const expiredOf = (value: unknown): readonly Expired[] =>
|
|
37
|
+
(Array.isArray(value) ? value : []).flatMap((each: unknown): Expired[] => {
|
|
38
|
+
if (typeof each !== 'object' || each === null) return [];
|
|
39
|
+
const { name, state: stage } = each as Record<string, unknown>;
|
|
40
|
+
return typeof name === 'string' &&
|
|
41
|
+
typeof stage === 'string' &&
|
|
42
|
+
RETIREMENT_STATES.includes(stage)
|
|
43
|
+
? [{ name, state: stage as Expired['state'] }]
|
|
44
|
+
: [];
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/** One transaction whose every lock wait is bounded: a blocked DDL fails fast, the table keeps serving. */
|
|
48
|
+
const bounded = <T>(client: DbClient, ms: number, work: (tx: DbTx) => Promise<T>): Promise<T> =>
|
|
49
|
+
withTransaction(
|
|
50
|
+
async (tx) => {
|
|
51
|
+
await tx.execute(raw(`set local lock_timeout = ${ms}`));
|
|
52
|
+
return work(tx);
|
|
53
|
+
},
|
|
54
|
+
{ client },
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Creates what `partitionBy` (and `from`) need, then retires each expired partition, resuming a
|
|
59
|
+
* run that died anywhere in between: a `pending` detach is finalized, a `detached` one is dropped.
|
|
60
|
+
* Never inside a caller's transaction — `detach … concurrently` refuses one (`25001`).
|
|
61
|
+
*/
|
|
62
|
+
export async function maintainPartitions(
|
|
63
|
+
client: DbClient,
|
|
64
|
+
entity: EntityDescriptionLike,
|
|
65
|
+
instant: Date,
|
|
66
|
+
options: PartitionRunOptions = {},
|
|
67
|
+
): Promise<PartitionRun> {
|
|
68
|
+
const statement = partitionMaintenance(entity, instant, options);
|
|
69
|
+
if (statement === null) return { created: [], dropped: [] };
|
|
70
|
+
const ms = finiteCount(
|
|
71
|
+
'maintainPartitions',
|
|
72
|
+
'lockTimeoutMs',
|
|
73
|
+
options.lockTimeoutMs ?? PARTITION_LOCK_TIMEOUT_MS,
|
|
74
|
+
1,
|
|
75
|
+
);
|
|
76
|
+
const [row] = await bounded(client, ms, (tx) => tx.query<{ result: unknown }>(statement));
|
|
77
|
+
const result =
|
|
78
|
+
typeof row?.result === 'object' && row.result !== null
|
|
79
|
+
? (row.result as Record<string, unknown>)
|
|
80
|
+
: {};
|
|
81
|
+
const parent = identifier(entity.table).text;
|
|
82
|
+
const dropped: string[] = [];
|
|
83
|
+
for (const { name, state } of expiredOf(result['expired'])) {
|
|
84
|
+
const child = identifier(name).text;
|
|
85
|
+
if (state === 'attached') {
|
|
86
|
+
await bounded(client, ms, (tx) =>
|
|
87
|
+
tx.execute(raw(`comment on table ${child} is ${literal(RETIRING_COMMENT).text}`)),
|
|
88
|
+
);
|
|
89
|
+
await client.execute(raw(`alter table ${parent} detach partition ${child} concurrently`));
|
|
90
|
+
} else if (state === 'pending') {
|
|
91
|
+
await client.execute(raw(`alter table ${parent} detach partition ${child} finalize`));
|
|
92
|
+
}
|
|
93
|
+
await bounded(client, ms, (tx) => tx.execute(raw(`drop table if exists ${child}`)));
|
|
94
|
+
dropped.push(name);
|
|
95
|
+
}
|
|
96
|
+
return { created: names(result['created']), dropped };
|
|
97
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// Single responsibility: `entity({ partitionBy })` as SQL — the parent's `partition by range`
|
|
2
|
+
// clause and the ONE plpgsql function that creates the partitions ahead and drops expired ones. The
|
|
3
|
+
// migration creating the table and the maintenance job both call it, so both name and bound a
|
|
4
|
+
// partition identically, and both read the database's clock unless handed one.
|
|
5
|
+
|
|
6
|
+
import { renderFixShellArg } from '@ultimat3/core';
|
|
7
|
+
import type { EntityDescriptionLike, PartitionDescriptionLike } from './entity-shape';
|
|
8
|
+
import { DbError } from './errors';
|
|
9
|
+
import { findTable, type SchemaDescription } from './introspect';
|
|
10
|
+
import { identifier, literal, raw, type SqlFragment, sql } from './sql';
|
|
11
|
+
|
|
12
|
+
/** The column kinds a range can be bounded by: `timestamp()` and `date()`. */
|
|
13
|
+
export const PARTITION_KINDS = ['timestamptz', 'date'] as const;
|
|
14
|
+
|
|
15
|
+
/** `_p20261101`: the suffix every partition carries — its lower bound, UTC, `YYYYMMDD`. */
|
|
16
|
+
export const PARTITION_SUFFIX_BYTES = 10;
|
|
17
|
+
|
|
18
|
+
export const PARTITION_FUNCTION = 'ultimate_partitions';
|
|
19
|
+
|
|
20
|
+
/** A bound, spelled independently of `DateStyle` and `TimeZone`: UTC, ISO. */
|
|
21
|
+
const bound = (at: string): string =>
|
|
22
|
+
`case when kind = 'date' then to_char(${at}, 'YYYY-MM-DD') ` +
|
|
23
|
+
`else to_char(${at}, 'YYYY-MM-DD HH24:MI:SS') || '+00' end`;
|
|
24
|
+
|
|
25
|
+
/** What a retiring partition's comment says, so a detached orphan is known to be this package's. */
|
|
26
|
+
export const RETIRING_COMMENT = 'ultimate:partition-retiring';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Creates every partition from `since`'s (the current one when `since` is null) through `ahead`
|
|
30
|
+
* past the current one (`if not exists`, so a double fire is a no-op). With `keep_ms`, it also
|
|
31
|
+
* NAMES — never touches — every `<parent>_pYYYYMMDD` whose upper bound is `keep_ms` before
|
|
32
|
+
* `instant`, with its state: `attached`, `pending` (a `detach … concurrently` interrupted) or
|
|
33
|
+
* `detached` (detached by a run that died before its drop, known by `RETIRING_COMMENT`). The caller
|
|
34
|
+
* retires them outside any transaction (`generate-partition-run.ts`): `detach … concurrently`
|
|
35
|
+
* cannot run inside a function. Refuses a parent that is not partitioned with this package's code.
|
|
36
|
+
* Answers `{ created, expired: [{ name, state }] }`.
|
|
37
|
+
*/
|
|
38
|
+
export const PARTITION_FUNCTION_SQL =
|
|
39
|
+
`create or replace function ${identifier(PARTITION_FUNCTION).text}(parent text, kind text, ` +
|
|
40
|
+
'unit text, ahead integer, keep_ms bigint, instant timestamptz default now(), ' +
|
|
41
|
+
'since timestamptz default null) returns jsonb ' +
|
|
42
|
+
'language plpgsql as $partitions$ declare ' +
|
|
43
|
+
"step interval := ('1 ' || unit)::interval; " +
|
|
44
|
+
"head timestamp := date_trunc(unit, instant at time zone 'UTC'); " +
|
|
45
|
+
'low timestamp; part text; child record; ' +
|
|
46
|
+
"created text[] := '{}'; expired jsonb := '[]'; " +
|
|
47
|
+
'begin ' +
|
|
48
|
+
'if (select c.relkind from pg_class c where c.oid = to_regclass(quote_ident(parent))) ' +
|
|
49
|
+
"is distinct from 'p' then raise exception 'X_MIGRATION_PARTITION_CHANGE: table % is not " +
|
|
50
|
+
"partitioned, and its entity declares partitionBy', parent using errcode = '42809', " +
|
|
51
|
+
"hint = 'Postgres cannot partition a table in place: declare a new entity with partitionBy, " +
|
|
52
|
+
"run partitions() with from: <its oldest row>, then backfill() it'; end if; " +
|
|
53
|
+
"low := least(head, coalesce(date_trunc(unit, since at time zone 'UTC'), head)); " +
|
|
54
|
+
'while low <= head + step * ahead loop ' +
|
|
55
|
+
"part := parent || '_p' || to_char(low, 'YYYYMMDD'); " +
|
|
56
|
+
'if to_regclass(quote_ident(part)) is null then ' +
|
|
57
|
+
"execute format('create table if not exists %I partition of %I for values from (%L) to (%L)', " +
|
|
58
|
+
`part, parent, ${bound('low')}, ${bound('low + step')}); ` +
|
|
59
|
+
'created := created || part; end if; low := low + step; end loop; ' +
|
|
60
|
+
'if keep_ms is not null then ' +
|
|
61
|
+
'for child in select c.relname::text as name, case when h.inhrelid is null then ' +
|
|
62
|
+
"'detached' when h.inhdetachpending then 'pending' else 'attached' end as state " +
|
|
63
|
+
'from pg_class c left join pg_inherits h on h.inhrelid = c.oid ' +
|
|
64
|
+
'and h.inhparent = to_regclass(quote_ident(parent)) ' +
|
|
65
|
+
"where c.relkind = 'r' and c.relnamespace = (select p.relnamespace from pg_class p " +
|
|
66
|
+
'where p.oid = to_regclass(quote_ident(parent))) ' +
|
|
67
|
+
`and length(c.relname) = length(parent) + ${PARTITION_SUFFIX_BYTES} ` +
|
|
68
|
+
"and left(c.relname, length(parent) + 2) = parent || '_p' " +
|
|
69
|
+
"and right(c.relname, 8) ~ '^[0-9]{8}$' " +
|
|
70
|
+
'and (h.inhrelid is not null or (not c.relispartition and ' +
|
|
71
|
+
`obj_description(c.oid, 'pg_class') = '${RETIRING_COMMENT}')) order by c.relname loop ` +
|
|
72
|
+
"if to_date(right(child.name, 8), 'YYYYMMDD')::timestamp + step <= " +
|
|
73
|
+
"(instant at time zone 'UTC') - make_interval(secs => keep_ms / 1000.0) then " +
|
|
74
|
+
"expired := expired || jsonb_build_object('name', child.name, 'state', child.state); " +
|
|
75
|
+
'end if; end loop; end if; ' +
|
|
76
|
+
"return jsonb_build_object('created', to_jsonb(created), 'expired', expired); " +
|
|
77
|
+
'end; $partitions$;';
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The function's first signature, before `since` existed: `create or replace` with another argument
|
|
81
|
+
* list makes an OVERLOAD, and a call naming five arguments then matches both (`42725`).
|
|
82
|
+
*/
|
|
83
|
+
export const PARTITION_FUNCTION_RETIRED_SQL =
|
|
84
|
+
`drop function if exists ${identifier(PARTITION_FUNCTION).text}` +
|
|
85
|
+
'(text, text, text, integer, bigint, timestamptz);';
|
|
86
|
+
|
|
87
|
+
/** ` partition by range ("at")` — appended to the parent's `create table (…)`. */
|
|
88
|
+
export const partitionByClause = (partition: PartitionDescriptionLike): string =>
|
|
89
|
+
` partition by range (${identifier(partition.column).text})`;
|
|
90
|
+
|
|
91
|
+
/** The partition column's kind, read off the description's own column. */
|
|
92
|
+
const kindOf = (entity: EntityDescriptionLike, partition: PartitionDescriptionLike): string =>
|
|
93
|
+
entity.columns.find((column) => column.column === partition.column)?.kind ?? 'timestamptz';
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The migration's call: partitions from the APPLY time onward, never a retention sweep — a
|
|
97
|
+
* migration replayed a year later (a fresh clone, a test database) still has this month's.
|
|
98
|
+
*/
|
|
99
|
+
export function partitionMigrationCall(entity: EntityDescriptionLike): string | null {
|
|
100
|
+
const partition = entity.partition;
|
|
101
|
+
if (partition === undefined) return null;
|
|
102
|
+
const args = [
|
|
103
|
+
literal(entity.table).text,
|
|
104
|
+
literal(kindOf(entity, partition)).text,
|
|
105
|
+
literal(partition.interval).text,
|
|
106
|
+
String(Math.trunc(partition.ahead)),
|
|
107
|
+
'null',
|
|
108
|
+
].join(', ');
|
|
109
|
+
return `select ${identifier(PARTITION_FUNCTION).text}(${args});`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** `from`: also create every partition back to this instant's — before a `backfill()` copies old rows. */
|
|
113
|
+
export interface PartitionMaintenanceOptions {
|
|
114
|
+
readonly from?: Date | undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The maintenance statement: create ahead, and name what `retain` expired (retired by
|
|
119
|
+
* `maintainPartitions`, never here), judged at `instant` — the framework clock's now, never the server's, so a test can move it.
|
|
120
|
+
* With `from`, it also creates every partition back to `from`'s and sweeps NOTHING: a backfill's
|
|
121
|
+
* preparation must not drop the partitions it just made for rows older than the window.
|
|
122
|
+
* Answers one row, `{ result: { created, expired } }`. `null` on a plain table.
|
|
123
|
+
*/
|
|
124
|
+
export function partitionMaintenance(
|
|
125
|
+
entity: EntityDescriptionLike,
|
|
126
|
+
instant: Date,
|
|
127
|
+
options: PartitionMaintenanceOptions = {},
|
|
128
|
+
): SqlFragment | null {
|
|
129
|
+
const partition = entity.partition;
|
|
130
|
+
if (partition === undefined) return null;
|
|
131
|
+
const from = options.from === undefined ? null : options.from.toISOString();
|
|
132
|
+
const keep =
|
|
133
|
+
partition.retain === undefined || from !== null ? null : Math.trunc(partition.retain.afterMs);
|
|
134
|
+
return sql`select ${raw(identifier(PARTITION_FUNCTION).text)}(${entity.table}, ${kindOf(entity, partition)}, ${partition.interval}, ${Math.trunc(partition.ahead)}::integer, ${keep}::bigint, ${instant.toISOString()}::timestamptz, ${from}::timestamptz) as result`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* A NEW partitioned table gets the function and its first partitions; an existing one that newly
|
|
139
|
+
* declares `partitionBy` gets them too — if the hand-edit recipe already partitioned it, that is
|
|
140
|
+
* adoption, and if it is a plain table the function refuses it at migrate time with
|
|
141
|
+
* `X_MIGRATION_PARTITION_CHANGE`. A table the snapshot records partitioned and the entity no
|
|
142
|
+
* longer declares is refused here: no statement turns it back.
|
|
143
|
+
*/
|
|
144
|
+
export function partitionPlan(
|
|
145
|
+
plan: { up: string[] },
|
|
146
|
+
entities: readonly EntityDescriptionLike[],
|
|
147
|
+
current: SchemaDescription,
|
|
148
|
+
): void {
|
|
149
|
+
let installed = false;
|
|
150
|
+
for (const entity of entities) {
|
|
151
|
+
const recorded = findTable(current, entity.table);
|
|
152
|
+
const call = partitionMigrationCall(entity);
|
|
153
|
+
if (call === null) {
|
|
154
|
+
if (recorded?.partitioned === true) throw partitionDropped(entity.name, entity.table);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const was = recorded?.partitionInterval;
|
|
158
|
+
const now = entity.partition?.interval;
|
|
159
|
+
if (was !== undefined && now !== undefined && was !== now) {
|
|
160
|
+
throw partitionRewidened(entity.name, entity.table, was, now);
|
|
161
|
+
}
|
|
162
|
+
if (recorded?.partitioned === true) continue;
|
|
163
|
+
if (!installed) plan.up.push(PARTITION_FUNCTION_RETIRED_SQL, PARTITION_FUNCTION_SQL);
|
|
164
|
+
installed = true;
|
|
165
|
+
plan.up.push(call);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** An existing partitioned table losing `partitionBy`: no in-place statement does it. */
|
|
170
|
+
export const partitionDropped = (entity: string, table: string): DbError =>
|
|
171
|
+
new DbError({
|
|
172
|
+
code: 'X_MIGRATION_PARTITION_CHANGE',
|
|
173
|
+
cause: `entity "${entity}" no longer declares partitionBy, and its table "${table}" was created partitioned: Postgres cannot turn it back into a plain table in place`,
|
|
174
|
+
fix: `x db gen "unpartition" # after putting partitionBy back on entity('${renderFixShellArg(entity, '<entity>')}'), or moving its rows to a new plain entity with backfill()`,
|
|
175
|
+
meta: { entity, table },
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
/** A partitioned table's interval changing: partitions of the new width would overlap the old. */
|
|
179
|
+
export const partitionRewidened = (
|
|
180
|
+
entity: string,
|
|
181
|
+
table: string,
|
|
182
|
+
was: string,
|
|
183
|
+
now: string,
|
|
184
|
+
): DbError =>
|
|
185
|
+
new DbError({
|
|
186
|
+
code: 'X_MIGRATION_PARTITION_CHANGE',
|
|
187
|
+
cause: `entity "${entity}" changes its partition interval from ${was} to ${now}, and "${table}" already holds ${was} partitions: Postgres cannot repartition in place, and new ones would overlap`,
|
|
188
|
+
fix: `x db gen "repartition" # after putting interval: '${was}' back on entity('${renderFixShellArg(entity, '<entity>')}'), or declaring a new entity with interval: '${now}', running partitions() with { from: <oldest row's instant> }, then backfill() into it`,
|
|
189
|
+
meta: { entity, table },
|
|
190
|
+
});
|
package/src/generate-snapshot.ts
CHANGED
|
@@ -22,6 +22,11 @@ export function snapshotOf(
|
|
|
22
22
|
): SchemaDescription {
|
|
23
23
|
// A view is recorded as its statements (`generate-view.ts`), never as a table it is not.
|
|
24
24
|
const split = splitViews(entities);
|
|
25
|
+
const partitioned = new Map(
|
|
26
|
+
entities.flatMap((entity) =>
|
|
27
|
+
entity.partition === undefined ? [] : [[entity.table, entity.partition.interval] as const],
|
|
28
|
+
),
|
|
29
|
+
);
|
|
25
30
|
const tables = [...withSameTenantIndexes(split.tables)]
|
|
26
31
|
.sort((a, b) => (a.table < b.table ? -1 : 1))
|
|
27
32
|
.map((entity): TableDescription => {
|
|
@@ -73,6 +78,10 @@ export function snapshotOf(
|
|
|
73
78
|
...(entity.appendOnly === true ? { appendOnly: true as const } : {}),
|
|
74
79
|
// And again: the record that makes the tenant policy a one-time statement.
|
|
75
80
|
...(rowSecurity.has(entity.table) ? { rowSecurity: true as const } : {}),
|
|
81
|
+
// `entity({ partitionBy })`: the record the next `x db gen` refuses its removal against.
|
|
82
|
+
...(partitioned.has(entity.table)
|
|
83
|
+
? { partitioned: true as const, partitionInterval: partitioned.get(entity.table) }
|
|
84
|
+
: {}),
|
|
76
85
|
};
|
|
77
86
|
});
|
|
78
87
|
// `views` absent when none is declared, so no snapshot written before views existed moves.
|
package/src/generate.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { dropOrder } from './drop-order';
|
|
|
12
12
|
import type { ColumnDescriptionLike, EntityDescriptionLike } from './entity-shape';
|
|
13
13
|
import { type ConstraintPlans, foreignKeyPlan, type Plan } from './foreign-key-plan';
|
|
14
14
|
import { appendOnlyBackfillRefused, appendOnlyPlan } from './generate-append-only';
|
|
15
|
+
import { partitionByClause, partitionPlan } from './generate-partition';
|
|
15
16
|
import { type RowSecurityOption, rowSecurityInput } from './generate-row-security';
|
|
16
17
|
import { snapshotOf } from './generate-snapshot';
|
|
17
18
|
import { assembleSteps } from './generate-steps';
|
|
@@ -76,8 +77,9 @@ function createTable(entity: EntityDescriptionLike): readonly string[] {
|
|
|
76
77
|
}
|
|
77
78
|
// After the key, so a table declaring no invariant emits the statement it always emitted.
|
|
78
79
|
clauses.push(...checkClauses(entity));
|
|
80
|
+
const by = entity.partition === undefined ? '' : partitionByClause(entity.partition);
|
|
79
81
|
const statements = [
|
|
80
|
-
`create table ${identifier(entity.table).text} (\n ${clauses.join(',\n ')}\n);`,
|
|
82
|
+
`create table ${identifier(entity.table).text} (\n ${clauses.join(',\n ')}\n)${by};`,
|
|
81
83
|
];
|
|
82
84
|
// Every column of a new table carries its own clause, so every `unique` one brings its index.
|
|
83
85
|
const added = new Set(entity.columns.map((column) => column.column));
|
|
@@ -205,6 +207,7 @@ function diffTable(
|
|
|
205
207
|
export { snapshotOf } from './generate-snapshot';
|
|
206
208
|
|
|
207
209
|
export interface GenerateOptions {
|
|
210
|
+
/** `partition` rides on the description when `entity({ partitionBy })` declares one. */
|
|
208
211
|
readonly entities: readonly EntityDescriptionLike[];
|
|
209
212
|
/** The schema migrations already declare — `expectedSchema(migrations, ledger)`. */
|
|
210
213
|
readonly current?: SchemaDescription | undefined;
|
|
@@ -405,6 +408,8 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
|
|
|
405
408
|
appendOnlyPlan(plan, options.entities, current, created);
|
|
406
409
|
// History, its guard and counters, the same way: after every table they name exists.
|
|
407
410
|
triggerPlan(plan, options.entities, current);
|
|
411
|
+
// The partitions a new partitioned table starts with, after its indexes so each clones them.
|
|
412
|
+
partitionPlan(plan, options.entities, current);
|
|
408
413
|
// Then each tenant table's policy, both directions (`row-security-plan.ts`), on tables that exist.
|
|
409
414
|
const rowSecurity = rowSecurityInput(options.entities, current, options.rowSecurity);
|
|
410
415
|
rowSecurityPlan(plan, rowSecurity);
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// `@ultimat3/auth`, `@ultimat3/entity`, `@ultimat3/jobs` and the CLI are written against this
|
|
3
3
|
// list, so anything not here is an implementation detail and may change.
|
|
4
4
|
|
|
5
|
+
// The `db.statement` payload is core's (the bus is tier 0); re-exported, never a second shape.
|
|
6
|
+
export type { DbStatementEvent, StatementAttribution } from '@ultimat3/core';
|
|
5
7
|
export { statementAttribution, withStatementAttribution } from './attribution';
|
|
6
8
|
export type { BranchInfo, BranchOptions, DropBranchOptions, ReapOptions } from './branch';
|
|
7
9
|
export {
|
|
@@ -12,14 +14,8 @@ export {
|
|
|
12
14
|
listBranches,
|
|
13
15
|
reapBranches,
|
|
14
16
|
} from './branch';
|
|
15
|
-
export {
|
|
16
|
-
|
|
17
|
-
checkPlan,
|
|
18
|
-
columnCheckName,
|
|
19
|
-
columnChecks,
|
|
20
|
-
columnNamesConstraint,
|
|
21
|
-
declaredChecks,
|
|
22
|
-
} from './check-ddl';
|
|
17
|
+
export { branchNameInvalid } from './branch-errors';
|
|
18
|
+
export { checkPlan, columnChecks, declaredChecks } from './check-ddl';
|
|
23
19
|
export type {
|
|
24
20
|
DbClient,
|
|
25
21
|
DbConnection,
|
|
@@ -47,15 +43,9 @@ export {
|
|
|
47
43
|
export { dbExecutor } from './db-executor';
|
|
48
44
|
export type { DbHealthReport } from './db-health';
|
|
49
45
|
export { checkDb } from './db-health';
|
|
50
|
-
export {
|
|
51
|
-
generatedExpressionUnsafe,
|
|
52
|
-
indexOrderInvalid,
|
|
53
|
-
indexPredicateUnsafe,
|
|
54
|
-
} from './ddl-errors';
|
|
55
|
-
export { defaultClient, REPLICA_URL_ENV } from './default-client';
|
|
46
|
+
export { REPLICA_URL_ENV } from './default-client';
|
|
56
47
|
export type { DestructiveKind, DestructiveStatement } from './destructive';
|
|
57
48
|
export {
|
|
58
|
-
DESTRUCTIVE_CAUSE,
|
|
59
49
|
DESTRUCTIVE_MARKER,
|
|
60
50
|
destructiveStatements,
|
|
61
51
|
hasDestructiveMarker,
|
|
@@ -70,7 +60,6 @@ export {
|
|
|
70
60
|
diffSchema,
|
|
71
61
|
driftError,
|
|
72
62
|
expectedSchema,
|
|
73
|
-
FRAMEWORK_TABLE_PREFIX,
|
|
74
63
|
} from './drift';
|
|
75
64
|
export { dbDrift } from './drift-errors';
|
|
76
65
|
export type { RowSecurityDifference } from './drift-row-security';
|
|
@@ -82,12 +71,13 @@ export type {
|
|
|
82
71
|
HistoryDescriptionLike,
|
|
83
72
|
IndexDescriptionLike,
|
|
84
73
|
InvariantDescriptionLike,
|
|
74
|
+
PartitionDescriptionLike,
|
|
75
|
+
PartitionInterval,
|
|
85
76
|
RetainDescriptionLike,
|
|
86
77
|
} from './entity-shape';
|
|
78
|
+
export { PARTITION_INTERVALS } from './entity-shape';
|
|
87
79
|
export type { DbErrorCode, DbErrorInit } from './errors';
|
|
88
80
|
export {
|
|
89
|
-
branchExists,
|
|
90
|
-
branchNameInvalid,
|
|
91
81
|
DB_ERROR_CODES,
|
|
92
82
|
DB_ERROR_RETRY,
|
|
93
83
|
DB_ERROR_TITLES,
|
|
@@ -98,8 +88,6 @@ export {
|
|
|
98
88
|
multipleStatements,
|
|
99
89
|
poolAcquireTimeout,
|
|
100
90
|
poolMaxInvalid,
|
|
101
|
-
serializationExhausted,
|
|
102
|
-
sqlUnsafe,
|
|
103
91
|
} from './errors';
|
|
104
92
|
export {
|
|
105
93
|
expectedQueryLoop,
|
|
@@ -111,37 +99,22 @@ export type { FailureSummary, PostgresFailureStore } from './failure-store-pg';
|
|
|
111
99
|
export {
|
|
112
100
|
FAILURES_TABLE,
|
|
113
101
|
failurePurgeTarget,
|
|
114
|
-
MAX_FAILURE_LIST,
|
|
115
102
|
postgresFailureStore,
|
|
116
103
|
SQL_FAILURES_TABLE,
|
|
117
104
|
} from './failure-store-pg';
|
|
118
105
|
export type { RecordedStatement, RecordingClient, StubResponse } from './fake';
|
|
119
106
|
export { recordingClient } from './fake';
|
|
120
107
|
export type { GeneratedMigration, GenerateOptions } from './generate';
|
|
121
|
-
export { generateMigration,
|
|
122
|
-
export {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
} from './generate-
|
|
128
|
-
export {
|
|
129
|
-
ACTOR_SETTING,
|
|
130
|
-
HISTORY_GUARD_TRIGGER,
|
|
131
|
-
HISTORY_TRIGGER,
|
|
132
|
-
PURGE_SETTING,
|
|
133
|
-
REQUEST_SETTING,
|
|
134
|
-
} from './generate-history';
|
|
108
|
+
export { generateMigration, slugify, snapshotOf } from './generate';
|
|
109
|
+
export { recountDriftSql, recountSql } from './generate-counter';
|
|
110
|
+
export { ACTOR_SETTING, PURGE_SETTING, REQUEST_SETTING } from './generate-history';
|
|
111
|
+
export type { PartitionMaintenanceOptions } from './generate-partition';
|
|
112
|
+
export { partitionMaintenance } from './generate-partition';
|
|
113
|
+
export type { PartitionRun, PartitionRunOptions } from './generate-partition-run';
|
|
114
|
+
export { maintainPartitions, PARTITION_LOCK_TIMEOUT_MS } from './generate-partition-run';
|
|
135
115
|
export type { RowSecurityOption, TenantColumnLike } from './generate-row-security';
|
|
136
|
-
export { declaredTriggers } from './generate-triggers';
|
|
137
116
|
export type { IndexMethod } from './index-method';
|
|
138
|
-
export {
|
|
139
|
-
declaredMethod,
|
|
140
|
-
INDEX_METHODS,
|
|
141
|
-
indexMethodOf,
|
|
142
|
-
indexMethodSql,
|
|
143
|
-
isIndexMethod,
|
|
144
|
-
} from './index-method';
|
|
117
|
+
export { declaredMethod, INDEX_METHODS, indexMethodOf, indexMethodSql } from './index-method';
|
|
145
118
|
export type {
|
|
146
119
|
CheckDescription,
|
|
147
120
|
ColumnDescription,
|
|
@@ -153,21 +126,21 @@ export type {
|
|
|
153
126
|
TriggerRecord,
|
|
154
127
|
ViewDescription,
|
|
155
128
|
} from './introspect';
|
|
156
|
-
export {
|
|
129
|
+
export { introspectSchema } from './introspect';
|
|
157
130
|
export {
|
|
158
131
|
constraintNameFor,
|
|
159
132
|
declaredIndexes,
|
|
160
133
|
invariantChecks,
|
|
161
134
|
uniqueColumns,
|
|
162
135
|
} from './invariant-ddl';
|
|
163
|
-
export {
|
|
136
|
+
export { constraintNameUnsafe } from './invariant-errors';
|
|
164
137
|
export type { Keyset, KeysetKey, KeysetKind, KeysetOptions, KeysetRow } from './keyset';
|
|
165
138
|
export { keyset } from './keyset';
|
|
166
139
|
export { retainInvalid } from './lifecycle-errors';
|
|
167
140
|
export type { DbSubscription, ListeningClient } from './listen';
|
|
168
141
|
export { canListen } from './listen';
|
|
169
142
|
export type { LocalSettings } from './local-settings';
|
|
170
|
-
export {
|
|
143
|
+
export { setLocal } from './local-settings';
|
|
171
144
|
export type {
|
|
172
145
|
AppliedMigration,
|
|
173
146
|
LedgerRow,
|
|
@@ -193,18 +166,12 @@ export {
|
|
|
193
166
|
runningAppVersion,
|
|
194
167
|
} from './migrate';
|
|
195
168
|
export {
|
|
196
|
-
migrateConcurrent,
|
|
197
|
-
migrationConcurrentInTransaction,
|
|
198
169
|
migrationConcurrentPartitioned,
|
|
199
|
-
migrationConflict,
|
|
200
170
|
migrationDestructive,
|
|
201
171
|
migrationIrreversible,
|
|
202
172
|
migrationSnapshotMissing,
|
|
203
|
-
migrationViewDepends,
|
|
204
173
|
rollbackStepsInvalid,
|
|
205
174
|
} from './migration-errors';
|
|
206
|
-
export type { StatementAttribution, StatementEvent, StatementObserver } from './observe';
|
|
207
|
-
export { setStatementObserver, statementObserver } from './observe';
|
|
208
175
|
export type {
|
|
209
176
|
PgliteClient,
|
|
210
177
|
PgliteDriver,
|
|
@@ -214,7 +181,6 @@ export type {
|
|
|
214
181
|
PgliteResult,
|
|
215
182
|
} from './pglite';
|
|
216
183
|
export {
|
|
217
|
-
loadPgliteDriver,
|
|
218
184
|
PGLITE_FIX,
|
|
219
185
|
PGLITE_MEMORY,
|
|
220
186
|
PGLITE_MISSING,
|
|
@@ -246,26 +212,19 @@ export {
|
|
|
246
212
|
export type { ReadTransactionOptions } from './read-transaction';
|
|
247
213
|
export { withReadTransaction } from './read-transaction';
|
|
248
214
|
export type { ReadOnlyQueryOptions, ReadOnlyQueryResult } from './readonly-query';
|
|
249
|
-
export {
|
|
215
|
+
export { readOnlyQuery } from './readonly-query';
|
|
250
216
|
export type { ReadOnlyRoleOptions } from './readonly-role';
|
|
251
|
-
export { ensureReadOnlyRole,
|
|
217
|
+
export { ensureReadOnlyRole, READONLY_ROLE } from './readonly-role';
|
|
252
218
|
export type {
|
|
253
219
|
ReplicaStats,
|
|
254
220
|
ReplicatedClient,
|
|
255
221
|
ReplicatedClientOptions,
|
|
256
222
|
} from './replica-client';
|
|
257
223
|
export { BREAKER_COOLDOWN_MS, BREAKER_FAILURES, replicatedClient } from './replica-client';
|
|
258
|
-
export
|
|
259
|
-
export {
|
|
260
|
-
formatPosition,
|
|
261
|
-
POSITION_CACHE_MS,
|
|
262
|
-
parsePosition,
|
|
263
|
-
primaryPosition,
|
|
264
|
-
replayReader,
|
|
265
|
-
} from './replica-position';
|
|
266
|
-
export { type DbNode, isPlainRead } from './replica-route';
|
|
224
|
+
export { formatPosition, parsePosition, primaryPosition } from './replica-position';
|
|
225
|
+
export { isPlainRead } from './replica-route';
|
|
267
226
|
export type { ReplicaReadsOptions, ReplicaScope } from './replica-scope';
|
|
268
|
-
export { markScopeWrote,
|
|
227
|
+
export { markScopeWrote, withReplicaReads } from './replica-scope';
|
|
269
228
|
export { recordRetired } from './retired';
|
|
270
229
|
export type { RollingUnsafeKind, RollingUnsafeStatement } from './rolling';
|
|
271
230
|
export {
|
|
@@ -277,52 +236,24 @@ export {
|
|
|
277
236
|
} from './rolling';
|
|
278
237
|
export { migrationRollingUnsafe } from './rolling-errors';
|
|
279
238
|
export { rowSecureClient } from './row-secure-client';
|
|
280
|
-
export {
|
|
281
|
-
|
|
282
|
-
dropRowSecuritySql,
|
|
283
|
-
enableRowSecuritySql,
|
|
284
|
-
ROW_SECURITY_POLICY,
|
|
285
|
-
TENANT_SETTING,
|
|
286
|
-
} from './row-security';
|
|
287
|
-
export { holdMigratorRole, migratorOwnershipSql } from './row-security-migrator';
|
|
288
|
-
export type { RowSecurityPlanInput, TenantTable } from './row-security-plan';
|
|
289
|
-
export { rowSecurityAfter, rowSecurityPlan } from './row-security-plan';
|
|
239
|
+
export { CROSS_TENANT_SETTING, enableRowSecuritySql } from './row-security';
|
|
240
|
+
export { holdMigratorRole } from './row-security-migrator';
|
|
290
241
|
export type { RowSecurityRole } from './row-security-role';
|
|
291
|
-
export {
|
|
292
|
-
|
|
293
|
-
rowSecurityExemption,
|
|
294
|
-
rowSecurityRole,
|
|
295
|
-
} from './row-security-role';
|
|
296
|
-
export {
|
|
297
|
-
APP_ROLE,
|
|
298
|
-
assumeRole,
|
|
299
|
-
ensureRowSecurityRoles,
|
|
300
|
-
MIGRATOR_ROLE,
|
|
301
|
-
rowSecurityRolesSql,
|
|
302
|
-
serveAsAppRole,
|
|
303
|
-
} from './row-security-roles';
|
|
242
|
+
export { assertRowSecurityBinds } from './row-security-role';
|
|
243
|
+
export { APP_ROLE, MIGRATOR_ROLE, rowSecurityRolesSql, serveAsAppRole } from './row-security-roles';
|
|
304
244
|
export { sameTenantKeyName } from './same-tenant';
|
|
305
245
|
export { SIBLING_SCOPE_WAIT_MS } from './sibling-turn';
|
|
306
246
|
export { snapshotJson } from './snapshot-json';
|
|
307
247
|
export { parseSnapshot } from './snapshot-parse';
|
|
308
248
|
export type { SqlFragment } from './sql';
|
|
309
|
-
export {
|
|
310
|
-
identifier,
|
|
311
|
-
isSqlFragment,
|
|
312
|
-
join,
|
|
313
|
-
literal,
|
|
314
|
-
raw,
|
|
315
|
-
shellInertIdentifier,
|
|
316
|
-
sql,
|
|
317
|
-
} from './sql';
|
|
249
|
+
export { identifier, join, literal, raw, shellInertIdentifier, sql } from './sql';
|
|
318
250
|
export { stripSqlNoise } from './sql-noise';
|
|
319
251
|
export { dollarTagAt, endOfBlockComment } from './sql-scan';
|
|
320
252
|
export type { DbSqlStateCode } from './sqlstate';
|
|
321
|
-
export { DB_SQLSTATE_CODES, isRetryableState, SQLSTATE, sqlState
|
|
253
|
+
export { DB_SQLSTATE_CODES, isRetryableState, SQLSTATE, sqlState } from './sqlstate';
|
|
322
254
|
export type { StatementBoundOptions } from './statement-bound';
|
|
323
255
|
export { withStatementTimeout } from './statement-bound';
|
|
324
256
|
export { statementFingerprint, statementKind, statementVerb } from './statement-shape';
|
|
325
|
-
export { STATEMENT_ATTRIBUTE } from './statement-span';
|
|
326
257
|
export { statementsOf } from './statement-split';
|
|
327
258
|
export {
|
|
328
259
|
completeTransaction,
|