@rebasepro/server-postgres 0.12.1-canary.gf5f1d39 → 0.13.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.
Files changed (92) hide show
  1. package/dist/PostgresBackendDriver.d.ts +1 -1
  2. package/dist/PostgresBootstrapper.d.ts +25 -1
  3. package/dist/auth/services.d.ts +21 -0
  4. package/dist/backup/backup-service.d.ts +10 -1
  5. package/dist/backup/pg-tools.d.ts +47 -0
  6. package/dist/backup-service-CD8o_1Sl.js +8999 -0
  7. package/dist/backup-service-CD8o_1Sl.js.map +1 -0
  8. package/dist/cli-helpers.d.ts +39 -0
  9. package/dist/connection-BuZ97wsr.js +250 -0
  10. package/dist/connection-BuZ97wsr.js.map +1 -0
  11. package/dist/connection.d.ts +42 -0
  12. package/dist/ensure-collection-policies-ViG8XiPn.js +57 -0
  13. package/dist/ensure-collection-policies-ViG8XiPn.js.map +1 -0
  14. package/dist/ensure-collection-tables-CBQdOETu.js +650 -0
  15. package/dist/ensure-collection-tables-CBQdOETu.js.map +1 -0
  16. package/dist/index.es.js +1231 -10031
  17. package/dist/index.es.js.map +1 -1
  18. package/dist/policy-CeA1JcxP.js +105 -0
  19. package/dist/policy-CeA1JcxP.js.map +1 -0
  20. package/dist/schema/auth-schema.d.ts +83 -144
  21. package/dist/schema/ensure-collection-policies.d.ts +60 -0
  22. package/dist/schema/ensure-collection-tables.d.ts +44 -2
  23. package/dist/schema/generate-postgres-ddl-logic.d.ts +135 -1
  24. package/dist/schema/introspect-db-constraints.d.ts +57 -0
  25. package/dist/schema/introspect-db-logic.d.ts +94 -5
  26. package/dist/schema/introspect-db-queries.d.ts +119 -0
  27. package/dist/schema/introspect-db-structure.d.ts +263 -0
  28. package/dist/schema/introspect-db-types.d.ts +11 -0
  29. package/dist/services/FetchService.d.ts +4 -1
  30. package/dist/services/RelationService.d.ts +24 -1
  31. package/dist/services/channel-bus/index.d.ts +1 -7
  32. package/dist/services/collection-helpers.d.ts +36 -2
  33. package/dist/services/dataService.d.ts +3 -1
  34. package/dist/services/row-pipeline.d.ts +1 -1
  35. package/dist/{src-BbFOPJ1S.js → src-DlPBctw_.js} +299 -173
  36. package/dist/src-DlPBctw_.js.map +1 -0
  37. package/dist/{src-Zqwaw3P5.js → src-DoU9yPqq.js} +3 -159
  38. package/dist/src-DoU9yPqq.js.map +1 -0
  39. package/dist/utils/connection-string.d.ts +29 -0
  40. package/dist/utils/drizzle-conditions.d.ts +5 -4
  41. package/dist/utils/pg-error-utils.d.ts +35 -0
  42. package/dist/websocket-B2LsrINK.js +530 -0
  43. package/dist/websocket-B2LsrINK.js.map +1 -0
  44. package/package.json +14 -14
  45. package/src/PostgresAdapter.ts +21 -2
  46. package/src/PostgresBackendDriver.ts +4 -0
  47. package/src/PostgresBootstrapper.ts +192 -33
  48. package/src/auth/ensure-tables.ts +164 -9
  49. package/src/auth/services.ts +24 -2
  50. package/src/backup/backup-cli.ts +41 -2
  51. package/src/backup/backup-service.ts +38 -5
  52. package/src/backup/pg-tools.ts +96 -3
  53. package/src/cli-helpers.ts +70 -0
  54. package/src/cli.ts +44 -26
  55. package/src/collections/validate-relations.ts +15 -0
  56. package/src/connection.ts +73 -0
  57. package/src/data-transformer.ts +9 -3
  58. package/src/databasePoolManager.ts +5 -2
  59. package/src/schema/auth-schema.ts +30 -19
  60. package/src/schema/ensure-collection-policies.ts +105 -0
  61. package/src/schema/ensure-collection-tables.test.ts +105 -9
  62. package/src/schema/ensure-collection-tables.ts +220 -32
  63. package/src/schema/generate-drizzle-schema-logic.ts +42 -6
  64. package/src/schema/generate-postgres-ddl-logic.ts +382 -19
  65. package/src/schema/introspect-db-constraints.ts +385 -0
  66. package/src/schema/introspect-db-inference.ts +18 -8
  67. package/src/schema/introspect-db-logic.ts +385 -71
  68. package/src/schema/introspect-db-queries.ts +326 -0
  69. package/src/schema/introspect-db-structure.ts +670 -0
  70. package/src/schema/introspect-db-types.ts +56 -0
  71. package/src/schema/introspect-db.ts +37 -80
  72. package/src/schema/introspect-runtime.test.ts +56 -8
  73. package/src/schema/introspect-runtime.ts +31 -9
  74. package/src/security/policy-drift.test.ts +11 -3
  75. package/src/services/BranchService.ts +66 -28
  76. package/src/services/FetchService.ts +90 -14
  77. package/src/services/PersistService.ts +20 -6
  78. package/src/services/RelationService.ts +249 -48
  79. package/src/services/channel-bus/index.ts +0 -9
  80. package/src/services/collection-helpers.ts +69 -3
  81. package/src/services/dataService.ts +3 -1
  82. package/src/services/realtimeService.ts +3 -3
  83. package/src/services/row-pipeline.ts +1 -1
  84. package/src/utils/connection-string.ts +58 -0
  85. package/src/utils/drizzle-conditions.ts +31 -6
  86. package/src/utils/pg-error-utils.ts +65 -0
  87. package/src/websocket.ts +18 -9
  88. package/dist/chunk-DSJWtz9O.js +0 -40
  89. package/dist/ensure-collection-tables-CNTcZGvn.js +0 -304
  90. package/dist/ensure-collection-tables-CNTcZGvn.js.map +0 -1
  91. package/dist/src-BbFOPJ1S.js.map +0 -1
  92. package/dist/src-Zqwaw3P5.js.map +0 -1
