@owlmeans/postgres-resource 0.1.15

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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/agent-meta/instructions/postgres-resource.instructions.md +60 -0
  4. package/agent-meta/manifest.json +23 -0
  5. package/agent-meta/skills/postgres-resource/SKILL.md +186 -0
  6. package/build/consts.d.ts +81 -0
  7. package/build/consts.d.ts.map +1 -0
  8. package/build/consts.js +86 -0
  9. package/build/consts.js.map +1 -0
  10. package/build/declarations.d.ts +12 -0
  11. package/build/declarations.d.ts.map +1 -0
  12. package/build/declarations.js +28 -0
  13. package/build/declarations.js.map +1 -0
  14. package/build/errors.d.ts +70 -0
  15. package/build/errors.d.ts.map +1 -0
  16. package/build/errors.js +201 -0
  17. package/build/errors.js.map +1 -0
  18. package/build/helper.d.ts +4 -0
  19. package/build/helper.d.ts.map +1 -0
  20. package/build/helper.js +5 -0
  21. package/build/helper.js.map +1 -0
  22. package/build/index.d.ts +8 -0
  23. package/build/index.d.ts.map +1 -0
  24. package/build/index.js +7 -0
  25. package/build/index.js.map +1 -0
  26. package/build/resource.d.ts +4 -0
  27. package/build/resource.d.ts.map +1 -0
  28. package/build/resource.js +395 -0
  29. package/build/resource.js.map +1 -0
  30. package/build/types.d.ts +273 -0
  31. package/build/types.d.ts.map +1 -0
  32. package/build/types.js +2 -0
  33. package/build/types.js.map +1 -0
  34. package/build/utils/criteria.d.ts +24 -0
  35. package/build/utils/criteria.d.ts.map +1 -0
  36. package/build/utils/criteria.js +209 -0
  37. package/build/utils/criteria.js.map +1 -0
  38. package/build/utils/diff.d.ts +24 -0
  39. package/build/utils/diff.d.ts.map +1 -0
  40. package/build/utils/diff.js +330 -0
  41. package/build/utils/diff.js.map +1 -0
  42. package/build/utils/index.d.ts +12 -0
  43. package/build/utils/index.d.ts.map +1 -0
  44. package/build/utils/index.js +12 -0
  45. package/build/utils/index.js.map +1 -0
  46. package/build/utils/introspect.d.ts +7 -0
  47. package/build/utils/introspect.d.ts.map +1 -0
  48. package/build/utils/introspect.js +70 -0
  49. package/build/utils/introspect.js.map +1 -0
  50. package/build/utils/life-cycle.d.ts +39 -0
  51. package/build/utils/life-cycle.d.ts.map +1 -0
  52. package/build/utils/life-cycle.js +119 -0
  53. package/build/utils/life-cycle.js.map +1 -0
  54. package/build/utils/marshal.d.ts +36 -0
  55. package/build/utils/marshal.d.ts.map +1 -0
  56. package/build/utils/marshal.js +152 -0
  57. package/build/utils/marshal.js.map +1 -0
  58. package/build/utils/migrations.d.ts +16 -0
  59. package/build/utils/migrations.d.ts.map +1 -0
  60. package/build/utils/migrations.js +108 -0
  61. package/build/utils/migrations.js.map +1 -0
  62. package/build/utils/name.d.ts +39 -0
  63. package/build/utils/name.d.ts.map +1 -0
  64. package/build/utils/name.js +63 -0
  65. package/build/utils/name.js.map +1 -0
  66. package/build/utils/schema.d.ts +28 -0
  67. package/build/utils/schema.d.ts.map +1 -0
  68. package/build/utils/schema.js +356 -0
  69. package/build/utils/schema.js.map +1 -0
  70. package/build/utils/sql.d.ts +22 -0
  71. package/build/utils/sql.d.ts.map +1 -0
  72. package/build/utils/sql.js +0 -0
  73. package/build/utils/sql.js.map +1 -0
  74. package/build/utils/sync.d.ts +21 -0
  75. package/build/utils/sync.d.ts.map +1 -0
  76. package/build/utils/sync.js +93 -0
  77. package/build/utils/sync.js.map +1 -0
  78. package/build/utils/table.d.ts +8 -0
  79. package/build/utils/table.d.ts.map +1 -0
  80. package/build/utils/table.js +68 -0
  81. package/build/utils/table.js.map +1 -0
  82. package/package.json +50 -0
  83. package/src/consts.ts +95 -0
  84. package/src/declarations.ts +41 -0
  85. package/src/errors.ts +242 -0
  86. package/src/helper.ts +7 -0
  87. package/src/index.ts +7 -0
  88. package/src/resource.ts +524 -0
  89. package/src/types.ts +310 -0
  90. package/src/utils/criteria.ts +246 -0
  91. package/src/utils/diff.ts +363 -0
  92. package/src/utils/index.ts +11 -0
  93. package/src/utils/introspect.ts +87 -0
  94. package/src/utils/life-cycle.ts +155 -0
  95. package/src/utils/marshal.ts +175 -0
  96. package/src/utils/migrations.ts +135 -0
  97. package/src/utils/name.ts +79 -0
  98. package/src/utils/schema.ts +426 -0
  99. package/src/utils/sql.ts +0 -0
  100. package/src/utils/sync.ts +106 -0
  101. package/src/utils/table.ts +76 -0
  102. package/tests/errors.spec.ts +121 -0
  103. package/tests/name.spec.ts +75 -0
  104. package/tests/schema.spec.ts +258 -0
  105. package/tests/sql.spec.ts +104 -0
  106. package/tsconfig.json +16 -0
