@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,426 @@
1
+ import { UnsupportedArgumentError } from '@owlmeans/resource'
2
+ import type { AnySchema } from 'ajv'
3
+
4
+ import {
5
+ DEF_ID_DEFAULT, DEF_JSON_TYPE, DEF_SQL_TYPE, ID_FIELD, PG_KEYWORD, PgIndexMethod
6
+ } from '../consts.js'
7
+ import type {
8
+ ColumnJsonType, ColumnSpec, PgCheckSpec, PgIndexSpec, PgPropertyOverride, PgRootOverride,
9
+ PgReferenceSpec, PgUniqueSpec, TableSpec
10
+ } from '../types.js'
11
+ import { pgIdentifier, qualify, quoteIdent } from './name.js'
12
+
13
+ interface RawProperty {
14
+ type?: string | string[]
15
+ format?: string
16
+ enum?: unknown[]
17
+ items?: RawProperty
18
+ maxLength?: number
19
+ maximum?: number
20
+ minimum?: number
21
+ default?: unknown
22
+ nullable?: boolean
23
+ secure?: boolean
24
+ [PG_KEYWORD]?: PgPropertyOverride
25
+ }
26
+
27
+ interface RawSchema {
28
+ properties?: Record<string, RawProperty>
29
+ required?: string[]
30
+ allOf?: RawSchema[]
31
+ [PG_KEYWORD]?: PgRootOverride
32
+ }
33
+
34
+ const INT32_MAX = 2147483647
35
+
36
+ /**
37
+ * Normalize a Postgres type name to the spelling `format_type()` reports, so the drift
38
+ * comparison against a live table is an exact string match instead of a fuzzy one.
39
+ */
40
+ export const toFormatType = (type: string): string => {
41
+ const trimmed = type.trim().toLowerCase()
42
+ const match = /^([a-z0-9_ ]+?)\s*(\(([^)]*)\))?\s*(\[\])?$/.exec(trimmed)
43
+ if (match == null) {
44
+ return trimmed
45
+ }
46
+ const [, base, , args, array] = match
47
+ const aliases: Record<string, string> = {
48
+ int: 'integer', int4: 'integer', int2: 'smallint', int8: 'bigint', serial: 'integer',
49
+ bool: 'boolean', float4: 'real', float8: 'double precision', decimal: 'numeric',
50
+ varchar: 'character varying', char: 'character', bpchar: 'character',
51
+ timestamptz: 'timestamp with time zone', timetz: 'time with time zone',
52
+ timestamp: 'timestamp without time zone', time: 'time without time zone'
53
+ }
54
+ const resolved = aliases[base.trim()] ?? base.trim()
55
+ /** Postgres prints multi-argument typmods without spaces: `numeric(12,2)`. */
56
+ const suffix = args != null ? `(${args.split(',').map(part => part.trim()).join(',')})` : ''
57
+
58
+ return `${resolved}${suffix}${array ?? ''}`
59
+ }
60
+
61
+ const readOverride = (property: RawProperty): PgPropertyOverride => property[PG_KEYWORD] ?? {}
62
+
63
+ /**
64
+ * Nullability is decided in exactly one place and threaded down from there. Mongo's mapper
65
+ * recomputes it per branch and lost it twice — on `date-time` and on optional objects.
66
+ */
67
+ const isNullable = (property: RawProperty, isRequired: boolean): boolean => {
68
+ const override = readOverride(property)
69
+ if (override.nullable != null) {
70
+ return override.nullable
71
+ }
72
+ if (property.nullable === true) {
73
+ return true
74
+ }
75
+ if (Array.isArray(property.type) && property.type.includes('null')) {
76
+ return true
77
+ }
78
+
79
+ return !isRequired
80
+ }
81
+
82
+ const baseType = (property: RawProperty): string | undefined =>
83
+ Array.isArray(property.type) ? property.type.find(type => type !== 'null') : property.type
84
+
85
+ const scalarSqlType = (property: RawProperty): { sqlType: string, jsonType: ColumnJsonType } => {
86
+ const override = readOverride(property)
87
+ const type = baseType(property)
88
+
89
+ switch (type) {
90
+ case 'string':
91
+ switch (property.format) {
92
+ case 'date-time': return { sqlType: 'timestamp with time zone', jsonType: 'date' }
93
+ case 'date': return { sqlType: 'date', jsonType: 'date' }
94
+ case 'time': return { sqlType: 'time without time zone', jsonType: 'string' }
95
+ case 'uuid': return { sqlType: 'uuid', jsonType: 'string' }
96
+ case 'binary': return { sqlType: 'bytea', jsonType: 'binary' }
97
+ default: break
98
+ }
99
+ return property.maxLength != null
100
+ ? { sqlType: `character varying(${property.maxLength})`, jsonType: 'string' }
101
+ : { sqlType: DEF_SQL_TYPE, jsonType: 'string' }
102
+ case 'integer':
103
+ return property.maximum != null && property.maximum > INT32_MAX
104
+ ? { sqlType: 'bigint', jsonType: 'bigint' }
105
+ : { sqlType: 'integer', jsonType: 'integer' }
106
+ case 'number':
107
+ return override.precision != null
108
+ ? { sqlType: `numeric(${override.precision},${override.scale ?? 0})`, jsonType: 'number' }
109
+ : { sqlType: 'double precision', jsonType: 'number' }
110
+ case 'boolean':
111
+ return { sqlType: 'boolean', jsonType: 'boolean' }
112
+ case 'object':
113
+ /**
114
+ * The framework's date convention — `{ type: 'object', format: 'date-time' }`. Mongo's
115
+ * mapper broke twice on exactly this branch by dropping nullability, so nullability is
116
+ * decided by the caller, never here.
117
+ */
118
+ return property.format === 'date-time'
119
+ ? { sqlType: 'timestamp with time zone', jsonType: 'date' }
120
+ : { sqlType: DEF_JSON_TYPE, jsonType: 'object' }
121
+ default:
122
+ return { sqlType: DEF_JSON_TYPE, jsonType: 'unknown' }
123
+ }
124
+ }
125
+
126
+ const arraySqlType = (property: RawProperty): { sqlType: string, jsonType: ColumnJsonType, array: boolean } => {
127
+ const items = property.items
128
+ const itemType = items != null ? baseType(items) : undefined
129
+ /** Only scalar element types become Postgres arrays; anything else stays jsonb. */
130
+ if (items != null && itemType != null && ['string', 'integer', 'number', 'boolean'].includes(itemType)
131
+ && items.format == null && items.enum == null) {
132
+ const scalar = scalarSqlType(items)
133
+ return { sqlType: `${scalar.sqlType}[]`, jsonType: 'array', array: true }
134
+ }
135
+
136
+ return { sqlType: DEF_JSON_TYPE, jsonType: 'array', array: false }
137
+ }
138
+
139
+ const compileColumn = (
140
+ name: string, property: RawProperty, required: string[]
141
+ ): ColumnSpec => {
142
+ const override = readOverride(property)
143
+ const secure = property.secure === true
144
+ const type = baseType(property)
145
+ const nullable = isNullable(property, required.includes(name))
146
+
147
+ let sqlType: string
148
+ let jsonType: ColumnJsonType
149
+ let array = false
150
+
151
+ if (override.type != null) {
152
+ sqlType = override.type
153
+ jsonType = secure ? 'string' : scalarSqlType(property).jsonType
154
+ array = override.array === true || override.type.endsWith('[]')
155
+ } else if (secure) {
156
+ /**
157
+ * A secure field is stored as ciphertext, so its declared JSON type says nothing about
158
+ * its column. It's always unbounded text: `maxLength` would truncate the ciphertext,
159
+ * an enum CHECK would never match it, and jsonb would fail to parse it.
160
+ */
161
+ sqlType = DEF_SQL_TYPE
162
+ jsonType = 'string'
163
+ } else if (type === 'array') {
164
+ const resolved = arraySqlType(property)
165
+ sqlType = resolved.sqlType
166
+ jsonType = resolved.jsonType
167
+ array = resolved.array
168
+ } else {
169
+ const resolved = scalarSqlType(property)
170
+ sqlType = resolved.sqlType
171
+ jsonType = resolved.jsonType
172
+ }
173
+
174
+ if (override.length != null) {
175
+ sqlType = `character varying(${override.length})`
176
+ }
177
+ if (override.array === true && !array && !sqlType.endsWith('[]')) {
178
+ sqlType = `${sqlType}[]`
179
+ array = true
180
+ }
181
+ if (override.jsonb === true) {
182
+ sqlType = DEF_JSON_TYPE
183
+ jsonType = jsonType === 'array' ? 'array' : 'object'
184
+ array = false
185
+ }
186
+
187
+ const formatted = toFormatType(sqlType)
188
+ const isJsonb = formatted === 'jsonb' || formatted === 'json'
189
+
190
+ const column: ColumnSpec = {
191
+ property: name,
192
+ /** No implicit snake_casing — a silent rename is a silent DROP plus ADD. */
193
+ column: pgIdentifier(override.column ?? name),
194
+ sqlType: formatted,
195
+ jsonType,
196
+ notNull: override.nullable === false ? true : !nullable,
197
+ primaryKey: override.primaryKey === true,
198
+ secure,
199
+ jsonb: isJsonb,
200
+ array,
201
+ managed: override.managed !== false,
202
+ ...(override.using != null ? { using: override.using } : {}),
203
+ ...(override.comment != null ? { comment: override.comment } : {})
204
+ }
205
+
206
+ if (override.defaultRaw != null) {
207
+ column.defaultRaw = override.defaultRaw
208
+ } else if (override.default !== undefined) {
209
+ column.defaultLiteral = override.default
210
+ } else if (property.default !== undefined && !isJsonb && !array) {
211
+ /** Non-scalar defaults stay in `getDefaults()` only — they'd need casting in DDL. */
212
+ column.defaultLiteral = property.default as string | number | boolean | null
213
+ }
214
+
215
+ return column
216
+ }
217
+
218
+ const collectProperties = (schema: RawSchema): { properties: Record<string, RawProperty>, required: string[] } => {
219
+ const properties: Record<string, RawProperty> = { ...schema.properties }
220
+ const required: string[] = [...(schema.required ?? [])]
221
+ /** `allOf` composition is used across the framework's schemas — flatten it like mongo does. */
222
+ for (const part of schema.allOf ?? []) {
223
+ const nested = collectProperties(part)
224
+ Object.assign(properties, nested.properties)
225
+ required.push(...nested.required)
226
+ }
227
+
228
+ return { properties, required }
229
+ }
230
+
231
+ /**
232
+ * Compile a resource's AJV schema into the table specification that drives both DDL
233
+ * emission and drift detection.
234
+ *
235
+ * `extraIndexes` carries what `resource.index()` declared. It's compiled here rather than
236
+ * merged afterwards so chained declarations get the same property-to-column mapping and
237
+ * the same generated names as schema-borne ones.
238
+ *
239
+ * @throws {UnsupportedArgumentError} when an override asks for something unrepresentable.
240
+ */
241
+ export const schemaToTableSpec = (
242
+ alias: string, schema: AnySchema | undefined, pgSchema: string, table: string,
243
+ autoSync: boolean, extraIndexes: PgIndexSpec[] = []
244
+ ): TableSpec => {
245
+ const raw = (schema ?? {}) as RawSchema
246
+ const root = raw[PG_KEYWORD] ?? {}
247
+ const { properties, required } = collectProperties(raw)
248
+
249
+ const columns: ColumnSpec[] = []
250
+ const uniques: PgUniqueSpec[] = [...(root.unique ?? [])]
251
+ const checks: PgCheckSpec[] = [...(root.checks ?? [])]
252
+ const indexes: PgIndexSpec[] = [...(root.indexes ?? []), ...extraIndexes]
253
+ const references: PgReferenceSpec[] = []
254
+
255
+ const resolvedTable = pgIdentifier(root.table ?? table)
256
+ const resolvedSchema = pgIdentifier(root.schema ?? pgSchema)
257
+
258
+ for (const [name, property] of Object.entries(properties)) {
259
+ const column = compileColumn(name, property, required)
260
+ columns.push(column)
261
+
262
+ const override = readOverride(property)
263
+
264
+ if (override.unique != null && override.unique !== false) {
265
+ if (column.secure) {
266
+ /**
267
+ * Encryption uses a managed nonce, so two identical plaintexts encrypt to different
268
+ * ciphertexts — a unique constraint on the column would never collide, silently.
269
+ */
270
+ throw new UnsupportedArgumentError(`secure-unique:${name}`)
271
+ }
272
+ uniques.push({
273
+ columns: [name],
274
+ ...(typeof override.unique === 'string' ? { name: override.unique } : {})
275
+ })
276
+ }
277
+
278
+ if (override.index != null && override.index !== false) {
279
+ if (column.secure) {
280
+ console.warn(
281
+ `@owlmeans/postgres-resource: index on secure column "${alias}.${name}" — encryption`
282
+ + ' is non-deterministic, so equality lookups through it will never match.'
283
+ )
284
+ }
285
+ const specs = override.index === true
286
+ ? [{ columns: [name] }]
287
+ : Array.isArray(override.index) ? override.index : [override.index]
288
+ indexes.push(...specs.map(spec => ({ ...spec, columns: spec.columns ?? [name] })))
289
+ }
290
+
291
+ if (override.references != null) {
292
+ references.push({
293
+ ...override.references,
294
+ property: name,
295
+ column: override.references.column ?? ID_FIELD,
296
+ name: pgIdentifier(override.references.name ?? `${resolvedTable}_${column.column}_fkey`)
297
+ })
298
+ }
299
+
300
+ if (override.check != null) {
301
+ checks.push({
302
+ name: `${resolvedTable}_${column.column}_check`,
303
+ expression: override.check.replace(/\{\{col\}\}/g, quoteIdent(column.column))
304
+ })
305
+ }
306
+
307
+ /** A string enum becomes a CHECK — a native PG enum can't drop values and can't be altered in a transaction. */
308
+ if (property.enum != null && !column.secure && override.type == null
309
+ && baseType(property) === 'string' && property.enum.every(value => typeof value === 'string')) {
310
+ const values = (property.enum as string[]).map(value => `'${value.replace(/'/g, "''")}'`).join(', ')
311
+ const predicate = column.notNull
312
+ ? `${quoteIdent(column.column)} IN (${values})`
313
+ : `${quoteIdent(column.column)} IS NULL OR ${quoteIdent(column.column)} IN (${values})`
314
+ checks.push({ name: `${resolvedTable}_${column.column}_enum`, expression: predicate })
315
+ }
316
+ }
317
+
318
+ const byProperty: Record<string, ColumnSpec> = {}
319
+ const byColumn: Record<string, ColumnSpec> = {}
320
+ for (const column of columns) {
321
+ byProperty[column.property] = column
322
+ byColumn[column.column] = column
323
+ }
324
+
325
+ let primaryKey: string[] = []
326
+ if (root.primaryKey != null && root.primaryKey.length > 0) {
327
+ primaryKey = root.primaryKey.map(property => {
328
+ const column = byProperty[property]
329
+ if (column == null) {
330
+ throw new UnsupportedArgumentError(`primary-key:${property}`)
331
+ }
332
+ column.notNull = true
333
+
334
+ return column.column
335
+ })
336
+ } else {
337
+ const explicit = columns.filter(column => column.primaryKey)
338
+ if (explicit.length > 0) {
339
+ primaryKey = explicit.map(column => {
340
+ column.notNull = true
341
+ return column.column
342
+ })
343
+ } else {
344
+ /**
345
+ * Every OwlMeans record is addressed by `id`, so the column is synthesized when the
346
+ * schema doesn't declare it — `create()` and `load()` both assume it exists.
347
+ */
348
+ let id = byProperty[ID_FIELD]
349
+ if (id == null) {
350
+ id = {
351
+ property: ID_FIELD, column: ID_FIELD, sqlType: DEF_SQL_TYPE, jsonType: 'string',
352
+ notNull: true, primaryKey: true, secure: false, jsonb: false, array: false,
353
+ managed: true, defaultRaw: DEF_ID_DEFAULT
354
+ }
355
+ columns.unshift(id)
356
+ byProperty[ID_FIELD] = id
357
+ byColumn[ID_FIELD] = id
358
+ } else {
359
+ id.notNull = true
360
+ id.primaryKey = true
361
+ if (id.defaultRaw == null && id.defaultLiteral === undefined) {
362
+ id.defaultRaw = id.sqlType === 'uuid' ? 'gen_random_uuid()' : DEF_ID_DEFAULT
363
+ }
364
+ }
365
+ primaryKey = [id.column]
366
+ }
367
+ }
368
+
369
+ /** Index and unique specs address properties; map them onto physical columns once, here. */
370
+ const mapColumns = (names: string[]): string[] => names.map(name => {
371
+ const column = byProperty[name]
372
+ if (column == null) {
373
+ throw new UnsupportedArgumentError(`unknown-property:${name}`)
374
+ }
375
+
376
+ return column.column
377
+ })
378
+
379
+ const resolvedIndexes: PgIndexSpec[] = indexes.map(spec => {
380
+ const list = spec.columns == null
381
+ ? []
382
+ : mapColumns(Array.isArray(spec.columns) ? spec.columns : [spec.columns])
383
+ const suffix = spec.unique === true ? 'uq' : 'idx'
384
+
385
+ return {
386
+ ...spec,
387
+ columns: list,
388
+ method: spec.method ?? PgIndexMethod.BTree,
389
+ name: pgIdentifier(spec.name ?? `${resolvedTable}_${list.join('_')}_${suffix}`)
390
+ }
391
+ })
392
+
393
+ const resolvedUniques: PgUniqueSpec[] = uniques.map(spec => {
394
+ const list = mapColumns(spec.columns)
395
+
396
+ return { columns: list, name: pgIdentifier(spec.name ?? `${resolvedTable}_${list.join('_')}_key`) }
397
+ })
398
+
399
+ return {
400
+ alias,
401
+ schema: resolvedSchema,
402
+ table: resolvedTable,
403
+ qualified: qualify(resolvedSchema, resolvedTable),
404
+ columns,
405
+ byProperty,
406
+ byColumn,
407
+ primaryKey,
408
+ uniques: resolvedUniques,
409
+ checks: checks.map(check => ({ ...check, name: pgIdentifier(check.name ?? `${resolvedTable}_check`) })),
410
+ indexes: resolvedIndexes,
411
+ references,
412
+ unmanaged: [
413
+ ...(root.unmanaged ?? []).map(name => byProperty[name]?.column ?? pgIdentifier(name)),
414
+ ...columns.filter(column => !column.managed).map(column => column.column)
415
+ ],
416
+ autoSync: root.autoSync ?? autoSync,
417
+ ...(root.comment != null ? { comment: root.comment } : {})
418
+ }
419
+ }
420
+
421
+ /**
422
+ * AJV keyword registration for consumers running in strict mode. The mapper reads the raw
423
+ * schema object and never validates through AJV, so this is purely to stop strict mode
424
+ * rejecting a schema that carries `pg` overrides.
425
+ */
426
+ export const pgKeyword = { keyword: PG_KEYWORD, valid: true }
Binary file
@@ -0,0 +1,106 @@
1
+ import type { PoolClient } from 'pg'
2
+
3
+ import { PgErrorCode } from '../consts.js'
4
+ import { PostgresCastRequired, PostgresSyncError, describePgError, pgErrorToResourceError } from '../errors.js'
5
+ import type { DdlPlan, TableSpec } from '../types.js'
6
+ import { countNonNull } from './introspect.js'
7
+ import { advisoryKey, quoteIdent } from './name.js'
8
+
9
+ /**
10
+ * Codes that mean "the cast is legal, the data isn't": a `text` column holding `'a'` retyped to
11
+ * `integer`, a value too wide for the new length, a number past the new range. Postgres refuses
12
+ * each of these rather than truncating, and the remedy is the same one a refused cast needs — so
13
+ * they are only read as a cast problem here, inside DDL. On the CRUD path the identical code means
14
+ * a caller passed a bad value, which is a different bug with a different fix.
15
+ */
16
+ const CAST_DATA_CODES: string[] = [
17
+ PgErrorCode.InvalidTextRepresentation,
18
+ PgErrorCode.StringDataRightTruncation,
19
+ PgErrorCode.NumericValueOutOfRange
20
+ ]
21
+
22
+ /**
23
+ * Serialize initialization across replicas. A session level lock, not `xact`, because
24
+ * migrations run in their own transactions inside the critical section.
25
+ */
26
+ export const acquireLock = async (client: PoolClient, qualified: string): Promise<void> => {
27
+ const [first, second] = advisoryKey(qualified)
28
+ await client.query('SELECT pg_advisory_lock($1, $2)', [first, second])
29
+ }
30
+
31
+ export const releaseLock = async (client: PoolClient, qualified: string): Promise<void> => {
32
+ const [first, second] = advisoryKey(qualified)
33
+ try {
34
+ await client.query('SELECT pg_advisory_unlock($1, $2)', [first, second])
35
+ } catch {
36
+ /** Releasing the session drops the lock anyway — never mask the original failure. */
37
+ }
38
+ }
39
+
40
+ export const ensureSchema = async (client: PoolClient, schema: string): Promise<void> => {
41
+ try {
42
+ await client.query(`CREATE SCHEMA IF NOT EXISTS ${quoteIdent(schema)}`)
43
+ } catch (error) {
44
+ throw pgErrorToResourceError(error)
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Apply a reconciliation plan in a single transaction.
50
+ *
51
+ * Postgres DDL is transactional, so a plan that fails partway leaves the table exactly as
52
+ * it was. That property is what makes converging without confirmation prompts tolerable —
53
+ * the table is either fully converged or untouched, never half migrated.
54
+ *
55
+ * @throws {PostgresCastRequired} Postgres refused an automatic cast.
56
+ * @throws {PostgresSyncError} any other statement failed — the message names the statement.
57
+ */
58
+ export const applyPlan = async (
59
+ client: PoolClient, spec: TableSpec, plan: DdlPlan
60
+ ): Promise<DdlPlan> => {
61
+ if (plan.statements.length < 1) {
62
+ return plan
63
+ }
64
+
65
+ /** Read what a drop would cost before the transaction opens, so the log can say it. */
66
+ for (const statement of plan.statements) {
67
+ if (statement.destructive === true) {
68
+ statement.affected = await countNonNull(client, spec.qualified, statement.target)
69
+ }
70
+ }
71
+
72
+ await client.query('BEGIN')
73
+ let current = ''
74
+ try {
75
+ for (const statement of plan.statements) {
76
+ current = statement.sql
77
+ if (statement.destructive === true && (statement.affected ?? 0) > 0) {
78
+ console.warn(
79
+ `@owlmeans/postgres-resource: dropping ${spec.qualified}.${statement.target} —`
80
+ + ` ${statement.affected} row(s) hold a value. Declare it under \`pg.unmanaged\``
81
+ + ' or set `pg: { managed: false }` to keep it.'
82
+ )
83
+ }
84
+ await client.query(statement.sql)
85
+ }
86
+ await client.query('COMMIT')
87
+ } catch (error) {
88
+ await client.query('ROLLBACK').catch(() => undefined)
89
+ const translated = pgErrorToResourceError(error)
90
+ const code = (error as { code?: string } | null)?.code
91
+ if (translated instanceof PostgresCastRequired || (code != null && CAST_DATA_CODES.includes(code))) {
92
+ const failure = new PostgresCastRequired(
93
+ `${spec.qualified}: ${describePgError(error)} — statement: ${current}.`
94
+ + ' Declare `pg: { using: \'<expr>\' }` on the property, or perform the change in a'
95
+ + ' `pre` migration so reconciliation observes no drift.'
96
+ )
97
+ failure.cause = error
98
+ throw failure
99
+ }
100
+ const failure = new PostgresSyncError(`${spec.qualified}: ${describePgError(error)} — statement: ${current}`)
101
+ failure.cause = error
102
+ throw failure
103
+ }
104
+
105
+ return plan
106
+ }
@@ -0,0 +1,76 @@
1
+ import { sql } from 'drizzle-orm'
2
+ import { customType, index, pgSchema, primaryKey, uniqueIndex } from 'drizzle-orm/pg-core'
3
+
4
+ import { PgIndexMethod } from '../consts.js'
5
+ import type { PgRuntimeTable, TableSpec } from '../types.js'
6
+
7
+ /**
8
+ * One universal column builder.
9
+ *
10
+ * Drizzle's typed builders (`text()`, `integer()`, ...) exist to drive compile time
11
+ * inference from a statically declared schema. Our tables are compiled at runtime from
12
+ * JSON Schema, so there's nothing to infer and a per-type switch would buy nothing but a
13
+ * mapping to keep in sync. `customType` lets the already-canonical `sqlType` string
14
+ * through verbatim, and `getSQLType()` reads it straight back for the drift cross-check.
15
+ *
16
+ * Marshalling is deliberately identity here — coercion lives in `marshal.ts`, which is
17
+ * driven by the same spec and also serves the raw-SQL path that never touches Drizzle.
18
+ */
19
+ const pgRaw = customType<{ data: unknown, driverData: unknown, config: { sqlType: string } }>({
20
+ dataType: config => config?.sqlType ?? 'text'
21
+ })
22
+
23
+ /**
24
+ * Build the Drizzle table used for CRUD query construction. Structure DDL is emitted from
25
+ * the {@link TableSpec} directly — Drizzle exposes no runtime DDL generator (that lives in
26
+ * drizzle-kit, which would be a second owner of the same tables).
27
+ */
28
+ export const specToTable = (spec: TableSpec): PgRuntimeTable => {
29
+ const namespace = pgSchema(spec.schema)
30
+ const columns: Record<string, any> = {}
31
+
32
+ for (const column of spec.columns) {
33
+ let builder: any = pgRaw(column.column, { sqlType: column.sqlType })
34
+ if (column.notNull) {
35
+ builder = builder.notNull()
36
+ }
37
+ if (column.defaultRaw != null) {
38
+ builder = builder.default(sql.raw(column.defaultRaw))
39
+ } else if (column.defaultLiteral !== undefined) {
40
+ builder = builder.default(column.defaultLiteral)
41
+ }
42
+ /** Composite keys are declared in the extra-config callback instead. */
43
+ if (column.primaryKey && spec.primaryKey.length === 1) {
44
+ builder = builder.primaryKey()
45
+ }
46
+ columns[column.property] = builder
47
+ }
48
+
49
+ return namespace.table(spec.table, columns, (table: any) => [
50
+ ...spec.indexes
51
+ .filter(entry => entry.columns != null && entry.columns.length > 0 && entry.expression == null)
52
+ .map(entry => {
53
+ const properties = (entry.columns as string[])
54
+ .map(name => spec.byColumn[name]?.property)
55
+ .filter((name): name is string => name != null && table[name] != null)
56
+ const builder = entry.unique === true ? uniqueIndex(entry.name!) : index(entry.name!)
57
+
58
+ /**
59
+ * Both `using` and `primaryKey` want a non-empty tuple of statically known columns.
60
+ * Nothing here is statically known — the columns were compiled a few lines above —
61
+ * so the tuple shape is asserted rather than proven.
62
+ */
63
+ return builder.using(
64
+ entry.method ?? PgIndexMethod.BTree,
65
+ ...properties.map(name => table[name]) as [any, ...any[]]
66
+ )
67
+ }),
68
+ ...(spec.primaryKey.length > 1
69
+ ? [primaryKey({
70
+ columns: spec.primaryKey
71
+ .map(name => table[spec.byColumn[name]?.property ?? name])
72
+ .filter((column: unknown) => column != null) as [any, ...any[]]
73
+ })]
74
+ : [])
75
+ ]) as PgRuntimeTable
76
+ }