@@ -0,0 +1,326 @@
1
+ /**
2
+ * The catalog queries introspection runs, and the shape they produce.
3
+ *
4
+ * These live apart from {@link ./introspect-db.ts} (the CLI entry point) on
5
+ * purpose: the fixture-capture script and the live e2e read a database through
6
+ * this module too, so what the tests see is what the CLI sees. A query that
7
+ * only exists inside the CLI's `main()` can only be tested by running the CLI.
8
+ *
9
+ * No side effects beyond `SELECT`. Introspection reads a database it does not
10
+ * own — it must never `ANALYZE`, create a temp table, or otherwise write.
11
+ */
12
+ import type {
13
+ TableRow,
14
+ TableColumn,
15
+ EnumValue,
16
+ PrimaryKeyRow,
17
+ ForeignKeyRow,
18
+ UniqueConstraintRow,
19
+ CheckConstraintRow,
20
+ CommentRow,
21
+ SchemaMetadata
22
+ } from "./introspect-db-logic";
23
+
24
+ /** The subset of `pg.Client` this module needs, so tests can pass a fake. */
25
+ export interface QueryableClient {
26
+ query<R = Record<string, unknown>>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;
27
+ }
28
+
29
+ /**
30
+ * Base tables, excluding partitions.
31
+ *
32
+ * `relispartition` is the reason this reads `pg_class` rather than
33
+ * `information_schema.tables`, which reports every partition as a base table of
34
+ * its own. Pagila partitions `payment` by month; introspected through
35
+ * information_schema it yields `payment` plus 26 near-identical
36
+ * `payment_p2022_*` collections, each with its own nav entry.
37
+ *
38
+ * `relkind = 'p'` (the partitioned parent) is included and `'r'` partitions are
39
+ * dropped, which is the right way round: the parent is the queryable table.
40
+ */
41
+ export const TABLES_QUERY = `
42
+ SELECT c.relname AS table_name,
43
+ c.relkind = 'p' AS is_partitioned
44
+ FROM pg_class c
45
+ JOIN pg_namespace n ON n.oid = c.relnamespace
46
+ WHERE n.nspname = $1
47
+ AND c.relkind IN ('r', 'p')
48
+ AND NOT c.relispartition
49
+ AND c.relname NOT LIKE 'drizzle_%'
50
+ AND c.relname NOT LIKE 'rebase_%'
51
+ ORDER BY c.relname
52
+ `;
53
+
54
+ /**
55
+ * Columns, with the catalog facts that say a column is not the user's to edit.
56
+ *
57
+ * `is_generated`/`is_identity` are read for that reason: a generated column
58
+ * rejects any write, so a form that offers it is offering a field that always
59
+ * errors. `character_maximum_length` is the declared `varchar(n)` bound —
60
+ * already enforced by the database, and free to surface as validation.
61
+ */
62
+ export const COLUMNS_QUERY = `
63
+ SELECT
64
+ c.table_name,
65
+ c.column_name,
66
+ c.data_type,
67
+ c.udt_name,
68
+ c.is_nullable,
69
+ c.column_default,
70
+ c.ordinal_position,
71
+ c.is_generated,
72
+ c.is_identity,
73
+ c.identity_generation,
74
+ c.character_maximum_length,
75
+ c.numeric_precision,
76
+ c.numeric_scale,
77
+ (SELECT a.atttypmod FROM pg_attribute a
78
+ JOIN pg_class pc ON a.attrelid = pc.oid
79
+ WHERE pc.relname = c.table_name
80
+ AND a.attname = c.column_name
81
+ AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod
82
+ FROM information_schema.columns c
83
+ WHERE c.table_schema = $1
84
+ ORDER BY c.table_name, c.ordinal_position
85
+ `;
86
+
87
+ export const ENUMS_QUERY = `
88
+ SELECT t.typname AS enum_name,
89
+ e.enumlabel AS enum_value,
90
+ e.enumsortorder AS sort_order
91
+ FROM pg_type t
92
+ JOIN pg_enum e ON t.oid = e.enumtypid
93
+ JOIN pg_namespace n ON t.typnamespace = n.oid
94
+ WHERE n.nspname = $1
95
+ ORDER BY t.typname, e.enumsortorder
96
+ `;
97
+
98
+ /**
99
+ * Primary key columns, in key order.
100
+ *
101
+ * `ORDER BY k.ord` matters for composite keys: the position of a column inside
102
+ * the key is what tells a two-column PK made of two foreign keys apart from an
103
+ * ordinary composite key, and `= ANY(i.indkey)` (the shape this replaced)
104
+ * returns catalog order instead.
105
+ */
106
+ export const PRIMARY_KEYS_QUERY = `
107
+ SELECT t.relname AS table_name,
108
+ a.attname AS column_name
109
+ FROM pg_index i
110
+ JOIN pg_class t ON t.oid = i.indrelid
111
+ JOIN pg_namespace n ON n.oid = t.relnamespace
112
+ CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
113
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
114
+ WHERE i.indisprimary AND n.nspname = $1
115
+ ORDER BY t.relname, k.ord
116
+ `;
117
+
118
+ /**
119
+ * Foreign keys, one row per referencing column, with the delete rule.
120
+ *
121
+ * Read from `pg_constraint` rather than through
122
+ * `information_schema.constraint_column_usage`, which does not preserve the
123
+ * pairing on a composite foreign key: it reports the cross product of the
124
+ * constraint's columns, so a two-column FK comes back as four rows, two of them
125
+ * pairing the wrong columns. `unnest(...) WITH ORDINALITY` on both sides joined
126
+ * on the ordinal keeps each referencing column with the column it references.
127
+ *
128
+ * `confdeltype` is carried because `ON DELETE CASCADE` is the schema author
129
+ * saying, in the database, that the child cannot outlive the parent — the one
130
+ * unambiguous declaration of ownership a schema contains.
131
+ *
132
+ * Constraints declared on a *partition* are attributed to the partition root,
133
+ * because that is the table this run generates a collection for. Pagila declares
134
+ * `payment`'s three foreign keys on each monthly partition and none on the
135
+ * parent, so reading `pg_constraint` at face value gives the `payment`
136
+ * collection no relations at all. `pick = 1` then keeps one row per logical key,
137
+ * preferring the root's own constraint when it has one, so a schema that
138
+ * declares the key on the parent *and* inherits it onto 26 partitions does not
139
+ * yield 27 copies of the same relation.
140
+ */
141
+ export const FOREIGN_KEYS_QUERY = `
142
+ WITH fk AS (
143
+ SELECT con.oid,
144
+ con.conname,
145
+ con.conrelid,
146
+ con.confrelid,
147
+ con.conkey,
148
+ con.confkey,
149
+ con.confdeltype,
150
+ COALESCE(pg_partition_root(con.conrelid), con.conrelid) AS root_oid,
151
+ row_number() OVER (
152
+ PARTITION BY COALESCE(pg_partition_root(con.conrelid), con.conrelid),
153
+ con.confrelid, con.conkey, con.confkey
154
+ ORDER BY (con.conrelid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)) DESC,
155
+ con.oid
156
+ ) AS pick
157
+ FROM pg_constraint con
158
+ JOIN pg_namespace n ON n.oid = con.connamespace
159
+ WHERE con.contype = 'f' AND n.nspname = $1
160
+ )
161
+ SELECT root.relname AS table_name,
162
+ sa.attname AS column_name,
163
+ tgt.relname AS foreign_table_name,
164
+ ta.attname AS foreign_column_name,
165
+ fk.conname AS constraint_name,
166
+ s.ord::int AS ordinal,
167
+ CASE fk.confdeltype
168
+ WHEN 'a' THEN 'NO ACTION'
169
+ WHEN 'r' THEN 'RESTRICT'
170
+ WHEN 'c' THEN 'CASCADE'
171
+ WHEN 'n' THEN 'SET NULL'
172
+ WHEN 'd' THEN 'SET DEFAULT'
173
+ END AS delete_rule
174
+ FROM fk
175
+ JOIN pg_class root ON root.oid = fk.root_oid
176
+ JOIN pg_class tgt ON tgt.oid = fk.confrelid
177
+ CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)
178
+ JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum
179
+ CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)
180
+ JOIN pg_attribute ta ON ta.attrelid = fk.confrelid AND ta.attnum = f.attnum
181
+ WHERE fk.pick = 1 AND s.ord = f.ord
182
+ ORDER BY root.relname, fk.conname, s.ord
183
+ `;
184
+
185
+ /**
186
+ * Unique constraints and unique indexes, as ordered column lists.
187
+ *
188
+ * Indexes rather than constraints alone, because `CREATE UNIQUE INDEX` and
189
+ * `ADD CONSTRAINT ... UNIQUE` produce the same guarantee and schemas use both.
190
+ * Partial indexes (`indpred IS NOT NULL`) are excluded: they promise uniqueness
191
+ * only over the rows matching their predicate, which is not the promise a
192
+ * `validation: { unique: true }` field makes.
193
+ */
194
+ export const UNIQUE_CONSTRAINTS_QUERY = `
195
+ SELECT t.relname AS table_name,
196
+ ic.relname AS constraint_name,
197
+ -- ::text, because the driver has no parser for an array of \`name\`
198
+ -- and hands back the raw \`{a,b}\` literal as a string. Every consumer
199
+ -- here indexes and compares it as an array, and a string of that
200
+ -- shape fails those silently rather than loudly.
201
+ array_agg(a.attname::text ORDER BY k.ord) AS column_names
202
+ FROM pg_index i
203
+ JOIN pg_class t ON t.oid = i.indrelid
204
+ JOIN pg_class ic ON ic.oid = i.indexrelid
205
+ JOIN pg_namespace n ON n.oid = t.relnamespace
206
+ CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
207
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
208
+ WHERE i.indisunique
209
+ AND NOT i.indisprimary
210
+ AND i.indpred IS NULL
211
+ AND n.nspname = $1
212
+ AND NOT t.relispartition
213
+ GROUP BY t.relname, ic.relname
214
+ ORDER BY t.relname, ic.relname
215
+ `;
216
+
217
+ /**
218
+ * CHECK constraints, as the source text Postgres reproduces them from.
219
+ *
220
+ * `pg_get_constraintdef` output is normalized by the server — the parser in
221
+ * {@link ./introspect-db-constraints.ts} reads that normalized form, not
222
+ * whatever the author typed.
223
+ */
224
+ export const CHECK_CONSTRAINTS_QUERY = `
225
+ SELECT DISTINCT
226
+ root.relname AS table_name,
227
+ con.conname AS constraint_name,
228
+ pg_get_constraintdef(con.oid) AS definition
229
+ FROM pg_constraint con
230
+ JOIN pg_namespace n ON n.oid = con.connamespace
231
+ JOIN pg_class root ON root.oid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)
232
+ WHERE con.contype = 'c'
233
+ AND n.nspname = $1
234
+ ORDER BY root.relname, con.conname
235
+ `;
236
+
237
+ /**
238
+ * `COMMENT ON TABLE` / `COMMENT ON COLUMN`, which is documentation the author
239
+ * already wrote and which nothing downstream has ever read.
240
+ */
241
+ export const COMMENTS_QUERY = `
242
+ SELECT t.relname AS table_name,
243
+ a.attname AS column_name,
244
+ d.description AS comment
245
+ FROM pg_description d
246
+ JOIN pg_class t ON t.oid = d.objoid
247
+ JOIN pg_namespace n ON n.oid = t.relnamespace
248
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.objsubid
249
+ WHERE n.nspname = $1
250
+ AND t.relkind IN ('r', 'p')
251
+ AND (d.objsubid = 0 OR a.attname IS NOT NULL)
252
+ ORDER BY t.relname, d.objsubid
253
+ `;
254
+
255
+ /**
256
+ * Counts a table's rows, stopping once the answer can only be "more than
257
+ * `limit`".
258
+ *
259
+ * Introspection asks this to tell a small reference table from a table that
260
+ * merely looks like one (see `classifyTables`). `reltuples` would answer for
261
+ * free but lies on a table that has never been analyzed — which is every table
262
+ * in a database restored from a dump, i.e. exactly the case introspection meets
263
+ * — and reports -1 there rather than an error, so the lie is silent.
264
+ *
265
+ * The subquery's LIMIT caps the work at `limit + 1` rows however large the
266
+ * table is, so this stays cheap on a table with a billion rows.
267
+ */
268
+ export async function countRowsUpTo(
269
+ client: QueryableClient,
270
+ schema: string,
271
+ table: string,
272
+ limit: number
273
+ ): Promise<number> {
274
+ const { rows } = await client.query<{ count: string }>(
275
+ `SELECT count(*)::text AS count FROM (SELECT 1 FROM "${schema}"."${table}" LIMIT ${limit + 1}) probe`
276
+ );
277
+ return Number(rows[0]?.count ?? 0);
278
+ }
279
+
280
+ /**
281
+ * Reads everything the generator needs, in one pass.
282
+ *
283
+ * `rowCounts` is deliberately absent here: it costs a query per table and only
284
+ * a handful of tables can possibly need it. The caller fills it in for the
285
+ * candidates `lookupCandidates()` names.
286
+ */
287
+ export async function readSchemaMetadata(
288
+ client: QueryableClient,
289
+ schema: string
290
+ ): Promise<SchemaMetadata> {
291
+ // Sequential, not `Promise.all`. A `pg.Client` is a single connection with
292
+ // one protocol stream: concurrent `query()` calls on one are queued and
293
+ // deprecated (removed in pg@9), so the parallel version buys nothing and
294
+ // warns while doing it.
295
+ const tables = await client.query<TableRow>(TABLES_QUERY, [schema]);
296
+ const columns = await client.query<TableColumn>(COLUMNS_QUERY, [schema]);
297
+ const enumValues = await client.query<EnumValue>(ENUMS_QUERY, [schema]);
298
+ const pks = await client.query<PrimaryKeyRow>(PRIMARY_KEYS_QUERY, [schema]);
299
+ const fks = await client.query<ForeignKeyRow>(FOREIGN_KEYS_QUERY, [schema]);
300
+ const uniques = await client.query<UniqueConstraintRow>(UNIQUE_CONSTRAINTS_QUERY, [schema]);
301
+ const checks = await client.query<CheckConstraintRow>(CHECK_CONSTRAINTS_QUERY, [schema]);
302
+ const comments = await client.query<CommentRow>(COMMENTS_QUERY, [schema]);
303
+
304
+ // A column list scoped to the schema still names tables this run excludes —
305
+ // views, partitions, the drizzle bookkeeping tables. Narrow every row set to
306
+ // the tables actually being introspected so downstream code never has to
307
+ // ask whether a table it found in `columns` really exists.
308
+ const known = new Set(tables.rows.map((t) => t.table_name));
309
+ const scoped = <T extends { table_name: string }>(rows: T[]) => rows.filter((r) => known.has(r.table_name));
310
+
311
+ return {
312
+ schema,
313
+ tables: tables.rows,
314
+ columns: scoped(columns.rows),
315
+ enumValues: enumValues.rows,
316
+ pks: scoped(pks.rows),
317
+ // A foreign key pointing *out* of the introspected set (into another
318
+ // schema, or at a view) cannot be turned into a relation: there is no
319
+ // collection on the other end to link to.
320
+ fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),
321
+ uniques: scoped(uniques.rows),
322
+ checks: scoped(checks.rows),
323
+ comments: scoped(comments.rows),
324
+ rowCounts: {}
325
+ };
326
+ }