@@ -0,0 +1,363 @@
1
+ import type { BasicContext } from '@owlmeans/context'
2
+ import type { ResourceRecord } from '@owlmeans/resource'
3
+
4
+ import { PgIndexMethod } from '../consts.js'
5
+ import { PostgresPlaceholderError } from '../errors.js'
6
+ import type {
7
+ ColumnSpec, DdlPlan, DdlStatement, LiveTable, PgIndexSpec, PostgresResource, TableSpec
8
+ } from '../types.js'
9
+ import { qualify, quoteIdent } from './name.js'
10
+
11
+ const literal = (value: string | number | boolean | null): string => {
12
+ if (value === null) return 'NULL'
13
+ if (typeof value === 'number') return `${value}`
14
+ if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE'
15
+
16
+ return `'${value.replace(/'/g, "''")}'`
17
+ }
18
+
19
+ const defaultExpression = (column: ColumnSpec): string | undefined => {
20
+ if (column.defaultRaw != null) return column.defaultRaw
21
+ if (column.defaultLiteral !== undefined) return literal(column.defaultLiteral)
22
+
23
+ return undefined
24
+ }
25
+
26
+ /**
27
+ * Postgres echoes defaults back with an explicit cast — a declared `'active'` comes back
28
+ * as `'active'::text`. Strip a trailing cast when the literal underneath still matches, so
29
+ * an unchanged default doesn't look like drift on every boot.
30
+ */
31
+ const normalizeDefault = (expression: string | null | undefined): string | null => {
32
+ if (expression == null) return null
33
+
34
+ return expression.trim().replace(/::[a-z0-9_ ."\[\]]+$/i, '').trim().toLowerCase()
35
+ }
36
+
37
+ const normalizeDefinition = (definition: string): string =>
38
+ definition.replace(/\s+/g, ' ').replace(/ ?, ?/g, ',').trim().toLowerCase()
39
+
40
+ const columnList = (columns: string[]): string => columns.map(quoteIdent).join(', ')
41
+
42
+ const indexStatement = (spec: TableSpec, entry: PgIndexSpec): string => {
43
+ const target = entry.expression != null
44
+ ? `(${entry.expression})`
45
+ : `(${columnList(entry.columns as string[])})`
46
+ const where = entry.where != null ? ` WHERE ${entry.where}` : ''
47
+
48
+ return `CREATE ${entry.unique === true ? 'UNIQUE ' : ''}INDEX ${quoteIdent(entry.name!)}`
49
+ + ` ON ${spec.qualified} USING ${entry.method ?? PgIndexMethod.BTree} ${target}${where}`
50
+ }
51
+
52
+ const columnDefinition = (column: ColumnSpec): string => {
53
+ const parts = [quoteIdent(column.column), column.sqlType]
54
+ if (column.notNull) parts.push('NOT NULL')
55
+ const expression = defaultExpression(column)
56
+ if (expression != null) parts.push(`DEFAULT ${expression}`)
57
+
58
+ return parts.join(' ')
59
+ }
60
+
61
+ /**
62
+ * Foreign keys are planned separately from the rest of the table, and applied only once
63
+ * every resource has initialized: a key points at a table another resource owns, and that
64
+ * resource's own `init()` may not have run yet.
65
+ *
66
+ * @throws {PostgresPlaceholderError} when a target can't be resolved.
67
+ */
68
+ export const planForeignKeys = (
69
+ spec: TableSpec, context?: BasicContext<any>
70
+ ): DdlStatement[] => spec.references.map(reference => {
71
+ const column = reference.property != null ? spec.byProperty[reference.property] : undefined
72
+ if (column == null) {
73
+ throw new PostgresPlaceholderError(`fk-unknown-property:${reference.property}`)
74
+ }
75
+
76
+ let targetSchema = reference.schema ?? spec.schema
77
+ let targetTable = reference.table
78
+ if (reference.resource != null) {
79
+ if (context == null) {
80
+ throw new PostgresPlaceholderError(`fk-no-context:${reference.resource}`)
81
+ }
82
+ let target: PostgresResource<ResourceRecord>
83
+ try {
84
+ target = context.resource<PostgresResource<ResourceRecord>>(reference.resource)
85
+ } catch {
86
+ throw new PostgresPlaceholderError(`fk-unknown-resource:${reference.resource}`)
87
+ }
88
+ if (target.table == null) {
89
+ throw new PostgresPlaceholderError(`fk-uninitialized:${reference.resource}`)
90
+ }
91
+ targetSchema = target.table.schema
92
+ targetTable = target.table.table
93
+ }
94
+ if (targetTable == null) {
95
+ throw new PostgresPlaceholderError(`fk-no-target:${reference.property}`)
96
+ }
97
+
98
+ const actions = [
99
+ reference.onDelete != null ? ` ON DELETE ${reference.onDelete}` : '',
100
+ reference.onUpdate != null ? ` ON UPDATE ${reference.onUpdate}` : ''
101
+ ].join('')
102
+
103
+ return {
104
+ kind: 'add-foreign-key' as const,
105
+ target: reference.name!,
106
+ sql: `ALTER TABLE ${spec.qualified} ADD CONSTRAINT ${quoteIdent(reference.name!)}`
107
+ + ` FOREIGN KEY (${quoteIdent(column.column)})`
108
+ + ` REFERENCES ${qualify(targetSchema, targetTable)} (${quoteIdent(reference.column!)})${actions}`
109
+ }
110
+ })
111
+
112
+ /**
113
+ * Compare the compiled specification against the live table and produce the ordered DDL
114
+ * that converges one onto the other.
115
+ *
116
+ * Statement order is load bearing:
117
+ * - `DROP COLUMN` is last, because a `USING` cast or a backfill may legitimately read a
118
+ * column that is about to disappear.
119
+ * - A primary key constraint is never dropped: it cascades into every referencing key and
120
+ * can't be undone inside the same transaction once dependents exist.
121
+ *
122
+ * Foreign keys are not part of the plan at all — see {@link planForeignKeys}.
123
+ */
124
+ export const planSync = (
125
+ spec: TableSpec, live: LiveTable, additive: boolean = false
126
+ ): DdlPlan => {
127
+ if (!live.exists) {
128
+ const constraints: string[] = []
129
+ if (spec.primaryKey.length > 0) {
130
+ constraints.push(`CONSTRAINT ${quoteIdent(`${spec.table}_pkey`)} PRIMARY KEY (${columnList(spec.primaryKey)})`)
131
+ }
132
+ for (const unique of spec.uniques) {
133
+ constraints.push(`CONSTRAINT ${quoteIdent(unique.name!)} UNIQUE (${columnList(unique.columns)})`)
134
+ }
135
+ for (const check of spec.checks) {
136
+ constraints.push(`CONSTRAINT ${quoteIdent(check.name!)} CHECK (${check.expression})`)
137
+ }
138
+
139
+ const statements: DdlStatement[] = [{
140
+ kind: 'create-table',
141
+ target: spec.table,
142
+ sql: `CREATE TABLE ${spec.qualified} (\n `
143
+ + [...spec.columns.map(columnDefinition), ...constraints].join(',\n ')
144
+ + '\n)'
145
+ }]
146
+ for (const entry of spec.indexes) {
147
+ statements.push({ kind: 'create-index', target: entry.name!, sql: indexStatement(spec, entry) })
148
+ }
149
+
150
+ return { fresh: true, statements }
151
+ }
152
+
153
+ const statements: DdlStatement[] = []
154
+ const byName: Record<string, typeof live.columns[number]> = {}
155
+ for (const column of live.columns) {
156
+ byName[column.name] = column
157
+ }
158
+
159
+ const managed = spec.columns.filter(column => column.managed)
160
+
161
+ /** 1. Columns the table doesn't have yet — always added nullable so existing rows survive. */
162
+ for (const column of managed) {
163
+ if (byName[column.column] != null) {
164
+ continue
165
+ }
166
+ const expression = defaultExpression(column)
167
+ statements.push({
168
+ kind: 'add-column',
169
+ target: column.column,
170
+ sql: `ALTER TABLE ${spec.qualified} ADD COLUMN ${quoteIdent(column.column)} ${column.sqlType}`
171
+ + (expression != null ? ` DEFAULT ${expression}` : '')
172
+ })
173
+ if (column.notNull) {
174
+ if (expression == null) {
175
+ statements.push({
176
+ kind: 'backfill',
177
+ target: column.column,
178
+ sql: `UPDATE ${spec.qualified} SET ${quoteIdent(column.column)} = ${fallback(column)}`
179
+ + ` WHERE ${quoteIdent(column.column)} IS NULL`
180
+ })
181
+ }
182
+ statements.push({
183
+ kind: 'set-not-null',
184
+ target: column.column,
185
+ sql: `ALTER TABLE ${spec.qualified} ALTER COLUMN ${quoteIdent(column.column)} SET NOT NULL`
186
+ })
187
+ }
188
+ }
189
+
190
+ /** 2-4. Type, nullability and default drift on columns that already exist. */
191
+ for (const column of managed) {
192
+ const existing = byName[column.column]
193
+ if (existing == null) {
194
+ continue
195
+ }
196
+
197
+ if (!additive && existing.type !== column.sqlType) {
198
+ const using = column.using ?? `${quoteIdent(column.column)}::${column.sqlType}`
199
+ statements.push({
200
+ kind: 'alter-type',
201
+ target: column.column,
202
+ sql: `ALTER TABLE ${spec.qualified} ALTER COLUMN ${quoteIdent(column.column)}`
203
+ + ` TYPE ${column.sqlType} USING ${using}`
204
+ })
205
+ }
206
+
207
+ const expression = defaultExpression(column)
208
+ if (normalizeDefault(expression) !== normalizeDefault(existing.defaultExpr)) {
209
+ statements.push(expression != null
210
+ ? {
211
+ kind: 'set-default',
212
+ target: column.column,
213
+ sql: `ALTER TABLE ${spec.qualified} ALTER COLUMN ${quoteIdent(column.column)}`
214
+ + ` SET DEFAULT ${expression}`
215
+ }
216
+ : {
217
+ kind: 'set-default',
218
+ target: column.column,
219
+ sql: `ALTER TABLE ${spec.qualified} ALTER COLUMN ${quoteIdent(column.column)} DROP DEFAULT`
220
+ })
221
+ }
222
+
223
+ if (column.notNull !== existing.notNull) {
224
+ if (column.notNull) {
225
+ statements.push({
226
+ kind: 'backfill',
227
+ target: column.column,
228
+ sql: `UPDATE ${spec.qualified} SET ${quoteIdent(column.column)}`
229
+ + ` = ${expression ?? fallback(column)} WHERE ${quoteIdent(column.column)} IS NULL`
230
+ })
231
+ }
232
+ statements.push({
233
+ kind: column.notNull ? 'set-not-null' : 'drop-not-null',
234
+ target: column.column,
235
+ sql: `ALTER TABLE ${spec.qualified} ALTER COLUMN ${quoteIdent(column.column)}`
236
+ + ` ${column.notNull ? 'SET' : 'DROP'} NOT NULL`
237
+ })
238
+ }
239
+ }
240
+
241
+ /** 5. Unique and check constraints. Primary keys are deliberately excluded. */
242
+ const desiredConstraints: Record<string, string> = {}
243
+ for (const unique of spec.uniques) {
244
+ desiredConstraints[unique.name!] = `UNIQUE (${columnList(unique.columns)})`
245
+ }
246
+ for (const check of spec.checks) {
247
+ desiredConstraints[check.name!] = `CHECK ((${check.expression}))`
248
+ }
249
+ const liveConstraints: Record<string, string> = {}
250
+ for (const constraint of live.constraints) {
251
+ if (constraint.type === 'p' || constraint.type === 'f') {
252
+ continue
253
+ }
254
+ liveConstraints[constraint.name] = constraint.definition
255
+ }
256
+
257
+ for (const [name, definition] of Object.entries(liveConstraints)) {
258
+ const desired = desiredConstraints[name]
259
+ if (desired != null && normalizeDefinition(desired) === normalizeDefinition(definition)) {
260
+ continue
261
+ }
262
+ if (desired == null && additive) {
263
+ continue
264
+ }
265
+ if (desired == null && !isGenerated(name, spec)) {
266
+ /** A constraint nobody declared was added by hand — leave it alone. */
267
+ continue
268
+ }
269
+ statements.push({
270
+ kind: 'drop-constraint',
271
+ target: name,
272
+ sql: `ALTER TABLE ${spec.qualified} DROP CONSTRAINT ${quoteIdent(name)}`
273
+ })
274
+ }
275
+ for (const [name, definition] of Object.entries(desiredConstraints)) {
276
+ const existing = liveConstraints[name]
277
+ if (existing != null && normalizeDefinition(existing) === normalizeDefinition(definition)) {
278
+ continue
279
+ }
280
+ if (existing != null && additive) {
281
+ continue
282
+ }
283
+ statements.push({
284
+ kind: 'add-constraint',
285
+ target: name,
286
+ sql: `ALTER TABLE ${spec.qualified} ADD CONSTRAINT ${quoteIdent(name)} ${definition}`
287
+ })
288
+ }
289
+
290
+ /** 6. Indexes. Constraint backed indexes are owned by their constraint, not by us. */
291
+ const constraintBacked = live.constraints.map(constraint => constraint.name)
292
+ const desiredIndexes: Record<string, string> = {}
293
+ for (const entry of spec.indexes) {
294
+ desiredIndexes[entry.name!] = indexStatement(spec, entry)
295
+ }
296
+ for (const existing of live.indexes) {
297
+ if (constraintBacked.includes(existing.name)) {
298
+ continue
299
+ }
300
+ const desired = desiredIndexes[existing.name]
301
+ if (desired != null && normalizeDefinition(desired) === normalizeDefinition(existing.definition)) {
302
+ continue
303
+ }
304
+ if (desired == null && (additive || !isGenerated(existing.name, spec))) {
305
+ continue
306
+ }
307
+ statements.push({
308
+ kind: 'drop-index',
309
+ target: existing.name,
310
+ sql: `DROP INDEX ${qualify(spec.schema, existing.name)}`
311
+ })
312
+ }
313
+ for (const [name, statement] of Object.entries(desiredIndexes)) {
314
+ const existing = live.indexes.find(entry => entry.name === name)
315
+ if (existing != null && normalizeDefinition(existing.definition) === normalizeDefinition(statement)) {
316
+ continue
317
+ }
318
+ if (constraintBacked.includes(name)) {
319
+ continue
320
+ }
321
+ statements.push({ kind: 'create-index', target: name, sql: statement })
322
+ }
323
+
324
+ /** 7. Drops, last and only in full mode. */
325
+ if (!additive) {
326
+ const keep = [...managed.map(column => column.column), ...spec.unmanaged]
327
+ for (const existing of live.columns) {
328
+ if (keep.includes(existing.name) || existing.generated !== '') {
329
+ continue
330
+ }
331
+ statements.push({
332
+ kind: 'drop-column',
333
+ target: existing.name,
334
+ destructive: true,
335
+ sql: `ALTER TABLE ${spec.qualified} DROP COLUMN ${quoteIdent(existing.name)}`
336
+ })
337
+ }
338
+ }
339
+
340
+ return { fresh: false, statements }
341
+ }
342
+
343
+ /** A name this package would have generated is a name this package may drop. */
344
+ const isGenerated = (name: string, spec: TableSpec): boolean =>
345
+ name.startsWith(`${spec.table}_`)
346
+
347
+ /** Value used to fill an existing row before a column becomes `NOT NULL`. */
348
+ const fallback = (column: ColumnSpec): string => {
349
+ if (column.array) return `'{}'::${column.sqlType}`
350
+ if (column.jsonb) return `'{}'::jsonb`
351
+ switch (column.jsonType) {
352
+ case 'number':
353
+ case 'integer':
354
+ case 'bigint':
355
+ return '0'
356
+ case 'boolean':
357
+ return 'FALSE'
358
+ case 'date':
359
+ return 'now()'
360
+ default:
361
+ return `''::${column.sqlType}`
362
+ }
363
+ }
@@ -0,0 +1,11 @@
1
+ export * from './criteria.js'
2
+ export * from './diff.js'
3
+ export * from './introspect.js'
4
+ export * from './life-cycle.js'
5
+ export * from './marshal.js'
6
+ export * from './migrations.js'
7
+ export * from './name.js'
8
+ export * from './schema.js'
9
+ export * from './sql.js'
10
+ export * from './sync.js'
11
+ export * from './table.js'
@@ -0,0 +1,87 @@
1
+ import type { PoolClient } from 'pg'
2
+
3
+ import type { LiveColumn, LiveConstraint, LiveIndex, LiveTable } from '../types.js'
4
+
5
+ /**
6
+ * `pg_attribute` + `format_type` rather than `information_schema.columns`, because it
7
+ * returns one canonical type string with the typmod already baked in
8
+ * (`character varying(320)`). `information_schema` splits the same information across
9
+ * four columns and reports every array as `ARRAY`, which no comparison can use.
10
+ */
11
+ const COLUMNS = `
12
+ SELECT a.attname AS name,
13
+ format_type(a.atttypid, a.atttypmod) AS type,
14
+ a.attnotnull AS not_null,
15
+ pg_get_expr(d.adbin, d.adrelid) AS default_expr,
16
+ a.attidentity AS identity,
17
+ a.attgenerated AS generated,
18
+ a.attnum AS ordinal
19
+ FROM pg_attribute a
20
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
21
+ WHERE a.attrelid = to_regclass($1) AND a.attnum > 0 AND NOT a.attisdropped
22
+ ORDER BY a.attnum
23
+ `
24
+
25
+ const INDEXES = `
26
+ SELECT indexname AS name, indexdef AS definition
27
+ FROM pg_indexes
28
+ WHERE schemaname = $1 AND tablename = $2
29
+ `
30
+
31
+ const CONSTRAINTS = `
32
+ SELECT c.conname AS name, c.contype AS type, pg_get_constraintdef(c.oid) AS definition
33
+ FROM pg_constraint c
34
+ WHERE c.conrelid = to_regclass($1)
35
+ `
36
+
37
+ /** Read the table exactly as Postgres currently holds it. */
38
+ export const introspectTable = async (
39
+ client: PoolClient, schema: string, table: string, qualified: string
40
+ ): Promise<LiveTable> => {
41
+ const exists = await client.query<{ present: boolean }>(
42
+ 'SELECT to_regclass($1) IS NOT NULL AS present', [qualified]
43
+ )
44
+ if (exists.rows[0]?.present !== true) {
45
+ return { exists: false, columns: [], indexes: [], constraints: [] }
46
+ }
47
+
48
+ /**
49
+ * Sequential, not `Promise.all`: this is one checked out connection, and a connection
50
+ * runs one statement at a time. Overlapping them only queues them behind each other —
51
+ * and node-postgres deprecated tolerating it.
52
+ */
53
+ const columns = await client.query<LiveColumn>(COLUMNS, [qualified])
54
+ const indexes = await client.query<LiveIndex>(INDEXES, [schema, table])
55
+ const constraints = await client.query<LiveConstraint>(CONSTRAINTS, [qualified])
56
+
57
+ return {
58
+ exists: true,
59
+ columns: columns.rows.map(row => ({
60
+ name: row.name,
61
+ type: row.type,
62
+ notNull: (row as unknown as { not_null: boolean }).not_null,
63
+ defaultExpr: (row as unknown as { default_expr: string | null }).default_expr,
64
+ identity: row.identity ?? '',
65
+ generated: row.generated ?? '',
66
+ ordinal: row.ordinal
67
+ })),
68
+ indexes: indexes.rows,
69
+ constraints: constraints.rows
70
+ }
71
+ }
72
+
73
+ /** Count the rows a destructive step would lose, so the boot log can say how much. */
74
+ export const countNonNull = async (
75
+ client: PoolClient, qualified: string, column: string
76
+ ): Promise<number> => {
77
+ try {
78
+ const result = await client.query<{ count: string }>(
79
+ `SELECT count(*)::text AS count FROM ${qualified} WHERE "${column.replace(/"/g, '""')}" IS NOT NULL`
80
+ )
81
+
82
+ return parseInt(result.rows[0]?.count ?? '0', 10)
83
+ } catch {
84
+ /** Never let a diagnostic read break reconciliation. */
85
+ return -1
86
+ }
87
+ }
@@ -0,0 +1,155 @@
1
+ import type { BasicContext } from '@owlmeans/context'
2
+ import { MigrationStage, runMigrations } from '@owlmeans/resource'
3
+ import type { DbConfig, MigrationReport, ResourceRecord } from '@owlmeans/resource'
4
+ import type { PoolClient } from 'pg'
5
+
6
+ import { DEF_MIGRATIONS_TABLE, PgAutoSync } from '../consts.js'
7
+ import { getDeclaration } from '../declarations.js'
8
+ import { describePgError, pgErrorToResourceError } from '../errors.js'
9
+ import type {
10
+ PgRuntimeTable, PostgresDb, PostgresMeta, PostgresResource, TableSpec
11
+ } from '../types.js'
12
+ import { planForeignKeys, planSync } from './diff.js'
13
+ import { introspectTable } from './introspect.js'
14
+ import { makeMigrationStore } from './migrations.js'
15
+ import { pgTableName } from './name.js'
16
+ import { schemaToTableSpec } from './schema.js'
17
+ import { refOf, resolvePlaceholders } from './sql.js'
18
+ import { acquireLock, applyPlan, ensureSchema, releaseLock } from './sync.js'
19
+ import { specToTable } from './table.js'
20
+
21
+ export interface TableInit {
22
+ spec: TableSpec
23
+ /** The Drizzle table CRUD is built against. */
24
+ entity: PgRuntimeTable
25
+ reports: MigrationReport[]
26
+ }
27
+
28
+ /**
29
+ * Bring a resource's table to the shape its schema declares, then hand back everything the
30
+ * resource needs to query it. The Postgres counterpart of mongo's `initializeCollection`.
31
+ *
32
+ * The whole sequence runs inside a session level advisory lock keyed on the qualified table
33
+ * name, so replicas booting simultaneously converge one at a time instead of racing each
34
+ * other's DDL — a race mongo's converge-on-boot leaves open.
35
+ *
36
+ * Order is deliberate:
37
+ *
38
+ * 1. probe for the table
39
+ * 2. absent → *baseline* every registered migration; present → run the `pre` ones
40
+ * 3. reconcile structure against the schema
41
+ * 4. present → run the `post` migrations
42
+ * 5. queue foreign keys for after every resource has initialized
43
+ *
44
+ * Step 2 is what stops the two mechanisms colliding. On a fresh deployment the table is
45
+ * created directly to its final shape, so migrations that would have produced that shape
46
+ * are recorded as satisfied rather than replayed against a table that already matches.
47
+ */
48
+ export const initializeTable = async (
49
+ db: PostgresDb, config: DbConfig, resource: PostgresResource<ResourceRecord>,
50
+ context: BasicContext<any>, defer: (task: () => Promise<void>) => void
51
+ ): Promise<TableInit> => {
52
+ const declaration = getDeclaration(resource.alias)
53
+ const meta = (config.meta ?? {}) as PostgresMeta
54
+ const mode = meta.autoSync ?? PgAutoSync.Full
55
+
56
+ const spec = schemaToTableSpec(
57
+ resource.alias, resource.schema ?? declaration.schema, db.schema,
58
+ pgTableName(config, resource), mode !== PgAutoSync.Off, declaration.indexes
59
+ )
60
+ const entity = specToTable(spec)
61
+ const reports: MigrationReport[] = []
62
+
63
+ const client = await db.pool.connect()
64
+ try {
65
+ await acquireLock(client, spec.qualified)
66
+ await ensureSchema(client, spec.schema)
67
+
68
+ const resolve = (text: string): string => resolvePlaceholders(text, context, spec)
69
+ const ref = (alias?: string): string => refOf(context, spec, alias)
70
+ const store = makeMigrationStore(client, spec, DEF_MIGRATIONS_TABLE, resolve, ref)
71
+
72
+ const fresh = !(await introspectTable(client, spec.schema, spec.table, spec.qualified)).exists
73
+
74
+ reports.push(await runMigrations(resource.alias, declaration.migrations, store, fresh
75
+ ? { baseline: true }
76
+ : { stage: MigrationStage.Pre }))
77
+
78
+ if (spec.autoSync) {
79
+ /** Re-read: a `pre` migration may have reshaped exactly what the diff is about to compare. */
80
+ const live = await introspectTable(client, spec.schema, spec.table, spec.qualified)
81
+ const plan = planSync(spec, live, mode === PgAutoSync.Additive)
82
+ await applyPlan(client, spec, plan)
83
+ }
84
+
85
+ if (!fresh) {
86
+ reports.push(await runMigrations(
87
+ resource.alias, declaration.migrations, store, { stage: MigrationStage.Post }
88
+ ))
89
+ }
90
+
91
+ for (const report of reports) {
92
+ if (report.applied.length > 0) {
93
+ console.log(
94
+ `@owlmeans/postgres-resource: ${spec.qualified} applied ${report.stage} migrations —`
95
+ + ` ${report.applied.join(', ')}`
96
+ )
97
+ }
98
+ }
99
+ } finally {
100
+ await releaseLock(client, spec.qualified)
101
+ client.release()
102
+ }
103
+
104
+ if (spec.references.length > 0) {
105
+ defer(async () => { await applyForeignKeys(db, spec, context) })
106
+ }
107
+
108
+ return { spec, entity, reports }
109
+ }
110
+
111
+ /**
112
+ * Add the foreign keys the schema declares, skipping any Postgres already holds.
113
+ *
114
+ * Constraints are compared by name only. A key whose *definition* drifted has to be dropped
115
+ * by hand or in a migration: `ALTER TABLE ... DROP CONSTRAINT` on a foreign key is not a
116
+ * change worth making on a boot nobody is watching.
117
+ */
118
+ export const applyForeignKeys = async (
119
+ db: PostgresDb, spec: TableSpec, context: BasicContext<any>
120
+ ): Promise<void> => {
121
+ const client = await db.pool.connect()
122
+ try {
123
+ const statements = planForeignKeys(spec, context)
124
+ const live = await introspectTable(client, spec.schema, spec.table, spec.qualified)
125
+ if (!live.exists) {
126
+ return
127
+ }
128
+ const present = live.constraints.map(constraint => constraint.name)
129
+
130
+ for (const statement of statements) {
131
+ if (present.includes(statement.target)) {
132
+ continue
133
+ }
134
+ await apply(client, spec, statement.sql)
135
+ }
136
+ } finally {
137
+ client.release()
138
+ }
139
+ }
140
+
141
+ const apply = async (client: PoolClient, spec: TableSpec, statement: string): Promise<void> => {
142
+ try {
143
+ await client.query(statement)
144
+ } catch (error) {
145
+ const translated = pgErrorToResourceError(error)
146
+ /**
147
+ * A foreign key failing means live rows point at nothing. That's a data problem the
148
+ * boot can't fix, and refusing to start is better than starting with the constraint
149
+ * quietly missing.
150
+ */
151
+ throw Object.assign(translated, {
152
+ message: `${spec.qualified}: ${describePgError(error)} — statement: ${statement}`
153
+ })
154
+ }
155
+ }