@owlmeans/postgres-resource 0.1.18-rc.41 → 0.1.18-rc.43

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 (171) hide show
  1. package/README.md +13 -13
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/postgres-resource/SKILL.md +2 -2
  4. package/build/consts.d.ts +9 -0
  5. package/build/consts.d.ts.map +1 -1
  6. package/build/consts.js +6 -0
  7. package/build/consts.js.map +1 -1
  8. package/build/declarations/types.d.ts +12 -0
  9. package/build/declarations/types.d.ts.map +1 -0
  10. package/build/declarations/types.js +2 -0
  11. package/build/declarations/types.js.map +1 -0
  12. package/build/declarations.d.ts +6 -9
  13. package/build/declarations.d.ts.map +1 -1
  14. package/build/declarations.js +25 -15
  15. package/build/declarations.js.map +1 -1
  16. package/build/errors.d.ts +0 -20
  17. package/build/errors.d.ts.map +1 -1
  18. package/build/errors.js +1 -111
  19. package/build/errors.js.map +1 -1
  20. package/build/index.d.ts +3 -0
  21. package/build/index.d.ts.map +1 -1
  22. package/build/index.js +1 -0
  23. package/build/index.js.map +1 -1
  24. package/build/pg-error/types.d.ts +24 -0
  25. package/build/pg-error/types.d.ts.map +1 -0
  26. package/build/pg-error/types.js +2 -0
  27. package/build/pg-error/types.js.map +1 -0
  28. package/build/pg-error.d.ts +4 -0
  29. package/build/pg-error.d.ts.map +1 -0
  30. package/build/pg-error.js +100 -0
  31. package/build/pg-error.js.map +1 -0
  32. package/build/resource.d.ts +1 -1
  33. package/build/resource.d.ts.map +1 -1
  34. package/build/resource.js +15 -11
  35. package/build/resource.js.map +1 -1
  36. package/build/types.d.ts +6 -1
  37. package/build/types.d.ts.map +1 -1
  38. package/build/types.local.d.ts +14 -0
  39. package/build/types.local.d.ts.map +1 -0
  40. package/build/types.local.js +2 -0
  41. package/build/types.local.js.map +1 -0
  42. package/build/utils/consts.local.d.ts +35 -0
  43. package/build/utils/consts.local.d.ts.map +1 -0
  44. package/build/utils/consts.local.js +63 -0
  45. package/build/utils/consts.local.js.map +1 -0
  46. package/build/utils/criteria/types.d.ts +31 -0
  47. package/build/utils/criteria/types.d.ts.map +1 -0
  48. package/build/utils/criteria/types.js +2 -0
  49. package/build/utils/criteria/types.js.map +1 -0
  50. package/build/utils/criteria.d.ts +3 -27
  51. package/build/utils/criteria.d.ts.map +1 -1
  52. package/build/utils/criteria.js +88 -107
  53. package/build/utils/criteria.js.map +1 -1
  54. package/build/utils/diff/types.d.ts +40 -0
  55. package/build/utils/diff/types.d.ts.map +1 -0
  56. package/build/utils/diff/types.js +2 -0
  57. package/build/utils/diff/types.js.map +1 -0
  58. package/build/utils/diff.d.ts +5 -35
  59. package/build/utils/diff.d.ts.map +1 -1
  60. package/build/utils/diff.js +321 -343
  61. package/build/utils/diff.js.map +1 -1
  62. package/build/utils/index.d.ts +10 -0
  63. package/build/utils/index.d.ts.map +1 -1
  64. package/build/utils/index.js.map +1 -1
  65. package/build/utils/introspect/types.d.ts +9 -0
  66. package/build/utils/introspect/types.d.ts.map +1 -0
  67. package/build/utils/introspect/types.js +2 -0
  68. package/build/utils/introspect/types.js.map +1 -0
  69. package/build/utils/introspect.d.ts +3 -3
  70. package/build/utils/introspect.d.ts.map +1 -1
  71. package/build/utils/introspect.js +42 -67
  72. package/build/utils/introspect.js.map +1 -1
  73. package/build/utils/life-cycle/types.d.ts +37 -0
  74. package/build/utils/life-cycle/types.d.ts.map +1 -0
  75. package/build/utils/life-cycle/types.js +2 -0
  76. package/build/utils/life-cycle/types.js.map +1 -0
  77. package/build/utils/life-cycle.d.ts +3 -38
  78. package/build/utils/life-cycle.d.ts.map +1 -1
  79. package/build/utils/life-cycle.js +90 -107
  80. package/build/utils/life-cycle.js.map +1 -1
  81. package/build/utils/marshal/types.d.ts +39 -0
  82. package/build/utils/marshal/types.d.ts.map +1 -0
  83. package/build/utils/marshal/types.js +2 -0
  84. package/build/utils/marshal/types.js.map +1 -0
  85. package/build/utils/marshal.d.ts +4 -32
  86. package/build/utils/marshal.d.ts.map +1 -1
  87. package/build/utils/marshal.js +124 -141
  88. package/build/utils/marshal.js.map +1 -1
  89. package/build/utils/migrations.d.ts.map +1 -1
  90. package/build/utils/migrations.js +41 -36
  91. package/build/utils/migrations.js.map +1 -1
  92. package/build/utils/name/types.d.ts +43 -0
  93. package/build/utils/name/types.d.ts.map +1 -0
  94. package/build/utils/name/types.js +2 -0
  95. package/build/utils/name/types.js.map +1 -0
  96. package/build/utils/name.d.ts +6 -35
  97. package/build/utils/name.d.ts.map +1 -1
  98. package/build/utils/name.js +40 -59
  99. package/build/utils/name.js.map +1 -1
  100. package/build/utils/schema/types.d.ts +22 -0
  101. package/build/utils/schema/types.d.ts.map +1 -0
  102. package/build/utils/schema/types.js +2 -0
  103. package/build/utils/schema/types.js.map +1 -0
  104. package/build/utils/schema.d.ts +4 -24
  105. package/build/utils/schema.d.ts.map +1 -1
  106. package/build/utils/schema.js +341 -352
  107. package/build/utils/schema.js.map +1 -1
  108. package/build/utils/sql/types.d.ts +25 -0
  109. package/build/utils/sql/types.d.ts.map +1 -0
  110. package/build/utils/sql/types.js +2 -0
  111. package/build/utils/sql/types.js.map +1 -0
  112. package/build/utils/sql.d.ts +5 -27
  113. package/build/utils/sql.d.ts.map +1 -1
  114. package/build/utils/sql.js +0 -0
  115. package/build/utils/sql.js.map +1 -1
  116. package/build/utils/sync/types.d.ts +25 -0
  117. package/build/utils/sync/types.d.ts.map +1 -0
  118. package/build/utils/sync/types.js +2 -0
  119. package/build/utils/sync/types.js.map +1 -0
  120. package/build/utils/sync.d.ts +2 -19
  121. package/build/utils/sync.d.ts.map +1 -1
  122. package/build/utils/sync.js +67 -84
  123. package/build/utils/sync.js.map +1 -1
  124. package/build/utils/types.d.ts +18 -0
  125. package/build/utils/types.d.ts.map +1 -0
  126. package/build/utils/types.js +2 -0
  127. package/build/utils/types.js.map +1 -0
  128. package/build/utils/types.local.d.ts +33 -0
  129. package/build/utils/types.local.d.ts.map +1 -0
  130. package/build/utils/types.local.js +2 -0
  131. package/build/utils/types.local.js.map +1 -0
  132. package/package.json +14 -13
  133. package/src/consts.ts +7 -0
  134. package/src/declarations/types.ts +12 -0
  135. package/src/declarations.ts +30 -23
  136. package/src/errors.ts +1 -131
  137. package/src/index.ts +3 -0
  138. package/src/pg-error/types.ts +23 -0
  139. package/src/pg-error.ts +114 -0
  140. package/src/resource.ts +20 -24
  141. package/src/types.local.ts +16 -0
  142. package/src/types.ts +8 -4
  143. package/src/utils/consts.local.ts +71 -0
  144. package/src/utils/criteria/types.ts +32 -0
  145. package/src/utils/criteria.ts +99 -129
  146. package/src/utils/diff/types.ts +41 -0
  147. package/src/utils/diff.ts +331 -348
  148. package/src/utils/index.ts +10 -0
  149. package/src/utils/introspect/types.ts +9 -0
  150. package/src/utils/introspect.ts +54 -79
  151. package/src/utils/life-cycle/types.ts +41 -0
  152. package/src/utils/life-cycle.ts +108 -134
  153. package/src/utils/marshal/types.ts +40 -0
  154. package/src/utils/marshal.ts +134 -147
  155. package/src/utils/migrations.ts +39 -33
  156. package/src/utils/name/types.ts +44 -0
  157. package/src/utils/name.ts +49 -63
  158. package/src/utils/schema/types.ts +26 -0
  159. package/src/utils/schema.ts +366 -397
  160. package/src/utils/sql/types.ts +25 -0
  161. package/src/utils/sql.ts +0 -0
  162. package/src/utils/sync/types.ts +25 -0
  163. package/src/utils/sync.ts +65 -83
  164. package/src/utils/types.local.ts +35 -0
  165. package/src/utils/types.ts +19 -0
  166. package/tests/criteria.spec.ts +4 -1
  167. package/tests/diff.spec.ts +28 -1
  168. package/tests/errors.spec.ts +4 -3
  169. package/tests/name.spec.ts +5 -3
  170. package/tests/schema.spec.ts +3 -1
  171. package/tests/sql.spec.ts +20 -22
@@ -1,380 +1,369 @@
1
1
  import { UnsupportedArgumentError } from '@owlmeans/resource';
2
+ import { logger } from '@owlmeans/log';
2
3
  import { DEF_ID_DEFAULT, DEF_JSON_TYPE, DEF_SQL_TYPE, ID_FIELD, PG_KEYWORD, PgIndexMethod } from '../consts.js';
3
- import { pgIdentifier, qualify, quoteIdent } from './name.js';
4
- const INT32_MAX = 2147483647;
5
- /**
6
- * Normalize a Postgres type name to the spelling `format_type()` reports, so the drift
7
- * comparison against a live table is an exact string match instead of a fuzzy one.
8
- */
9
- export const toFormatType = (type) => {
10
- const trimmed = type.trim().toLowerCase();
11
- const match = /^([a-z0-9_ ]+?)\s*(\(([^)]*)\))?\s*(\[\])?$/.exec(trimmed);
12
- if (match == null) {
13
- return trimmed;
14
- }
15
- const [, base, , args, array] = match;
16
- const aliases = {
17
- int: 'integer', int4: 'integer', int2: 'smallint', int8: 'bigint', serial: 'integer',
18
- bool: 'boolean', float4: 'real', float8: 'double precision', decimal: 'numeric',
19
- varchar: 'character varying', char: 'character', bpchar: 'character',
20
- timestamptz: 'timestamp with time zone', timetz: 'time with time zone',
21
- timestamp: 'timestamp without time zone', time: 'time without time zone'
22
- };
23
- const resolved = aliases[base.trim()] ?? base.trim();
24
- /** Postgres prints multi-argument typmods without spaces: `numeric(12,2)`. */
25
- const suffix = args != null ? `(${args.split(',').map(part => part.trim()).join(',')})` : '';
26
- return `${resolved}${suffix}${array ?? ''}`;
27
- };
28
- const readOverride = (property) => property[PG_KEYWORD] ?? {};
29
- /**
30
- * Nullability is decided in exactly one place and threaded down from there. Mongo's mapper
31
- * recomputes it per branch and lost it twice — on `date-time` and on optional objects.
32
- */
33
- const isNullable = (property, isRequired) => {
34
- const override = readOverride(property);
35
- if (override.nullable != null) {
36
- return override.nullable;
37
- }
38
- if (property.nullable === true) {
39
- return true;
40
- }
41
- if (Array.isArray(property.type) && property.type.includes('null')) {
42
- return true;
43
- }
44
- return !isRequired;
45
- };
46
- const baseType = (property) => Array.isArray(property.type) ? property.type.find(type => type !== 'null') : property.type;
47
- const scalarSqlType = (property) => {
48
- const override = readOverride(property);
49
- const type = baseType(property);
50
- switch (type) {
51
- case 'string':
52
- switch (property.format) {
53
- case 'date-time': return { sqlType: 'timestamp with time zone', jsonType: 'date' };
54
- case 'date': return { sqlType: 'date', jsonType: 'date' };
55
- case 'time': return { sqlType: 'time without time zone', jsonType: 'string' };
56
- case 'uuid': return { sqlType: 'uuid', jsonType: 'string' };
57
- case 'binary': return { sqlType: 'bytea', jsonType: 'binary' };
58
- default: break;
59
- }
60
- return property.maxLength != null
61
- ? { sqlType: `character varying(${property.maxLength})`, jsonType: 'string' }
62
- : { sqlType: DEF_SQL_TYPE, jsonType: 'string' };
63
- case 'integer':
64
- return property.maximum != null && property.maximum > INT32_MAX
65
- ? { sqlType: 'bigint', jsonType: 'bigint' }
66
- : { sqlType: 'integer', jsonType: 'integer' };
67
- case 'number':
68
- return override.precision != null
69
- ? { sqlType: `numeric(${override.precision},${override.scale ?? 0})`, jsonType: 'number' }
70
- : { sqlType: 'double precision', jsonType: 'number' };
71
- case 'boolean':
72
- return { sqlType: 'boolean', jsonType: 'boolean' };
73
- case 'object':
74
- /**
75
- * The framework's date convention — `{ type: 'object', format: 'date-time' }`. Mongo's
76
- * mapper broke twice on exactly this branch by dropping nullability, so nullability is
77
- * decided by the caller, never here.
78
- */
79
- return property.format === 'date-time'
80
- ? { sqlType: 'timestamp with time zone', jsonType: 'date' }
81
- : { sqlType: DEF_JSON_TYPE, jsonType: 'object' };
82
- default:
83
- return { sqlType: DEF_JSON_TYPE, jsonType: 'unknown' };
84
- }
85
- };
86
- const arraySqlType = (property) => {
87
- const items = property.items;
88
- const itemType = items != null ? baseType(items) : undefined;
89
- /** Only scalar element types become Postgres arrays; anything else stays jsonb. */
90
- if (items != null && itemType != null && ['string', 'integer', 'number', 'boolean'].includes(itemType)
91
- && items.format == null && items.enum == null) {
92
- const scalar = scalarSqlType(items);
93
- return { sqlType: `${scalar.sqlType}[]`, jsonType: 'array', array: true };
94
- }
95
- return { sqlType: DEF_JSON_TYPE, jsonType: 'array', array: false };
96
- };
97
- const compileColumn = (name, property, required) => {
98
- const override = readOverride(property);
99
- const secure = property.secure === true;
100
- const type = baseType(property);
101
- const nullable = isNullable(property, required.includes(name));
102
- let sqlType;
103
- let jsonType;
104
- let array = false;
105
- if (override.type != null) {
106
- sqlType = override.type;
107
- jsonType = secure ? 'string' : scalarSqlType(property).jsonType;
108
- array = override.array === true || override.type.endsWith('[]');
109
- }
110
- else if (secure) {
111
- /**
112
- * A secure field is stored as ciphertext, so its declared JSON type says nothing about
113
- * its column. It's always unbounded text: `maxLength` would truncate the ciphertext,
114
- * an enum CHECK would never match it, and jsonb would fail to parse it.
115
- */
116
- sqlType = DEF_SQL_TYPE;
117
- jsonType = 'string';
118
- }
119
- else if (type === 'array') {
120
- const resolved = arraySqlType(property);
121
- sqlType = resolved.sqlType;
122
- jsonType = resolved.jsonType;
123
- array = resolved.array;
124
- }
125
- else {
126
- const resolved = scalarSqlType(property);
127
- sqlType = resolved.sqlType;
128
- jsonType = resolved.jsonType;
129
- }
130
- if (override.length != null) {
131
- sqlType = `character varying(${override.length})`;
132
- }
133
- if (override.array === true && !array && !sqlType.endsWith('[]')) {
134
- sqlType = `${sqlType}[]`;
135
- array = true;
136
- }
137
- if (override.jsonb === true) {
138
- sqlType = DEF_JSON_TYPE;
139
- jsonType = jsonType === 'array' ? 'array' : 'object';
140
- array = false;
141
- }
142
- const formatted = toFormatType(sqlType);
143
- const isJsonb = formatted === 'jsonb' || formatted === 'json';
144
- const column = {
145
- property: name,
146
- /** No implicit snake_casing — a silent rename is a silent DROP plus ADD. */
147
- column: pgIdentifier(override.column ?? name),
148
- sqlType: formatted,
149
- jsonType,
150
- notNull: override.nullable === false ? true : !nullable,
151
- primaryKey: override.primaryKey === true,
152
- secure,
153
- jsonb: isJsonb,
154
- array,
155
- managed: override.managed !== false,
156
- ...(override.using != null ? { using: override.using } : {}),
157
- ...(override.comment != null ? { comment: override.comment } : {})
4
+ import { pgNameHelper } from './name.js';
5
+ import { INT32_MAX } from './consts.local.js';
6
+ const log = logger('postgres-resource');
7
+ export const createPgSchemaHelper = () => {
8
+ const { pgIdentifier, qualify, quoteIdent } = pgNameHelper;
9
+ const toFormatType = (type) => {
10
+ const trimmed = type.trim().toLowerCase();
11
+ const match = /^([a-z0-9_ ]+?)\s*(\(([^)]*)\))?\s*(\[\])?$/.exec(trimmed);
12
+ if (match == null) {
13
+ return trimmed;
14
+ }
15
+ const [, base, , args, array] = match;
16
+ const aliases = {
17
+ int: 'integer', int4: 'integer', int2: 'smallint', int8: 'bigint', serial: 'integer',
18
+ bool: 'boolean', float4: 'real', float8: 'double precision', decimal: 'numeric',
19
+ varchar: 'character varying', char: 'character', bpchar: 'character',
20
+ timestamptz: 'timestamp with time zone', timetz: 'time with time zone',
21
+ timestamp: 'timestamp without time zone', time: 'time without time zone'
22
+ };
23
+ const resolved = aliases[base.trim()] ?? base.trim();
24
+ /** Postgres prints multi-argument typmods without spaces: `numeric(12,2)`. */
25
+ const suffix = args != null ? `(${args.split(',').map(part => part.trim()).join(',')})` : '';
26
+ return `${resolved}${suffix}${array ?? ''}`;
158
27
  };
159
- if (override.defaultRaw != null) {
160
- column.defaultRaw = override.defaultRaw;
161
- }
162
- else if (override.default !== undefined) {
163
- column.defaultLiteral = override.default;
164
- }
165
- else if (property.default !== undefined && !isJsonb && !array) {
166
- /** Non-scalar defaults stay in `getDefaults()` only — they'd need casting in DDL. */
167
- column.defaultLiteral = property.default;
168
- }
169
- return column;
170
- };
171
- const collectProperties = (schema) => {
172
- const properties = { ...schema.properties };
173
- const required = [...(schema.required ?? [])];
174
- /** `allOf` composition is used across the framework's schemas — flatten it like mongo does. */
175
- for (const part of schema.allOf ?? []) {
176
- const nested = collectProperties(part);
177
- Object.assign(properties, nested.properties);
178
- required.push(...nested.required);
179
- }
180
- return { properties, required };
181
- };
182
- /**
183
- * Collapse specs that resolved to the same object name, first declaration wins.
184
- *
185
- * The same index can legitimately be declared twice — a schema-root `pg.indexes` entry, a
186
- * per-property `pg: { index: ... }` override and a `resource.index()` call all land in one
187
- * list, and nothing stops a declaration from repeating one of the others. Two entries with
188
- * one name emit the same `CREATE INDEX` twice inside a single DDL transaction, and Postgres
189
- * answers the second with `42P07 already exists` — which rolls back the whole plan, so the
190
- * table the first statement created never lands and the resource can never initialize.
191
- * Duplicates are a declaration style, not a schema error: dedupe them, don't fail the boot.
192
- */
193
- const byName = (specs, alias, kind) => {
194
- const seen = new Map();
195
- for (const spec of specs) {
196
- const name = spec.name;
197
- if (seen.has(name)) {
198
- console.warn(`@owlmeans/postgres-resource: ${alias} declares ${kind} "${name}" more than once —`
199
- + ' keeping the first declaration.');
200
- continue;
28
+ const readOverride = (property) => property[PG_KEYWORD] ?? {};
29
+ /**
30
+ * Nullability is decided in exactly one place and threaded down from there. Mongo's mapper
31
+ * recomputes it per branch and lost it twice — on `date-time` and on optional objects.
32
+ */
33
+ const isNullable = (property, isRequired) => {
34
+ const override = readOverride(property);
35
+ if (override.nullable != null) {
36
+ return override.nullable;
201
37
  }
202
- seen.set(name, spec);
203
- }
204
- return [...seen.values()];
205
- };
206
- /**
207
- * Compile a resource's AJV schema into the table specification that drives both DDL
208
- * emission and drift detection.
209
- *
210
- * `extraIndexes` carries what `resource.index()` declared. It's compiled here rather than
211
- * merged afterwards so chained declarations get the same property-to-column mapping and
212
- * the same generated names as schema-borne ones.
213
- *
214
- * @throws {UnsupportedArgumentError} when an override asks for something unrepresentable.
215
- */
216
- export const schemaToTableSpec = (alias, schema, pgSchema, table, autoSync, extraIndexes = []) => {
217
- const raw = (schema ?? {});
218
- const root = raw[PG_KEYWORD] ?? {};
219
- const { properties, required } = collectProperties(raw);
220
- const columns = [];
221
- const uniques = [...(root.unique ?? [])];
222
- const checks = [...(root.checks ?? [])];
223
- const indexes = [...(root.indexes ?? []), ...extraIndexes];
224
- const references = [];
225
- const resolvedTable = pgIdentifier(root.table ?? table);
226
- const resolvedSchema = pgIdentifier(root.schema ?? pgSchema);
227
- for (const [name, property] of Object.entries(properties)) {
228
- const column = compileColumn(name, property, required);
229
- columns.push(column);
38
+ if (property.nullable === true) {
39
+ return true;
40
+ }
41
+ if (Array.isArray(property.type) && property.type.includes('null')) {
42
+ return true;
43
+ }
44
+ return !isRequired;
45
+ };
46
+ const baseType = (property) => Array.isArray(property.type) ? property.type.find(type => type !== 'null') : property.type;
47
+ const scalarSqlType = (property) => {
230
48
  const override = readOverride(property);
231
- if (override.unique != null && override.unique !== false) {
232
- if (column.secure) {
49
+ const type = baseType(property);
50
+ switch (type) {
51
+ case 'string':
52
+ switch (property.format) {
53
+ case 'date-time': return { sqlType: 'timestamp with time zone', jsonType: 'date' };
54
+ case 'date': return { sqlType: 'date', jsonType: 'date' };
55
+ case 'time': return { sqlType: 'time without time zone', jsonType: 'string' };
56
+ case 'uuid': return { sqlType: 'uuid', jsonType: 'string' };
57
+ case 'binary': return { sqlType: 'bytea', jsonType: 'binary' };
58
+ default: break;
59
+ }
60
+ return property.maxLength != null
61
+ ? { sqlType: `character varying(${property.maxLength})`, jsonType: 'string' }
62
+ : { sqlType: DEF_SQL_TYPE, jsonType: 'string' };
63
+ case 'integer':
64
+ return property.maximum != null && property.maximum > INT32_MAX
65
+ ? { sqlType: 'bigint', jsonType: 'bigint' }
66
+ : { sqlType: 'integer', jsonType: 'integer' };
67
+ case 'number':
68
+ return override.precision != null
69
+ ? { sqlType: `numeric(${override.precision},${override.scale ?? 0})`, jsonType: 'number' }
70
+ : { sqlType: 'double precision', jsonType: 'number' };
71
+ case 'boolean':
72
+ return { sqlType: 'boolean', jsonType: 'boolean' };
73
+ case 'object':
233
74
  /**
234
- * Encryption uses a managed nonce, so two identical plaintexts encrypt to different
235
- * ciphertexts — a unique constraint on the column would never collide, silently.
75
+ * The framework's date convention — `{ type: 'object', format: 'date-time' }`. Mongo's
76
+ * mapper broke twice on exactly this branch by dropping nullability, so nullability is
77
+ * decided by the caller, never here.
236
78
  */
237
- throw new UnsupportedArgumentError(`secure-unique:${name}`);
238
- }
239
- uniques.push({
240
- columns: [name],
241
- ...(typeof override.unique === 'string' ? { name: override.unique } : {})
242
- });
79
+ return property.format === 'date-time'
80
+ ? { sqlType: 'timestamp with time zone', jsonType: 'date' }
81
+ : { sqlType: DEF_JSON_TYPE, jsonType: 'object' };
82
+ default:
83
+ return { sqlType: DEF_JSON_TYPE, jsonType: 'unknown' };
243
84
  }
244
- if (override.index != null && override.index !== false) {
245
- if (column.secure) {
246
- console.warn(`@owlmeans/postgres-resource: index on secure column "${alias}.${name}" — encryption`
247
- + ' is non-deterministic, so equality lookups through it will never match.');
248
- }
249
- const specs = override.index === true
250
- ? [{ columns: [name] }]
251
- : Array.isArray(override.index) ? override.index : [override.index];
252
- indexes.push(...specs.map(spec => ({ ...spec, columns: spec.columns ?? [name] })));
85
+ };
86
+ const arraySqlType = (property) => {
87
+ const items = property.items;
88
+ const itemType = items != null ? baseType(items) : undefined;
89
+ /** Only scalar element types become Postgres arrays; anything else stays jsonb. */
90
+ if (items != null && itemType != null && ['string', 'integer', 'number', 'boolean'].includes(itemType)
91
+ && items.format == null && items.enum == null) {
92
+ const scalar = scalarSqlType(items);
93
+ return { sqlType: `${scalar.sqlType}[]`, jsonType: 'array', array: true };
253
94
  }
254
- if (override.references != null) {
255
- references.push({
256
- ...override.references,
257
- property: name,
258
- column: override.references.column ?? ID_FIELD,
259
- name: pgIdentifier(override.references.name ?? `${resolvedTable}_${column.column}_fkey`)
260
- });
95
+ return { sqlType: DEF_JSON_TYPE, jsonType: 'array', array: false };
96
+ };
97
+ const compileColumn = (name, property, required) => {
98
+ const override = readOverride(property);
99
+ const secure = property.secure === true;
100
+ const type = baseType(property);
101
+ const nullable = isNullable(property, required.includes(name));
102
+ let sqlType;
103
+ let jsonType;
104
+ let array = false;
105
+ if (override.type != null) {
106
+ sqlType = override.type;
107
+ jsonType = secure ? 'string' : scalarSqlType(property).jsonType;
108
+ array = override.array === true || override.type.endsWith('[]');
261
109
  }
262
- if (override.check != null) {
263
- checks.push({
264
- name: `${resolvedTable}_${column.column}_check`,
265
- expression: override.check.replace(/\{\{col\}\}/g, quoteIdent(column.column))
266
- });
110
+ else if (secure) {
111
+ /**
112
+ * A secure field is stored as ciphertext, so its declared JSON type says nothing about
113
+ * its column. It's always unbounded text: `maxLength` would truncate the ciphertext,
114
+ * an enum CHECK would never match it, and jsonb would fail to parse it.
115
+ */
116
+ sqlType = DEF_SQL_TYPE;
117
+ jsonType = 'string';
267
118
  }
268
- /** A string enum becomes a CHECK — a native PG enum can't drop values and can't be altered in a transaction. */
269
- if (property.enum != null && !column.secure && override.type == null
270
- && baseType(property) === 'string' && property.enum.every(value => typeof value === 'string')) {
271
- const values = property.enum.map(value => `'${value.replace(/'/g, "''")}'`).join(', ');
272
- const predicate = column.notNull
273
- ? `${quoteIdent(column.column)} IN (${values})`
274
- : `${quoteIdent(column.column)} IS NULL OR ${quoteIdent(column.column)} IN (${values})`;
275
- checks.push({ name: `${resolvedTable}_${column.column}_enum`, expression: predicate });
119
+ else if (type === 'array') {
120
+ const resolved = arraySqlType(property);
121
+ sqlType = resolved.sqlType;
122
+ jsonType = resolved.jsonType;
123
+ array = resolved.array;
276
124
  }
277
- }
278
- const byProperty = {};
279
- const byColumn = {};
280
- for (const column of columns) {
281
- byProperty[column.property] = column;
282
- byColumn[column.column] = column;
283
- }
284
- let primaryKey = [];
285
- if (root.primaryKey != null && root.primaryKey.length > 0) {
286
- primaryKey = root.primaryKey.map(property => {
287
- const column = byProperty[property];
288
- if (column == null) {
289
- throw new UnsupportedArgumentError(`primary-key:${property}`);
125
+ else {
126
+ const resolved = scalarSqlType(property);
127
+ sqlType = resolved.sqlType;
128
+ jsonType = resolved.jsonType;
129
+ }
130
+ if (override.length != null) {
131
+ sqlType = `character varying(${override.length})`;
132
+ }
133
+ if (override.array === true && !array && !sqlType.endsWith('[]')) {
134
+ sqlType = `${sqlType}[]`;
135
+ array = true;
136
+ }
137
+ if (override.jsonb === true) {
138
+ sqlType = DEF_JSON_TYPE;
139
+ jsonType = jsonType === 'array' ? 'array' : 'object';
140
+ array = false;
141
+ }
142
+ const formatted = toFormatType(sqlType);
143
+ const isJsonb = formatted === 'jsonb' || formatted === 'json';
144
+ const column = {
145
+ property: name,
146
+ /** No implicit snake_casing — a silent rename is a silent DROP plus ADD. */
147
+ column: pgIdentifier(override.column ?? name),
148
+ sqlType: formatted,
149
+ jsonType,
150
+ notNull: override.nullable === false ? true : !nullable,
151
+ primaryKey: override.primaryKey === true,
152
+ secure,
153
+ jsonb: isJsonb,
154
+ array,
155
+ managed: override.managed !== false,
156
+ ...(override.using != null ? { using: override.using } : {}),
157
+ ...(override.comment != null ? { comment: override.comment } : {})
158
+ };
159
+ if (override.defaultRaw != null) {
160
+ column.defaultRaw = override.defaultRaw;
161
+ }
162
+ else if (override.default !== undefined) {
163
+ column.defaultLiteral = override.default;
164
+ }
165
+ else if (property.default !== undefined && !isJsonb && !array) {
166
+ /** Non-scalar defaults stay in `getDefaults()` only — they'd need casting in DDL. */
167
+ column.defaultLiteral = property.default;
168
+ }
169
+ return column;
170
+ };
171
+ const collectProperties = (schema) => {
172
+ const properties = { ...schema.properties };
173
+ const required = [...(schema.required ?? [])];
174
+ /** `allOf` composition is used across the framework's schemas — flatten it like mongo does. */
175
+ for (const part of schema.allOf ?? []) {
176
+ const nested = collectProperties(part);
177
+ Object.assign(properties, nested.properties);
178
+ required.push(...nested.required);
179
+ }
180
+ return { properties, required };
181
+ };
182
+ /**
183
+ * Collapse specs that resolved to the same object name, first declaration wins.
184
+ *
185
+ * The same index can legitimately be declared twice — a schema-root `pg.indexes` entry, a
186
+ * per-property `pg: { index: ... }` override and a `resource.index()` call all land in one
187
+ * list, and nothing stops a declaration from repeating one of the others. Two entries with
188
+ * one name emit the same `CREATE INDEX` twice inside a single DDL transaction, and Postgres
189
+ * answers the second with `42P07 already exists` — which rolls back the whole plan, so the
190
+ * table the first statement created never lands and the resource can never initialize.
191
+ * Duplicates are a declaration style, not a schema error: dedupe them, don't fail the boot.
192
+ */
193
+ const byName = (specs, alias, kind) => {
194
+ const seen = new Map();
195
+ for (const spec of specs) {
196
+ const name = spec.name;
197
+ if (seen.has(name)) {
198
+ log.warn('Duplicate declaration, keeping the first one', { resource: alias, kind, name });
199
+ continue;
290
200
  }
291
- column.notNull = true;
292
- return column.column;
293
- });
294
- }
295
- else {
296
- const explicit = columns.filter(column => column.primaryKey);
297
- if (explicit.length > 0) {
298
- primaryKey = explicit.map(column => {
201
+ seen.set(name, spec);
202
+ }
203
+ return [...seen.values()];
204
+ };
205
+ const schemaToTableSpec = (alias, schema, pgSchema, table, autoSync, extraIndexes = []) => {
206
+ const raw = (schema ?? {});
207
+ const root = raw[PG_KEYWORD] ?? {};
208
+ const { properties, required } = collectProperties(raw);
209
+ const columns = [];
210
+ const uniques = [...(root.unique ?? [])];
211
+ const checks = [...(root.checks ?? [])];
212
+ const indexes = [...(root.indexes ?? []), ...extraIndexes];
213
+ const references = [];
214
+ const resolvedTable = pgIdentifier(root.table ?? table);
215
+ const resolvedSchema = pgIdentifier(root.schema ?? pgSchema);
216
+ for (const [name, property] of Object.entries(properties)) {
217
+ const column = compileColumn(name, property, required);
218
+ columns.push(column);
219
+ const override = readOverride(property);
220
+ if (override.unique != null && override.unique !== false) {
221
+ if (column.secure) {
222
+ /**
223
+ * Encryption uses a managed nonce, so two identical plaintexts encrypt to different
224
+ * ciphertexts — a unique constraint on the column would never collide, silently.
225
+ */
226
+ throw new UnsupportedArgumentError(`secure-unique:${name}`);
227
+ }
228
+ uniques.push({
229
+ columns: [name],
230
+ ...(typeof override.unique === 'string' ? { name: override.unique } : {})
231
+ });
232
+ }
233
+ if (override.index != null && override.index !== false) {
234
+ if (column.secure) {
235
+ log.warn('Index on a secure column will never match: encryption is non-deterministic', {
236
+ resource: alias, column: name,
237
+ });
238
+ }
239
+ const specs = override.index === true
240
+ ? [{ columns: [name] }]
241
+ : Array.isArray(override.index) ? override.index : [override.index];
242
+ indexes.push(...specs.map(spec => ({ ...spec, columns: spec.columns ?? [name] })));
243
+ }
244
+ if (override.references != null) {
245
+ references.push({
246
+ ...override.references,
247
+ property: name,
248
+ column: override.references.column ?? ID_FIELD,
249
+ name: pgIdentifier(override.references.name ?? `${resolvedTable}_${column.column}_fkey`)
250
+ });
251
+ }
252
+ if (override.check != null) {
253
+ checks.push({
254
+ name: `${resolvedTable}_${column.column}_check`,
255
+ expression: override.check.replace(/\{\{col\}\}/g, quoteIdent(column.column))
256
+ });
257
+ }
258
+ /** A string enum becomes a CHECK — a native PG enum can't drop values and can't be altered in a transaction. */
259
+ if (property.enum != null && !column.secure && override.type == null
260
+ && baseType(property) === 'string' && property.enum.every(value => typeof value === 'string')) {
261
+ const values = property.enum.map(value => `'${value.replace(/'/g, "''")}'`).join(', ');
262
+ const predicate = column.notNull
263
+ ? `${quoteIdent(column.column)} IN (${values})`
264
+ : `${quoteIdent(column.column)} IS NULL OR ${quoteIdent(column.column)} IN (${values})`;
265
+ checks.push({ name: `${resolvedTable}_${column.column}_enum`, expression: predicate });
266
+ }
267
+ }
268
+ const byProperty = {};
269
+ const byColumn = {};
270
+ for (const column of columns) {
271
+ byProperty[column.property] = column;
272
+ byColumn[column.column] = column;
273
+ }
274
+ let primaryKey = [];
275
+ if (root.primaryKey != null && root.primaryKey.length > 0) {
276
+ primaryKey = root.primaryKey.map(property => {
277
+ const column = byProperty[property];
278
+ if (column == null) {
279
+ throw new UnsupportedArgumentError(`primary-key:${property}`);
280
+ }
299
281
  column.notNull = true;
300
282
  return column.column;
301
283
  });
302
284
  }
303
285
  else {
304
- /**
305
- * Every OwlMeans record is addressed by `id`, so the column is synthesized when the
306
- * schema doesn't declare it — `create()` and `load()` both assume it exists.
307
- */
308
- let id = byProperty[ID_FIELD];
309
- if (id == null) {
310
- id = {
311
- property: ID_FIELD, column: ID_FIELD, sqlType: DEF_SQL_TYPE, jsonType: 'string',
312
- notNull: true, primaryKey: true, secure: false, jsonb: false, array: false,
313
- managed: true, defaultRaw: DEF_ID_DEFAULT
314
- };
315
- columns.unshift(id);
316
- byProperty[ID_FIELD] = id;
317
- byColumn[ID_FIELD] = id;
286
+ const explicit = columns.filter(column => column.primaryKey);
287
+ if (explicit.length > 0) {
288
+ primaryKey = explicit.map(column => {
289
+ column.notNull = true;
290
+ return column.column;
291
+ });
318
292
  }
319
293
  else {
320
- id.notNull = true;
321
- id.primaryKey = true;
322
- if (id.defaultRaw == null && id.defaultLiteral === undefined) {
323
- id.defaultRaw = id.sqlType === 'uuid' ? 'gen_random_uuid()' : DEF_ID_DEFAULT;
294
+ /**
295
+ * Every OwlMeans record is addressed by `id`, so the column is synthesized when the
296
+ * schema doesn't declare it — `create()` and `load()` both assume it exists.
297
+ */
298
+ let id = byProperty[ID_FIELD];
299
+ if (id == null) {
300
+ id = {
301
+ property: ID_FIELD, column: ID_FIELD, sqlType: DEF_SQL_TYPE, jsonType: 'string',
302
+ notNull: true, primaryKey: true, secure: false, jsonb: false, array: false,
303
+ managed: true, defaultRaw: DEF_ID_DEFAULT
304
+ };
305
+ columns.unshift(id);
306
+ byProperty[ID_FIELD] = id;
307
+ byColumn[ID_FIELD] = id;
324
308
  }
309
+ else {
310
+ id.notNull = true;
311
+ id.primaryKey = true;
312
+ if (id.defaultRaw == null && id.defaultLiteral === undefined) {
313
+ id.defaultRaw = id.sqlType === 'uuid' ? 'gen_random_uuid()' : DEF_ID_DEFAULT;
314
+ }
315
+ }
316
+ primaryKey = [id.column];
325
317
  }
326
- primaryKey = [id.column];
327
- }
328
- }
329
- /** Index and unique specs address properties; map them onto physical columns once, here. */
330
- const mapColumns = (names) => names.map(name => {
331
- const column = byProperty[name];
332
- if (column == null) {
333
- throw new UnsupportedArgumentError(`unknown-property:${name}`);
334
318
  }
335
- return column.column;
336
- });
337
- const resolvedIndexes = byName(indexes.map(spec => {
338
- const list = spec.columns == null
339
- ? []
340
- : mapColumns(Array.isArray(spec.columns) ? spec.columns : [spec.columns]);
341
- const suffix = spec.unique === true ? 'uq' : 'idx';
319
+ /** Index and unique specs address properties; map them onto physical columns once, here. */
320
+ const mapColumns = (names) => names.map(name => {
321
+ const column = byProperty[name];
322
+ if (column == null) {
323
+ throw new UnsupportedArgumentError(`unknown-property:${name}`);
324
+ }
325
+ return column.column;
326
+ });
327
+ const resolvedIndexes = byName(indexes.map(spec => {
328
+ const list = spec.columns == null
329
+ ? []
330
+ : mapColumns(Array.isArray(spec.columns) ? spec.columns : [spec.columns]);
331
+ const suffix = spec.unique === true ? 'uq' : 'idx';
332
+ return {
333
+ ...spec,
334
+ columns: list,
335
+ method: spec.method ?? PgIndexMethod.BTree,
336
+ name: pgIdentifier(spec.name ?? `${resolvedTable}_${list.join('_')}_${suffix}`)
337
+ };
338
+ }), alias, 'index');
339
+ const resolvedUniques = byName(uniques.map(spec => {
340
+ const list = mapColumns(spec.columns);
341
+ return { columns: list, name: pgIdentifier(spec.name ?? `${resolvedTable}_${list.join('_')}_key`) };
342
+ }), alias, 'unique');
342
343
  return {
343
- ...spec,
344
- columns: list,
345
- method: spec.method ?? PgIndexMethod.BTree,
346
- name: pgIdentifier(spec.name ?? `${resolvedTable}_${list.join('_')}_${suffix}`)
344
+ alias,
345
+ schema: resolvedSchema,
346
+ table: resolvedTable,
347
+ qualified: qualify(resolvedSchema, resolvedTable),
348
+ columns,
349
+ byProperty,
350
+ byColumn,
351
+ primaryKey,
352
+ uniques: resolvedUniques,
353
+ checks: checks.map(check => ({ ...check, name: pgIdentifier(check.name ?? `${resolvedTable}_check`) })),
354
+ indexes: resolvedIndexes,
355
+ references,
356
+ unmanaged: [
357
+ ...(root.unmanaged ?? []).map(name => byProperty[name]?.column ?? pgIdentifier(name)),
358
+ ...columns.filter(column => !column.managed).map(column => column.column)
359
+ ],
360
+ autoSync: root.autoSync ?? autoSync,
361
+ ...(root.comment != null ? { comment: root.comment } : {})
347
362
  };
348
- }), alias, 'index');
349
- const resolvedUniques = byName(uniques.map(spec => {
350
- const list = mapColumns(spec.columns);
351
- return { columns: list, name: pgIdentifier(spec.name ?? `${resolvedTable}_${list.join('_')}_key`) };
352
- }), alias, 'unique');
353
- return {
354
- alias,
355
- schema: resolvedSchema,
356
- table: resolvedTable,
357
- qualified: qualify(resolvedSchema, resolvedTable),
358
- columns,
359
- byProperty,
360
- byColumn,
361
- primaryKey,
362
- uniques: resolvedUniques,
363
- checks: checks.map(check => ({ ...check, name: pgIdentifier(check.name ?? `${resolvedTable}_check`) })),
364
- indexes: resolvedIndexes,
365
- references,
366
- unmanaged: [
367
- ...(root.unmanaged ?? []).map(name => byProperty[name]?.column ?? pgIdentifier(name)),
368
- ...columns.filter(column => !column.managed).map(column => column.column)
369
- ],
370
- autoSync: root.autoSync ?? autoSync,
371
- ...(root.comment != null ? { comment: root.comment } : {})
372
363
  };
364
+ return { toFormatType, schemaToTableSpec };
373
365
  };
374
- /**
375
- * AJV keyword registration for consumers running in strict mode. The mapper reads the raw
376
- * schema object and never validates through AJV, so this is purely to stop strict mode
377
- * rejecting a schema that carries `pg` overrides.
378
- */
379
- export const pgKeyword = { keyword: PG_KEYWORD, valid: true };
366
+ export const pgSchemaHelper = createPgSchemaHelper();
367
+ /** @deprecated compat:factory-refactor — use `pgSchemaHelper.schemaToTableSpec(…)` */
368
+ export const schemaToTableSpec = (alias, schema, pgSchema, table, autoSync, extraIndexes = []) => pgSchemaHelper.schemaToTableSpec(alias, schema, pgSchema, table, autoSync, extraIndexes);
380
369
  //# sourceMappingURL=schema.js.map