rev-dal 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +234 -0
- package/CONTRIBUTING.md +83 -0
- package/LICENSE +121 -0
- package/README.md +67 -2
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +26 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/clone.d.ts +24 -0
- package/dist/lib/clone.d.ts.map +1 -0
- package/dist/lib/clone.js +83 -0
- package/dist/lib/clone.js.map +1 -0
- package/dist/lib/create-model.d.ts +207 -0
- package/dist/lib/create-model.d.ts.map +1 -0
- package/dist/lib/create-model.js +230 -0
- package/dist/lib/create-model.js.map +1 -0
- package/dist/lib/data-access-layer.d.ts +140 -0
- package/dist/lib/data-access-layer.d.ts.map +1 -0
- package/dist/lib/data-access-layer.js +389 -0
- package/dist/lib/data-access-layer.js.map +1 -0
- package/dist/lib/errors.d.ts +139 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +206 -0
- package/dist/lib/errors.js.map +1 -0
- package/dist/lib/filter-where.d.ts +199 -0
- package/dist/lib/filter-where.d.ts.map +1 -0
- package/dist/lib/filter-where.js +563 -0
- package/dist/lib/filter-where.js.map +1 -0
- package/dist/lib/ml-string.d.ts +63 -0
- package/dist/lib/ml-string.d.ts.map +1 -0
- package/dist/lib/ml-string.js +331 -0
- package/dist/lib/ml-string.js.map +1 -0
- package/dist/lib/model-factory.d.ts +25 -0
- package/dist/lib/model-factory.d.ts.map +1 -0
- package/dist/lib/model-factory.js +57 -0
- package/dist/lib/model-factory.js.map +1 -0
- package/dist/lib/model-handle.d.ts +67 -0
- package/dist/lib/model-handle.d.ts.map +1 -0
- package/dist/lib/model-handle.js +182 -0
- package/dist/lib/model-handle.js.map +1 -0
- package/dist/lib/model-initializer.d.ts +96 -0
- package/dist/lib/model-initializer.d.ts.map +1 -0
- package/dist/lib/model-initializer.js +182 -0
- package/dist/lib/model-initializer.js.map +1 -0
- package/dist/lib/model-manifest.d.ts +112 -0
- package/dist/lib/model-manifest.d.ts.map +1 -0
- package/dist/lib/model-manifest.js +2 -0
- package/dist/lib/model-manifest.js.map +1 -0
- package/dist/lib/model-registry.d.ts +81 -0
- package/dist/lib/model-registry.d.ts.map +1 -0
- package/dist/lib/model-registry.js +139 -0
- package/dist/lib/model-registry.js.map +1 -0
- package/dist/lib/model-types.d.ts +380 -0
- package/dist/lib/model-types.d.ts.map +1 -0
- package/dist/lib/model-types.js +2 -0
- package/dist/lib/model-types.js.map +1 -0
- package/dist/lib/model.d.ts +503 -0
- package/dist/lib/model.d.ts.map +1 -0
- package/dist/lib/model.js +1423 -0
- package/dist/lib/model.js.map +1 -0
- package/dist/lib/postgres-config.d.ts +3 -0
- package/dist/lib/postgres-config.d.ts.map +1 -0
- package/dist/lib/postgres-config.js +2 -0
- package/dist/lib/postgres-config.js.map +1 -0
- package/dist/lib/query-builder.d.ts +607 -0
- package/dist/lib/query-builder.d.ts.map +1 -0
- package/dist/lib/query-builder.js +1734 -0
- package/dist/lib/query-builder.js.map +1 -0
- package/dist/lib/revision.d.ts +55 -0
- package/dist/lib/revision.d.ts.map +1 -0
- package/dist/lib/revision.js +307 -0
- package/dist/lib/revision.js.map +1 -0
- package/dist/lib/runtime.d.ts +18 -0
- package/dist/lib/runtime.d.ts.map +1 -0
- package/dist/lib/runtime.js +134 -0
- package/dist/lib/runtime.js.map +1 -0
- package/dist/lib/transaction.d.ts +17 -0
- package/dist/lib/transaction.d.ts.map +1 -0
- package/dist/lib/transaction.js +30 -0
- package/dist/lib/transaction.js.map +1 -0
- package/dist/lib/type.d.ts +130 -0
- package/dist/lib/type.d.ts.map +1 -0
- package/dist/lib/type.js +376 -0
- package/dist/lib/type.js.map +1 -0
- package/docs/models.md +406 -0
- package/docs/multilingual-text.md +142 -0
- package/docs/queries.md +374 -0
- package/docs/revisions.md +61 -0
- package/package.json +60 -4
- package/releases/0.2.0.md +18 -0
- package/releases/0.2.1.md +22 -0
- package/releases/README.md +7 -0
- package/setup-db-grants.sql +51 -0
|
@@ -0,0 +1,1423 @@
|
|
|
1
|
+
import isUUID from 'is-uuid';
|
|
2
|
+
import { cloneRowValue } from './clone.js';
|
|
3
|
+
import { convertPostgreSQLError, DocumentNotFound, RevisionConflictError } from './errors.js';
|
|
4
|
+
import QueryBuilder from './query-builder.js';
|
|
5
|
+
import revision from './revision.js';
|
|
6
|
+
import { assertTransactionClient, runInTransaction } from './transaction.js';
|
|
7
|
+
/**
|
|
8
|
+
* Base Model class for PostgreSQL DAL
|
|
9
|
+
*
|
|
10
|
+
* Provides CRUD operations, virtual fields, and query building functionality.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Deep equality comparison for detecting actual changes in validated values
|
|
14
|
+
* @param a - First value
|
|
15
|
+
* @param b - Second value
|
|
16
|
+
* @returns True if values are deeply equal
|
|
17
|
+
* @private
|
|
18
|
+
*/
|
|
19
|
+
function deepEqual(a, b) {
|
|
20
|
+
// Strict equality check (handles primitives, null, undefined, same reference)
|
|
21
|
+
if (a === b)
|
|
22
|
+
return true;
|
|
23
|
+
// Different types or one is null/undefined
|
|
24
|
+
if (a == null || b == null || typeof a !== typeof b)
|
|
25
|
+
return false;
|
|
26
|
+
// Date comparison
|
|
27
|
+
if (a instanceof Date && b instanceof Date) {
|
|
28
|
+
return a.getTime() === b.getTime();
|
|
29
|
+
}
|
|
30
|
+
// Array comparison
|
|
31
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
32
|
+
if (a.length !== b.length)
|
|
33
|
+
return false;
|
|
34
|
+
for (let i = 0; i < a.length; i++) {
|
|
35
|
+
if (!deepEqual(a[i], b[i]))
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
// Object comparison
|
|
41
|
+
if (typeof a === 'object' && typeof b === 'object') {
|
|
42
|
+
const keysA = Object.keys(a);
|
|
43
|
+
const keysB = Object.keys(b);
|
|
44
|
+
if (keysA.length !== keysB.length)
|
|
45
|
+
return false;
|
|
46
|
+
for (const key of keysA) {
|
|
47
|
+
if (!keysB.includes(key) || !deepEqual(a[key], b[key])) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
// Other types (functions, symbols, etc.) - use strict equality
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
/** Column names that are safe to interpolate into SQL. */
|
|
57
|
+
const SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
58
|
+
/**
|
|
59
|
+
* Base Model class
|
|
60
|
+
*/
|
|
61
|
+
class Model {
|
|
62
|
+
static _fieldMappings = new Map();
|
|
63
|
+
static _relations = new Map();
|
|
64
|
+
static _revisionHandlers;
|
|
65
|
+
static schema;
|
|
66
|
+
static tableName;
|
|
67
|
+
static options;
|
|
68
|
+
static dal;
|
|
69
|
+
_data;
|
|
70
|
+
_virtualFields;
|
|
71
|
+
_changed;
|
|
72
|
+
_isNew;
|
|
73
|
+
_originalData;
|
|
74
|
+
_pendingRevision = null;
|
|
75
|
+
static _views = new Map();
|
|
76
|
+
static get runtime() {
|
|
77
|
+
return this;
|
|
78
|
+
}
|
|
79
|
+
get runtime() {
|
|
80
|
+
return this.constructor;
|
|
81
|
+
}
|
|
82
|
+
_setVirtualField(key, value) {
|
|
83
|
+
this._virtualFields[key] = value;
|
|
84
|
+
}
|
|
85
|
+
constructor(data = {}, _options = {}) {
|
|
86
|
+
this._data = {};
|
|
87
|
+
this._virtualFields = {};
|
|
88
|
+
this._changed = new Set();
|
|
89
|
+
this._isNew = true;
|
|
90
|
+
this._originalData = {}; // Track original values for detecting in-place JSONB modifications
|
|
91
|
+
// Set up property accessors before applying data so setters map correctly
|
|
92
|
+
this._setupPropertyAccessors();
|
|
93
|
+
const initialData = data && typeof data === 'object' ? data : {};
|
|
94
|
+
// Apply schema defaults for missing values
|
|
95
|
+
this._applyDefaults(initialData);
|
|
96
|
+
// Apply provided data using setters to respect mappings and change tracking
|
|
97
|
+
for (const [key, value] of Object.entries(initialData)) {
|
|
98
|
+
this.setValue(key, value);
|
|
99
|
+
}
|
|
100
|
+
// Generate virtual field values (may depend on applied data)
|
|
101
|
+
this.generateVirtualValues();
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Register a camelCase to snake_case field mapping
|
|
105
|
+
* @param camelCase - camelCase property name
|
|
106
|
+
* @param snakeCase - snake_case database column name
|
|
107
|
+
*/
|
|
108
|
+
static _registerFieldMapping(camelCase, snakeCase) {
|
|
109
|
+
this.runtime._fieldMappings.set(camelCase, snakeCase);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Register relation metadata for the model
|
|
113
|
+
* @param name - Relation name
|
|
114
|
+
* @param config - Relation configuration
|
|
115
|
+
*/
|
|
116
|
+
static defineRelation(name, config) {
|
|
117
|
+
const runtime = this.runtime;
|
|
118
|
+
if (!name || typeof name !== 'string') {
|
|
119
|
+
throw new Error('Relation name must be a non-empty string');
|
|
120
|
+
}
|
|
121
|
+
// Relation names are used in SQL aliases, so they must be plain identifiers
|
|
122
|
+
if (!SAFE_IDENTIFIER.test(name)) {
|
|
123
|
+
throw new Error(`Relation name '${name}' must be a plain identifier (letters, digits and underscores, ` +
|
|
124
|
+
'not starting with a digit).');
|
|
125
|
+
}
|
|
126
|
+
if (!config || typeof config !== 'object') {
|
|
127
|
+
throw new Error(`Relation '${name}' configuration must be an object`);
|
|
128
|
+
}
|
|
129
|
+
if (!runtime._relations || !(runtime._relations instanceof Map)) {
|
|
130
|
+
runtime._relations = new Map();
|
|
131
|
+
}
|
|
132
|
+
const normalizedConfig = this._normalizeRelationConfig(name, config);
|
|
133
|
+
runtime._relations.set(name, normalizedConfig);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Normalize and enrich relation metadata for downstream consumers.
|
|
137
|
+
*
|
|
138
|
+
* @param name - Relation name.
|
|
139
|
+
* @param config - Raw relation configuration.
|
|
140
|
+
* @returns Frozen, normalized relation configuration.
|
|
141
|
+
* @private
|
|
142
|
+
*/
|
|
143
|
+
static _normalizeRelationConfig(name, config) {
|
|
144
|
+
const baseConfig = config && typeof config === 'object' ? { ...config } : {};
|
|
145
|
+
const targetTable = baseConfig.targetTable || baseConfig.table || baseConfig.target;
|
|
146
|
+
if (!targetTable) {
|
|
147
|
+
throw new Error(`Relation '${name}' must define a targetTable or table property.`);
|
|
148
|
+
}
|
|
149
|
+
const targetModelKey = baseConfig.targetModelKey || baseConfig.targetModel || targetTable;
|
|
150
|
+
const rawSource = baseConfig.sourceColumn || baseConfig.sourceKey || baseConfig.sourceField || 'id';
|
|
151
|
+
const sourceColumn = this._getDbFieldName(typeof rawSource === 'string' ? rawSource : String(rawSource));
|
|
152
|
+
const rawTarget = baseConfig.targetColumn || baseConfig.targetKey || baseConfig.targetField || 'id';
|
|
153
|
+
const targetColumn = typeof rawTarget === 'string' ? rawTarget : String(rawTarget);
|
|
154
|
+
const hasRevisions = Boolean(baseConfig.hasRevisions);
|
|
155
|
+
let throughConfig = null;
|
|
156
|
+
if (baseConfig.through && typeof baseConfig.through === 'object') {
|
|
157
|
+
const rawThrough = baseConfig.through;
|
|
158
|
+
const throughTable = rawThrough.table || rawThrough.name || baseConfig.joinTable;
|
|
159
|
+
if (!throughTable) {
|
|
160
|
+
throw new Error(`Relation '${name}' requires a through.table definition for many-to-many joins.`);
|
|
161
|
+
}
|
|
162
|
+
const throughSourceColumn = rawThrough.sourceColumn || rawThrough.sourceForeignKey || rawThrough.sourceKey;
|
|
163
|
+
const throughTargetColumn = rawThrough.targetColumn || rawThrough.targetForeignKey || rawThrough.targetKey;
|
|
164
|
+
if (!throughSourceColumn || !throughTargetColumn) {
|
|
165
|
+
throw new Error(`Relation '${name}' through definition must include sourceForeignKey and targetForeignKey.`);
|
|
166
|
+
}
|
|
167
|
+
throughConfig = Object.freeze({
|
|
168
|
+
table: String(throughTable),
|
|
169
|
+
sourceColumn: String(throughSourceColumn),
|
|
170
|
+
targetColumn: String(throughTargetColumn),
|
|
171
|
+
sourceCondition: rawThrough.sourceCondition || null,
|
|
172
|
+
targetCondition: rawThrough.targetCondition || null,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
const inferredCardinality = baseConfig.cardinality || (throughConfig ? 'many' : sourceColumn === 'id' ? 'many' : 'one');
|
|
176
|
+
return Object.freeze({
|
|
177
|
+
...baseConfig,
|
|
178
|
+
targetTable,
|
|
179
|
+
targetModelKey,
|
|
180
|
+
sourceColumn,
|
|
181
|
+
targetColumn,
|
|
182
|
+
hasRevisions,
|
|
183
|
+
cardinality: inferredCardinality,
|
|
184
|
+
isArray: inferredCardinality !== 'one',
|
|
185
|
+
through: throughConfig,
|
|
186
|
+
joinType: throughConfig ? 'through' : 'direct',
|
|
187
|
+
condition: baseConfig.condition || null,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Retrieve relation metadata by name
|
|
192
|
+
* @param name - Relation name
|
|
193
|
+
* @returns Stored relation configuration
|
|
194
|
+
*/
|
|
195
|
+
static getRelation(name) {
|
|
196
|
+
const runtime = this.runtime;
|
|
197
|
+
if (!runtime._relations || !(runtime._relations instanceof Map)) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
return runtime._relations.get(name) || null;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Retrieve all registered relation metadata
|
|
204
|
+
* @returns Array of relation configurations with names
|
|
205
|
+
*/
|
|
206
|
+
static getRelations() {
|
|
207
|
+
const runtime = this.runtime;
|
|
208
|
+
if (!runtime._relations || !(runtime._relations instanceof Map)) {
|
|
209
|
+
return [];
|
|
210
|
+
}
|
|
211
|
+
return Array.from(runtime._relations.entries()).map(([name, config]) => ({
|
|
212
|
+
name,
|
|
213
|
+
config,
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Register a named projection/view for this model.
|
|
218
|
+
* @param name - Unique view identifier
|
|
219
|
+
* @param definition - View configuration
|
|
220
|
+
*/
|
|
221
|
+
static defineView(name, definition) {
|
|
222
|
+
const runtime = this.runtime;
|
|
223
|
+
if (!runtime._views || !(runtime._views instanceof Map)) {
|
|
224
|
+
runtime._views = new Map();
|
|
225
|
+
}
|
|
226
|
+
runtime._views.set(name, definition);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Retrieve the view definition for a registered projection.
|
|
230
|
+
*
|
|
231
|
+
* @param name - View identifier
|
|
232
|
+
* @returns Stored view definition or null if missing
|
|
233
|
+
*/
|
|
234
|
+
static getView(name) {
|
|
235
|
+
const view = this._getViewDefinition(name);
|
|
236
|
+
return view || null;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Internal helper to access the normalized view definition.
|
|
240
|
+
*
|
|
241
|
+
* @param name - View identifier
|
|
242
|
+
* @returns Registered definition or null
|
|
243
|
+
* @private
|
|
244
|
+
*/
|
|
245
|
+
static _getViewDefinition(name) {
|
|
246
|
+
const runtime = this.runtime;
|
|
247
|
+
if (!runtime._views || !(runtime._views instanceof Map)) {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
return (runtime._views.get(name) || null);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Execute a view query using the provided builder configuration.
|
|
254
|
+
*
|
|
255
|
+
* @param name - Registered view name
|
|
256
|
+
* @param options - View fetch options
|
|
257
|
+
* @returns Array of projected view objects
|
|
258
|
+
*/
|
|
259
|
+
static async fetchView(name, options = {}) {
|
|
260
|
+
const viewDef = this._getViewDefinition(name);
|
|
261
|
+
if (!viewDef) {
|
|
262
|
+
throw new Error(`View '${name}' not defined for model '${this.tableName}'`);
|
|
263
|
+
}
|
|
264
|
+
const builder = this.filterWhere({});
|
|
265
|
+
if (options.includeSensitive && options.includeSensitive.length > 0) {
|
|
266
|
+
builder.includeSensitive(options.includeSensitive);
|
|
267
|
+
}
|
|
268
|
+
if (typeof options.configure === 'function') {
|
|
269
|
+
options.configure(builder);
|
|
270
|
+
}
|
|
271
|
+
const results = await builder.run();
|
|
272
|
+
return results.map(instance => viewDef.project(instance));
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Batch-load many-to-many related records through a junction table.
|
|
276
|
+
*
|
|
277
|
+
* Given an array of source IDs, fetches all related records and groups them
|
|
278
|
+
* by source ID. Handles both direct and through (junction table) relations,
|
|
279
|
+
* automatically applying revision system guards when needed.
|
|
280
|
+
*
|
|
281
|
+
* @param relationName - Name of the relation from the manifest
|
|
282
|
+
* @param sourceIds - Array of source record IDs to load relations for
|
|
283
|
+
* @returns Map of source ID to array of related model instances
|
|
284
|
+
*
|
|
285
|
+
* @example
|
|
286
|
+
* // Load all teams for multiple reviews
|
|
287
|
+
* const reviewTeamMap = await Review.loadManyRelated('teams', reviewIds);
|
|
288
|
+
* reviewTeamMap.get(reviewId) // => TeamInstance[]
|
|
289
|
+
*/
|
|
290
|
+
static async loadManyRelated(relationName, sourceIds) {
|
|
291
|
+
const resultMap = new Map();
|
|
292
|
+
// Validate inputs
|
|
293
|
+
const uniqueIds = [
|
|
294
|
+
...new Set(sourceIds.filter((id) => typeof id === 'string' && id.length > 0)),
|
|
295
|
+
];
|
|
296
|
+
if (uniqueIds.length === 0) {
|
|
297
|
+
return resultMap;
|
|
298
|
+
}
|
|
299
|
+
// Get relation metadata
|
|
300
|
+
const relationConfig = this.getRelation(relationName);
|
|
301
|
+
if (!relationConfig) {
|
|
302
|
+
const availableRelations = this.getRelations().map(r => r.name);
|
|
303
|
+
const suggestion = availableRelations.length > 0
|
|
304
|
+
? ` Available relations: ${availableRelations.join(', ')}`
|
|
305
|
+
: ' No relations defined for this model.';
|
|
306
|
+
throw new Error(`Relation '${relationName}' not found for model '${this.tableName}'.${suggestion}`);
|
|
307
|
+
}
|
|
308
|
+
// Get target model
|
|
309
|
+
const targetModelKey = relationConfig.targetModelKey || relationConfig.targetTable;
|
|
310
|
+
let TargetModel;
|
|
311
|
+
try {
|
|
312
|
+
TargetModel = this.dal.getModel(targetModelKey);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
throw new Error(`Target model '${targetModelKey}' not found for relation '${relationName}': ${error instanceof Error ? error.message : String(error)}`);
|
|
316
|
+
}
|
|
317
|
+
// Resolve table names
|
|
318
|
+
const schemaNamespace = this.dal.schemaNamespace || '';
|
|
319
|
+
const targetTableName = schemaNamespace
|
|
320
|
+
? `${schemaNamespace}${relationConfig.targetTable}`
|
|
321
|
+
: relationConfig.targetTable;
|
|
322
|
+
// Select the target model's safe columns so sensitive fields stay out,
|
|
323
|
+
// as they do for inline joins
|
|
324
|
+
const safeColumns = TargetModel.getSafeColumnNames?.() ?? [];
|
|
325
|
+
const targetColumns = (prefix) => safeColumns.length > 0
|
|
326
|
+
? safeColumns.map(column => `${prefix}${column}`).join(', ')
|
|
327
|
+
: `${prefix}*`;
|
|
328
|
+
// Build query based on relation type
|
|
329
|
+
let query;
|
|
330
|
+
const params = uniqueIds;
|
|
331
|
+
if (relationConfig.through && relationConfig.joinType === 'through') {
|
|
332
|
+
// Many-to-many through junction table
|
|
333
|
+
const junctionTableName = schemaNamespace
|
|
334
|
+
? `${schemaNamespace}${relationConfig.through.table}`
|
|
335
|
+
: relationConfig.through.table;
|
|
336
|
+
const junctionSourceColumn = relationConfig.through.sourceColumn;
|
|
337
|
+
const junctionTargetColumn = relationConfig.through.targetColumn;
|
|
338
|
+
const targetColumn = relationConfig.targetColumn || 'id';
|
|
339
|
+
const placeholders = uniqueIds.map((_, index) => `$${index + 1}`).join(', ');
|
|
340
|
+
// Build SELECT with junction table join
|
|
341
|
+
query = `
|
|
342
|
+
SELECT
|
|
343
|
+
j.${junctionSourceColumn} AS __source_id,
|
|
344
|
+
${targetColumns('t.')}
|
|
345
|
+
FROM ${targetTableName} t
|
|
346
|
+
JOIN ${junctionTableName} j ON t.${targetColumn} = j.${junctionTargetColumn}
|
|
347
|
+
WHERE j.${junctionSourceColumn} IN (${placeholders})
|
|
348
|
+
`;
|
|
349
|
+
// Add revision guards for target table if needed
|
|
350
|
+
if (relationConfig.hasRevisions) {
|
|
351
|
+
query += `
|
|
352
|
+
AND (t._old_rev_of IS NULL)
|
|
353
|
+
AND (t._rev_deleted IS NULL OR t._rev_deleted = false)
|
|
354
|
+
`;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
else {
|
|
358
|
+
// Direct one-to-many relation
|
|
359
|
+
const targetColumn = relationConfig.targetColumn || 'id';
|
|
360
|
+
const placeholders = uniqueIds.map((_, index) => `$${index + 1}`).join(', ');
|
|
361
|
+
query = `
|
|
362
|
+
SELECT
|
|
363
|
+
${targetColumn} AS __source_id,
|
|
364
|
+
${targetColumns('')}
|
|
365
|
+
FROM ${targetTableName}
|
|
366
|
+
WHERE ${targetColumn} IN (${placeholders})
|
|
367
|
+
`;
|
|
368
|
+
// Add revision guards if needed
|
|
369
|
+
if (relationConfig.hasRevisions) {
|
|
370
|
+
query += `
|
|
371
|
+
AND (_old_rev_of IS NULL)
|
|
372
|
+
AND (_rev_deleted IS NULL OR _rev_deleted = false)
|
|
373
|
+
`;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
// Execute query
|
|
377
|
+
const result = await this.dal.query(query, params);
|
|
378
|
+
// Group results by source ID
|
|
379
|
+
result.rows.forEach(row => {
|
|
380
|
+
const sourceId = row.__source_id;
|
|
381
|
+
if (!sourceId || typeof sourceId !== 'string') {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
// Create instance from row (excluding our __source_id marker)
|
|
385
|
+
const rowData = { ...row };
|
|
386
|
+
delete rowData.__source_id;
|
|
387
|
+
// Manifest models provide createFromRow(); fall back to _createInstance()
|
|
388
|
+
const target = TargetModel;
|
|
389
|
+
const instance = (typeof target.createFromRow === 'function'
|
|
390
|
+
? target.createFromRow(rowData)
|
|
391
|
+
: target._createInstance?.(rowData));
|
|
392
|
+
if (!resultMap.has(sourceId)) {
|
|
393
|
+
resultMap.set(sourceId, []);
|
|
394
|
+
}
|
|
395
|
+
resultMap.get(sourceId)?.push(instance);
|
|
396
|
+
});
|
|
397
|
+
return resultMap;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Batch-insert associations into a many-to-many junction table.
|
|
401
|
+
*
|
|
402
|
+
* This helper creates associations between a single source record and multiple target records
|
|
403
|
+
* by inserting rows into a junction table. It automatically handles:
|
|
404
|
+
* - Schema namespace prefixing for test isolation
|
|
405
|
+
* - Duplicate associations via ON CONFLICT DO NOTHING
|
|
406
|
+
* - Input validation with helpful error messages
|
|
407
|
+
*
|
|
408
|
+
* @param relationName - Name of the relation defined in the manifest (must have a `through` junction table)
|
|
409
|
+
* @param sourceId - ID of the source record to associate from
|
|
410
|
+
* @param targetIds - Array of target record IDs to associate with
|
|
411
|
+
* @param options - Optional configuration
|
|
412
|
+
* @param options.onConflict - How to handle duplicate associations: 'ignore' (default) or 'error'
|
|
413
|
+
* @throws {Error} If relation not found, has no junction table, or inputs are invalid
|
|
414
|
+
*
|
|
415
|
+
* @example
|
|
416
|
+
* ```ts
|
|
417
|
+
* // Associate a thing with multiple files
|
|
418
|
+
* await Thing.addManyRelated('files', thingId, [file1.id, file2.id]);
|
|
419
|
+
*
|
|
420
|
+
* // Associate a review with teams
|
|
421
|
+
* await Review.addManyRelated('teams', reviewId, teamIds, { onConflict: 'error' });
|
|
422
|
+
* ```
|
|
423
|
+
*/
|
|
424
|
+
static async addManyRelated(relationName, sourceId, targetIds, options) {
|
|
425
|
+
// Validate inputs
|
|
426
|
+
if (!sourceId || typeof sourceId !== 'string') {
|
|
427
|
+
throw new Error(`Invalid sourceId: expected non-empty string, got ${typeof sourceId === 'string' ? 'empty string' : typeof sourceId}`);
|
|
428
|
+
}
|
|
429
|
+
const uniqueIds = [
|
|
430
|
+
...new Set(targetIds.filter((id) => typeof id === 'string' && id.length > 0)),
|
|
431
|
+
];
|
|
432
|
+
if (uniqueIds.length === 0) {
|
|
433
|
+
return; // Nothing to insert
|
|
434
|
+
}
|
|
435
|
+
// Get relation metadata
|
|
436
|
+
const relationConfig = this.getRelation(relationName);
|
|
437
|
+
if (!relationConfig) {
|
|
438
|
+
const availableRelations = this.getRelations().map(r => r.name);
|
|
439
|
+
const suggestion = availableRelations.length > 0
|
|
440
|
+
? ` Available relations: ${availableRelations.join(', ')}`
|
|
441
|
+
: ' No relations defined for this model.';
|
|
442
|
+
throw new Error(`Relation '${relationName}' not found for model '${this.tableName}'.${suggestion}`);
|
|
443
|
+
}
|
|
444
|
+
// Validate that this is a many-to-many relation with junction table
|
|
445
|
+
if (!relationConfig.through || relationConfig.joinType !== 'through') {
|
|
446
|
+
throw new Error(`Relation '${relationName}' is not a many-to-many relation with a junction table. ` +
|
|
447
|
+
`Only relations with 'through' configuration support addManyRelated.`);
|
|
448
|
+
}
|
|
449
|
+
// Resolve table names with schema namespace
|
|
450
|
+
const schemaNamespace = this.dal.schemaNamespace || '';
|
|
451
|
+
const junctionTableName = schemaNamespace
|
|
452
|
+
? `${schemaNamespace}${relationConfig.through.table}`
|
|
453
|
+
: relationConfig.through.table;
|
|
454
|
+
const junctionSourceColumn = relationConfig.through.sourceColumn;
|
|
455
|
+
const junctionTargetColumn = relationConfig.through.targetColumn;
|
|
456
|
+
// Build parameterized INSERT query
|
|
457
|
+
const valueClauses = [];
|
|
458
|
+
const params = [];
|
|
459
|
+
let paramIndex = 1;
|
|
460
|
+
uniqueIds.forEach(targetId => {
|
|
461
|
+
valueClauses.push(`($${paramIndex}, $${paramIndex + 1})`);
|
|
462
|
+
params.push(sourceId, targetId);
|
|
463
|
+
paramIndex += 2;
|
|
464
|
+
});
|
|
465
|
+
const onConflictClause = options?.onConflict === 'error' ? '' : 'ON CONFLICT DO NOTHING';
|
|
466
|
+
const query = `
|
|
467
|
+
INSERT INTO ${junctionTableName} (${junctionSourceColumn}, ${junctionTargetColumn})
|
|
468
|
+
VALUES ${valueClauses.join(', ')}
|
|
469
|
+
${onConflictClause}
|
|
470
|
+
`;
|
|
471
|
+
// Execute insert
|
|
472
|
+
await this.dal.query(query, params);
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Get the database field name for a given property name
|
|
476
|
+
* @param propertyName - Property name (camelCase or snake_case)
|
|
477
|
+
* @returns Database field name (snake_case)
|
|
478
|
+
*/
|
|
479
|
+
static _getDbFieldName(propertyName) {
|
|
480
|
+
return this._fieldMappings.get(propertyName) || propertyName;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Get list of database column names filtered by criteria
|
|
484
|
+
* @param filterFn - Filter function for field entries
|
|
485
|
+
* @returns Array of database column names
|
|
486
|
+
* @private
|
|
487
|
+
*/
|
|
488
|
+
static _getFilteredColumnNames(filterFn) {
|
|
489
|
+
const schema = this.schema;
|
|
490
|
+
if (!schema)
|
|
491
|
+
return [];
|
|
492
|
+
return Object.entries(schema)
|
|
493
|
+
.filter(filterFn)
|
|
494
|
+
.map(([fieldName]) => this._getDbFieldName(fieldName));
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Get list of non-sensitive database column names for safe querying
|
|
498
|
+
* Excludes fields marked as sensitive and virtual fields
|
|
499
|
+
* @returns Array of database column names
|
|
500
|
+
*/
|
|
501
|
+
static getSafeColumnNames() {
|
|
502
|
+
return this._getFilteredColumnNames(([, fieldDef]) => fieldDef && !fieldDef.isVirtual && !fieldDef.isSensitive);
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Get list of database column names including specified sensitive fields
|
|
506
|
+
* @param includeSensitive - Array of sensitive field names to include
|
|
507
|
+
* @returns Array of database column names
|
|
508
|
+
*/
|
|
509
|
+
static getColumnNames(includeSensitive = []) {
|
|
510
|
+
return this._getFilteredColumnNames(([fieldName, fieldDef]) => {
|
|
511
|
+
if (!fieldDef || fieldDef.isVirtual)
|
|
512
|
+
return false;
|
|
513
|
+
if (fieldDef.isSensitive && !includeSensitive.includes(fieldName))
|
|
514
|
+
return false;
|
|
515
|
+
return true;
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Get list of sensitive field names in the schema
|
|
520
|
+
* @returns Array of field names (camelCase)
|
|
521
|
+
*/
|
|
522
|
+
static getSensitiveFieldNames() {
|
|
523
|
+
const schema = this.schema;
|
|
524
|
+
if (!schema)
|
|
525
|
+
return [];
|
|
526
|
+
return Object.entries(schema)
|
|
527
|
+
.filter(([, fieldDef]) => fieldDef && fieldDef.isSensitive)
|
|
528
|
+
.map(([fieldName]) => fieldName);
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Create a new model class
|
|
532
|
+
* @param tableName - Database table name
|
|
533
|
+
* @param schema - Model schema definition
|
|
534
|
+
* @param options - Model options
|
|
535
|
+
* @param dal - DAL instance
|
|
536
|
+
* @returns Model constructor
|
|
537
|
+
*/
|
|
538
|
+
static createModel(tableName, schema, options, dal) {
|
|
539
|
+
// Create the model constructor
|
|
540
|
+
class DynamicModel extends Model {
|
|
541
|
+
static _fieldMappings = new Map();
|
|
542
|
+
static _relations = new Map();
|
|
543
|
+
static _views = new Map();
|
|
544
|
+
static get tableName() {
|
|
545
|
+
return tableName;
|
|
546
|
+
}
|
|
547
|
+
static get schema() {
|
|
548
|
+
return schema;
|
|
549
|
+
}
|
|
550
|
+
static get options() {
|
|
551
|
+
return options;
|
|
552
|
+
}
|
|
553
|
+
static get dal() {
|
|
554
|
+
return dal;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return DynamicModel;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Get a record by ID
|
|
561
|
+
* @param id - Record ID
|
|
562
|
+
* @param options - Query options
|
|
563
|
+
* @param options.includeSensitive - Array of sensitive field names to include
|
|
564
|
+
* @param options (other properties) - Join options for related data (e.g., {teams: true})
|
|
565
|
+
* @returns Model instance
|
|
566
|
+
*/
|
|
567
|
+
static async get(id, options = {}) {
|
|
568
|
+
// Extract includeSensitive option, rest are join options
|
|
569
|
+
const { includeSensitive, ...joinOptions } = options;
|
|
570
|
+
const builder = this.filterWhere({}).includeDeleted().includeStale();
|
|
571
|
+
const idField = 'id';
|
|
572
|
+
if (isUUID.v4(id)) {
|
|
573
|
+
builder.whereIn(idField, [id], { cast: 'uuid[]' });
|
|
574
|
+
}
|
|
575
|
+
else {
|
|
576
|
+
builder.whereIn(idField, [id]);
|
|
577
|
+
}
|
|
578
|
+
if (includeSensitive && includeSensitive.length > 0) {
|
|
579
|
+
builder.includeSensitive(includeSensitive);
|
|
580
|
+
}
|
|
581
|
+
if (Object.keys(joinOptions).length > 0) {
|
|
582
|
+
builder.getJoin(joinOptions);
|
|
583
|
+
}
|
|
584
|
+
const result = await builder.first();
|
|
585
|
+
if (!result) {
|
|
586
|
+
throw new DocumentNotFound(`${this.tableName} with id ${id} not found`);
|
|
587
|
+
}
|
|
588
|
+
return result;
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Get multiple records by IDs
|
|
592
|
+
* @param ids - Record IDs
|
|
593
|
+
* @returns Array of model instances
|
|
594
|
+
*/
|
|
595
|
+
static async getAll(...ids) {
|
|
596
|
+
if (ids.length === 0) {
|
|
597
|
+
return [];
|
|
598
|
+
}
|
|
599
|
+
const builder = this.filterWhere({}).includeDeleted().includeStale();
|
|
600
|
+
const idField = 'id';
|
|
601
|
+
const cast = ids.length > 0 && ids.every(id => isUUID.v4(id)) ? 'uuid[]' : undefined;
|
|
602
|
+
if (cast) {
|
|
603
|
+
builder.whereIn(idField, ids, { cast });
|
|
604
|
+
}
|
|
605
|
+
else {
|
|
606
|
+
builder.whereIn(idField, ids);
|
|
607
|
+
}
|
|
608
|
+
const results = await builder.run();
|
|
609
|
+
return results;
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Create a new record
|
|
613
|
+
* @param data - Record data
|
|
614
|
+
* @param options - Creation options
|
|
615
|
+
* @returns Created model instance
|
|
616
|
+
*/
|
|
617
|
+
static async create(data, options = {}) {
|
|
618
|
+
const instance = new this(data);
|
|
619
|
+
await instance.save(options);
|
|
620
|
+
return instance;
|
|
621
|
+
}
|
|
622
|
+
/** Atomically insert or update selected fields of a non-revisioned model. */
|
|
623
|
+
static async upsert(data, options) {
|
|
624
|
+
assertTransactionClient(options.transaction);
|
|
625
|
+
if (Object.hasOwn(this.schema, '_revID')) {
|
|
626
|
+
throw new Error('Upsert is not supported for revisioned models.');
|
|
627
|
+
}
|
|
628
|
+
const quote = (identifier) => `"${identifier.replaceAll('"', '""')}"`;
|
|
629
|
+
const checkField = (field) => {
|
|
630
|
+
if (!Object.hasOwn(this.schema, field) || this.schema[field].isVirtual) {
|
|
631
|
+
throw new Error(`Invalid persisted schema field '${field}' in upsert.`);
|
|
632
|
+
}
|
|
633
|
+
return this._getDbFieldName(field);
|
|
634
|
+
};
|
|
635
|
+
const checkList = (fields, name) => {
|
|
636
|
+
if (!Array.isArray(fields) || fields.length === 0 || new Set(fields).size !== fields.length) {
|
|
637
|
+
throw new Error(`${name} must be a non-empty array of distinct schema fields.`);
|
|
638
|
+
}
|
|
639
|
+
for (const field of fields)
|
|
640
|
+
checkField(field);
|
|
641
|
+
};
|
|
642
|
+
checkList(options.conflictFields, 'conflictFields');
|
|
643
|
+
checkList(options.updateFields, 'updateFields');
|
|
644
|
+
for (const field of Object.keys(data))
|
|
645
|
+
checkField(field);
|
|
646
|
+
for (const field of [...(options.updateSensitive ?? []), ...(options.includeSensitive ?? [])]) {
|
|
647
|
+
checkField(field);
|
|
648
|
+
}
|
|
649
|
+
for (const field of options.updateFields) {
|
|
650
|
+
if (!Object.hasOwn(data, field) || data[field] === undefined) {
|
|
651
|
+
throw new Error(`Upsert update field '${field}' requires an explicit insert value.`);
|
|
652
|
+
}
|
|
653
|
+
if (this.schema[field].isSensitive && !options.updateSensitive?.includes(field)) {
|
|
654
|
+
throw new Error(`Upsert update of sensitive field '${field}' requires updateSensitive.`);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
const instance = new this(data);
|
|
658
|
+
instance._validate();
|
|
659
|
+
for (const field of options.conflictFields) {
|
|
660
|
+
if (instance.getValue(field) == null) {
|
|
661
|
+
throw new Error(`Upsert conflict field '${field}' requires a non-null value.`);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
const fields = Object.keys(this.schema)
|
|
665
|
+
.filter(field => !this.schema[field].isVirtual)
|
|
666
|
+
.map(field => checkField(field))
|
|
667
|
+
.filter(field => instance._data[field] !== undefined);
|
|
668
|
+
const updates = options.updateFields.map(field => {
|
|
669
|
+
const column = quote(checkField(field));
|
|
670
|
+
return `${column} = EXCLUDED.${column}`;
|
|
671
|
+
});
|
|
672
|
+
const returning = this.getColumnNames([...(options.includeSensitive ?? [])]).map(quote);
|
|
673
|
+
try {
|
|
674
|
+
const result = await this.dal.query(`INSERT INTO ${this.tableName} (${fields.map(quote).join(', ')})
|
|
675
|
+
VALUES (${fields.map((_, index) => `$${index + 1}`).join(', ')})
|
|
676
|
+
ON CONFLICT (${options.conflictFields.map(field => quote(checkField(field))).join(', ')})
|
|
677
|
+
DO UPDATE SET ${updates.join(', ')} RETURNING ${returning.join(', ')}`, fields.map(field => instance._data[field]), options.transaction ?? null);
|
|
678
|
+
const persisted = this._createInstance(result.rows[0]);
|
|
679
|
+
// Construction applies defaults, including defaults on omitted sensitive fields.
|
|
680
|
+
for (const field of this.getSensitiveFieldNames()) {
|
|
681
|
+
if (!options.includeSensitive?.includes(field)) {
|
|
682
|
+
delete persisted._data[this._getDbFieldName(field)];
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
persisted._trackOriginalValues();
|
|
686
|
+
persisted.generateVirtualValues();
|
|
687
|
+
return persisted;
|
|
688
|
+
}
|
|
689
|
+
catch (error) {
|
|
690
|
+
throw convertPostgreSQLError(error);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
/*
|
|
694
|
+
*
|
|
695
|
+
* Update a record by ID
|
|
696
|
+
* @param id - Record ID
|
|
697
|
+
* @param data - Update data
|
|
698
|
+
* @returns Updated model instance
|
|
699
|
+
*/
|
|
700
|
+
static async update(id, data) {
|
|
701
|
+
const instance = await this.get(id);
|
|
702
|
+
for (const [key, value] of Object.entries(data || {})) {
|
|
703
|
+
instance.setValue(key, value);
|
|
704
|
+
}
|
|
705
|
+
await instance.save();
|
|
706
|
+
return instance;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Delete a record by ID. Models with revision tracking require
|
|
710
|
+
* `{ purge: true }`, which also removes the document's archived revisions;
|
|
711
|
+
* use `deleteAllRevisions(user)` to soft-delete instead.
|
|
712
|
+
* @param id - Record ID
|
|
713
|
+
* @param options - Delete options
|
|
714
|
+
* @returns Success status
|
|
715
|
+
*/
|
|
716
|
+
static async delete(id, options = {}) {
|
|
717
|
+
const query = new QueryBuilder(this, this.dal);
|
|
718
|
+
const result = await query.deleteById(id, options);
|
|
719
|
+
return result > 0;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Create query builder for ordering
|
|
723
|
+
* @param field - Field to order by
|
|
724
|
+
* @param direction - Sort direction (ASC/DESC)
|
|
725
|
+
* @returns Query builder
|
|
726
|
+
*/
|
|
727
|
+
static orderBy(field, direction = 'ASC') {
|
|
728
|
+
const query = new QueryBuilder(this, this.dal);
|
|
729
|
+
return query.orderBy(field, direction);
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Create query builder with limit
|
|
733
|
+
* @param count - Limit count
|
|
734
|
+
* @returns Query builder
|
|
735
|
+
*/
|
|
736
|
+
static limit(count) {
|
|
737
|
+
const query = new QueryBuilder(this, this.dal);
|
|
738
|
+
return query.limit(count);
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Create query builder with joins
|
|
742
|
+
* @param joinSpec - Join specification
|
|
743
|
+
* @returns Query builder
|
|
744
|
+
*/
|
|
745
|
+
static getJoin(joinSpec) {
|
|
746
|
+
const query = new QueryBuilder(this, this.dal);
|
|
747
|
+
return query.getJoin(joinSpec);
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Create query builder with date range filter
|
|
751
|
+
* @param startDate - Start date
|
|
752
|
+
* @param endDate - End date
|
|
753
|
+
* @param options - Options for the range
|
|
754
|
+
* @returns Query builder
|
|
755
|
+
*/
|
|
756
|
+
static between(startDate, endDate, options = {}) {
|
|
757
|
+
const query = new QueryBuilder(this, this.dal);
|
|
758
|
+
return query.between(startDate, endDate, options);
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Create query builder with array contains filter
|
|
762
|
+
* @param field - Field name
|
|
763
|
+
* @param value - Value to check for
|
|
764
|
+
* @returns Query builder
|
|
765
|
+
*/
|
|
766
|
+
static contains(field, value) {
|
|
767
|
+
const query = new QueryBuilder(this, this.dal);
|
|
768
|
+
return query.contains(field, value);
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Get multiple records by IDs, excluding stale and deleted revisions
|
|
772
|
+
* @param ids - Record IDs
|
|
773
|
+
* @returns Query builder for chaining
|
|
774
|
+
*/
|
|
775
|
+
static getMultipleNotStaleOrDeleted(ids) {
|
|
776
|
+
const builder = this.filterWhere({});
|
|
777
|
+
const idField = 'id';
|
|
778
|
+
if (ids.length === 0) {
|
|
779
|
+
return builder.limit(0);
|
|
780
|
+
}
|
|
781
|
+
const cast = ids.every(id => isUUID.v4(id)) ? 'uuid[]' : undefined;
|
|
782
|
+
if (cast) {
|
|
783
|
+
return builder.whereIn(idField, ids, { cast });
|
|
784
|
+
}
|
|
785
|
+
return builder.whereIn(idField, ids);
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Create a model instance from database result
|
|
789
|
+
* @param data - Database row data
|
|
790
|
+
* @returns Model instance
|
|
791
|
+
* @private
|
|
792
|
+
*/
|
|
793
|
+
static _createInstance(data) {
|
|
794
|
+
// If data is already a Model instance, extract the raw database data
|
|
795
|
+
const rawData = data instanceof this && typeof data._data === 'object' ? data._data : data;
|
|
796
|
+
const instance = new this(rawData);
|
|
797
|
+
// The public type is `ModelInstance`, but internally we still operate on the
|
|
798
|
+
// concrete `Model` subclass so we can reuse protected helpers like
|
|
799
|
+
// `_setupPropertyAccessors` and `_trackOriginalValues`. Casting through
|
|
800
|
+
// `unknown` keeps those internals hidden from the consumer-facing types.
|
|
801
|
+
const runtimeInstance = instance;
|
|
802
|
+
runtimeInstance._isNew = false;
|
|
803
|
+
runtimeInstance._changed.clear();
|
|
804
|
+
runtimeInstance._setupPropertyAccessors();
|
|
805
|
+
runtimeInstance._trackOriginalValues();
|
|
806
|
+
return runtimeInstance;
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Define an instance method on the model
|
|
810
|
+
* @param name - Method name
|
|
811
|
+
* @param method - Method function
|
|
812
|
+
*/
|
|
813
|
+
static define(name, method) {
|
|
814
|
+
this.prototype[name] = method;
|
|
815
|
+
if (name === 'newRevision' || name === 'deleteAllRevisions') {
|
|
816
|
+
if (!this._revisionHandlers) {
|
|
817
|
+
this._revisionHandlers = {};
|
|
818
|
+
}
|
|
819
|
+
this._revisionHandlers[name] = method;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Save the model instance
|
|
824
|
+
* @param options - Save options
|
|
825
|
+
* @returns This instance
|
|
826
|
+
*/
|
|
827
|
+
async save(options = {}) {
|
|
828
|
+
assertTransactionClient(options.transaction);
|
|
829
|
+
try {
|
|
830
|
+
// Detect in-place modifications to JSONB fields before validation
|
|
831
|
+
this._detectInPlaceChanges();
|
|
832
|
+
// Validate data (may also mark fields as changed if validation transforms them)
|
|
833
|
+
this._validate();
|
|
834
|
+
const pending = this._isNew ? null : this._pendingRevision;
|
|
835
|
+
if (pending) {
|
|
836
|
+
// Update the current row and archive the previous revision atomically
|
|
837
|
+
const snapshot = this._snapshotSaveState();
|
|
838
|
+
try {
|
|
839
|
+
await runInTransaction(this.runtime.dal, options.transaction, async (client) => {
|
|
840
|
+
await this._update({ ...options, transaction: client }, pending.expectedRevId);
|
|
841
|
+
await this._insertArchivedRevision(pending.archive, client);
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
catch (error) {
|
|
845
|
+
this._restoreSaveState(snapshot);
|
|
846
|
+
throw error;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
else if (this._isNew) {
|
|
850
|
+
await this._insert(options);
|
|
851
|
+
}
|
|
852
|
+
else {
|
|
853
|
+
await this._update(options);
|
|
854
|
+
}
|
|
855
|
+
this._isNew = false;
|
|
856
|
+
this._pendingRevision = null;
|
|
857
|
+
this._changed.clear();
|
|
858
|
+
// Refresh original values after successful save to track future in-place modifications
|
|
859
|
+
this._trackOriginalValues();
|
|
860
|
+
// Regenerate virtual fields after save in case they depend on saved data
|
|
861
|
+
this.generateVirtualValues();
|
|
862
|
+
return this;
|
|
863
|
+
}
|
|
864
|
+
catch (error) {
|
|
865
|
+
throw convertPostgreSQLError(error);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Persist this instance and synchronize any many-to-many relations.
|
|
870
|
+
*
|
|
871
|
+
* ⚠️ Only `through` relations whose join tables contain *just*
|
|
872
|
+
* foreign keys are managed automatically. If the join table carries
|
|
873
|
+
* additional editable columns (role flags, metadata, timestamps that
|
|
874
|
+
* should be user-controlled, etc.), mutate that table directly instead
|
|
875
|
+
* of relying on {@link saveAll}, because the DAL currently treats
|
|
876
|
+
* relation membership as an ID-only diff.
|
|
877
|
+
*
|
|
878
|
+
* @param joinOptions - Optional map of relation names to include.
|
|
879
|
+
* When omitted, every declared `through` relation is synchronized.
|
|
880
|
+
* @returns This instance
|
|
881
|
+
*/
|
|
882
|
+
async saveAll(joinOptions = {}, options = {}) {
|
|
883
|
+
const snapshot = this._snapshotSaveState();
|
|
884
|
+
try {
|
|
885
|
+
// Save the record and its relations atomically
|
|
886
|
+
await runInTransaction(this.runtime.dal, options.transaction, async (client) => {
|
|
887
|
+
await this.save({ ...options, transaction: client });
|
|
888
|
+
const relations = this.runtime.getRelations();
|
|
889
|
+
for (const { name, config } of relations) {
|
|
890
|
+
// Only handle many-to-many relationships with through tables for now
|
|
891
|
+
if (config.cardinality !== 'many' || !config.through)
|
|
892
|
+
continue;
|
|
893
|
+
// Get the related data from this instance
|
|
894
|
+
const relatedData = this[name];
|
|
895
|
+
if (!relatedData)
|
|
896
|
+
continue;
|
|
897
|
+
// If joinOptions is explicitly provided, only process requested relationships
|
|
898
|
+
// If joinOptions is empty (default), process all relationships
|
|
899
|
+
const isExplicitOptions = Object.keys(joinOptions).length > 0;
|
|
900
|
+
if (isExplicitOptions && !joinOptions[name])
|
|
901
|
+
continue;
|
|
902
|
+
await this._saveManyToManyRelation(name, config, relatedData, client);
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
catch (error) {
|
|
907
|
+
// The transaction rolled back, so the instance must not look saved
|
|
908
|
+
this._restoreSaveState(snapshot);
|
|
909
|
+
throw error;
|
|
910
|
+
}
|
|
911
|
+
return this;
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Capture the instance state that a save mutates.
|
|
915
|
+
* @private
|
|
916
|
+
*/
|
|
917
|
+
_snapshotSaveState() {
|
|
918
|
+
return {
|
|
919
|
+
// Shallow is enough: saving only replaces top-level values (validation,
|
|
920
|
+
// RETURNING), never mutates nested ones. Keeping the caller's nested
|
|
921
|
+
// objects also means references they hold stay attached to the instance.
|
|
922
|
+
data: { ...this._data },
|
|
923
|
+
changed: new Set(this._changed),
|
|
924
|
+
isNew: this._isNew,
|
|
925
|
+
pendingRevision: this._pendingRevision,
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Restore state captured by {@link Model._snapshotSaveState} after a rollback.
|
|
930
|
+
* @private
|
|
931
|
+
*/
|
|
932
|
+
_restoreSaveState(snapshot) {
|
|
933
|
+
this._data = snapshot.data;
|
|
934
|
+
this._changed = snapshot.changed;
|
|
935
|
+
this._isNew = snapshot.isNew;
|
|
936
|
+
this._pendingRevision = snapshot.pendingRevision;
|
|
937
|
+
this._trackOriginalValues();
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Insert the archived copy of the previous revision.
|
|
941
|
+
* @param archive - Row snapshot, with `_old_rev_of` set and no `id`
|
|
942
|
+
* @param client - Transaction client
|
|
943
|
+
* @private
|
|
944
|
+
*/
|
|
945
|
+
async _insertArchivedRevision(archive, client) {
|
|
946
|
+
const tableName = this.runtime.tableName;
|
|
947
|
+
const fields = Object.keys(archive).filter(key => archive[key] !== undefined);
|
|
948
|
+
// Column names are interpolated, so only plain identifiers are allowed
|
|
949
|
+
for (const field of fields) {
|
|
950
|
+
if (!SAFE_IDENTIFIER.test(field)) {
|
|
951
|
+
throw new Error(`Invalid field name '${field}' in ${tableName} revision archive.`);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
const values = fields.map(key => archive[key]);
|
|
955
|
+
const placeholders = fields.map((_, index) => `$${index + 1}`);
|
|
956
|
+
const query = `
|
|
957
|
+
INSERT INTO ${tableName} (${fields.join(', ')})
|
|
958
|
+
VALUES (${placeholders.join(', ')})
|
|
959
|
+
`;
|
|
960
|
+
await this.runtime.dal.query(query, values, client);
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Save a many-to-many relationship through a join table
|
|
964
|
+
* @param relationName - Name of the relation
|
|
965
|
+
* @param config - Relation configuration
|
|
966
|
+
* @param relatedData - Array of related model instances or IDs
|
|
967
|
+
* @private
|
|
968
|
+
*/
|
|
969
|
+
async _saveManyToManyRelation(relationName, config, relatedData, client = null) {
|
|
970
|
+
if (!Array.isArray(relatedData)) {
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
const { through } = config;
|
|
974
|
+
const schemaNamespace = this.runtime.dal.schemaNamespace || '';
|
|
975
|
+
const joinTableName = schemaNamespace ? `${schemaNamespace}${through.table}` : through.table;
|
|
976
|
+
const getBaseName = value => {
|
|
977
|
+
if (!value)
|
|
978
|
+
return '';
|
|
979
|
+
const segments = String(value).split('.');
|
|
980
|
+
return segments[segments.length - 1];
|
|
981
|
+
};
|
|
982
|
+
const sourceBase = getBaseName(this.runtime.tableName);
|
|
983
|
+
const targetBase = getBaseName(config.targetTable);
|
|
984
|
+
// Normalized relations store the join columns as sourceColumn/targetColumn
|
|
985
|
+
const sourceColumn = through.sourceColumn || through.sourceForeignKey || `${sourceBase.replace(/s$/, '')}_id`;
|
|
986
|
+
const targetColumn = through.targetColumn || through.targetForeignKey || `${targetBase.replace(/s$/, '')}_id`;
|
|
987
|
+
const desiredIds = [];
|
|
988
|
+
const desiredSet = new Set();
|
|
989
|
+
for (const item of relatedData) {
|
|
990
|
+
const itemId = typeof item === 'string' ? item : item?.id;
|
|
991
|
+
if (!itemId)
|
|
992
|
+
continue;
|
|
993
|
+
if (desiredSet.has(itemId)) {
|
|
994
|
+
throw new Error(`Duplicate entry detected while saving ${relationName} relation: ${itemId}`);
|
|
995
|
+
}
|
|
996
|
+
desiredIds.push(itemId);
|
|
997
|
+
desiredSet.add(itemId);
|
|
998
|
+
}
|
|
999
|
+
try {
|
|
1000
|
+
const existingResult = await this.runtime.dal.query(`SELECT ${targetColumn} FROM ${joinTableName} WHERE ${sourceColumn} = $1`, [this.id], client);
|
|
1001
|
+
const existingIds = new Set(existingResult.rows
|
|
1002
|
+
.map(row => row && row[targetColumn])
|
|
1003
|
+
.filter((value) => typeof value === 'string' && value.length > 0));
|
|
1004
|
+
const idsToRemove = [...existingIds].filter(id => !desiredSet.has(id));
|
|
1005
|
+
if (idsToRemove.length > 0) {
|
|
1006
|
+
const deleteParams = [this.id, ...idsToRemove];
|
|
1007
|
+
const placeholders = idsToRemove.map((_, index) => `$${index + 2}`).join(', ');
|
|
1008
|
+
const deleteQuery = `
|
|
1009
|
+
DELETE FROM ${joinTableName}
|
|
1010
|
+
WHERE ${sourceColumn} = $1
|
|
1011
|
+
AND ${targetColumn} IN (${placeholders})
|
|
1012
|
+
`;
|
|
1013
|
+
await this.runtime.dal.query(deleteQuery, deleteParams, client);
|
|
1014
|
+
}
|
|
1015
|
+
const idsToAdd = desiredIds.filter(id => !existingIds.has(id));
|
|
1016
|
+
if (idsToAdd.length > 0) {
|
|
1017
|
+
const values = [];
|
|
1018
|
+
const params = [];
|
|
1019
|
+
let paramIndex = 1;
|
|
1020
|
+
for (const itemId of idsToAdd) {
|
|
1021
|
+
values.push(`($${paramIndex}, $${paramIndex + 1})`);
|
|
1022
|
+
params.push(this.id, itemId);
|
|
1023
|
+
paramIndex += 2;
|
|
1024
|
+
}
|
|
1025
|
+
const insertQuery = `
|
|
1026
|
+
INSERT INTO ${joinTableName} (${sourceColumn}, ${targetColumn})
|
|
1027
|
+
VALUES ${values.join(', ')}
|
|
1028
|
+
ON CONFLICT (${sourceColumn}, ${targetColumn}) DO NOTHING
|
|
1029
|
+
`;
|
|
1030
|
+
await this.runtime.dal.query(insertQuery, params, client);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
catch (error) {
|
|
1034
|
+
throw new Error(`Failed to save ${relationName} relation: ${error.message}`, {
|
|
1035
|
+
cause: error,
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Delete this model instance. Models with revision tracking require
|
|
1041
|
+
* `{ purge: true }`, which also removes the document's archived revisions;
|
|
1042
|
+
* use `deleteAllRevisions(user)` to soft-delete instead.
|
|
1043
|
+
* @param options - Delete options
|
|
1044
|
+
* @returns Success status
|
|
1045
|
+
*/
|
|
1046
|
+
async delete(options = {}) {
|
|
1047
|
+
if (this._isNew) {
|
|
1048
|
+
throw new Error('Cannot delete unsaved record');
|
|
1049
|
+
}
|
|
1050
|
+
const runtime = this.runtime;
|
|
1051
|
+
const query = new QueryBuilder(runtime, runtime.dal);
|
|
1052
|
+
const result = await query.deleteById(String(this.id), options);
|
|
1053
|
+
return result > 0;
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Ensure a revision handler is available for this model runtime
|
|
1057
|
+
* @param handlerName - Revision handler to initialize
|
|
1058
|
+
* @returns Revision handler function
|
|
1059
|
+
*/
|
|
1060
|
+
static _ensureRevisionHandler(handlerName) {
|
|
1061
|
+
if (!this._revisionHandlers) {
|
|
1062
|
+
this._revisionHandlers = {};
|
|
1063
|
+
}
|
|
1064
|
+
const existing = this._revisionHandlers[handlerName];
|
|
1065
|
+
if (existing) {
|
|
1066
|
+
return existing;
|
|
1067
|
+
}
|
|
1068
|
+
const hasRevisionFields = this.schema && Object.prototype.hasOwnProperty.call(this.schema, '_revID');
|
|
1069
|
+
if (!hasRevisionFields) {
|
|
1070
|
+
const modelName = this.tableName || this.name || 'Model';
|
|
1071
|
+
throw new Error(`Revision support is not enabled for ${modelName}`);
|
|
1072
|
+
}
|
|
1073
|
+
switch (handlerName) {
|
|
1074
|
+
case 'newRevision':
|
|
1075
|
+
return (this._revisionHandlers.newRevision = revision.getNewRevisionHandler(this));
|
|
1076
|
+
case 'deleteAllRevisions':
|
|
1077
|
+
return (this._revisionHandlers.deleteAllRevisions = revision.getDeleteAllRevisionsHandler(this));
|
|
1078
|
+
default:
|
|
1079
|
+
throw new Error(`Unknown revision handler requested: ${handlerName}`);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
async newRevision(user = null, options = {}) {
|
|
1083
|
+
const handler = this.runtime._ensureRevisionHandler('newRevision');
|
|
1084
|
+
return handler.call(this, user, options);
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Delete all revisions of this model instance
|
|
1088
|
+
* This method will be dynamically assigned by revision handlers
|
|
1089
|
+
* @param user - User performing the deletion
|
|
1090
|
+
* @param options - Deletion options
|
|
1091
|
+
* @returns Deletion revision
|
|
1092
|
+
*/
|
|
1093
|
+
async deleteAllRevisions(user = null, options = {}) {
|
|
1094
|
+
const handler = this.runtime._ensureRevisionHandler('deleteAllRevisions');
|
|
1095
|
+
return handler.call(this, user, options);
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Generate virtual field values
|
|
1099
|
+
*/
|
|
1100
|
+
generateVirtualValues() {
|
|
1101
|
+
const schema = this.runtime.schema;
|
|
1102
|
+
for (const [fieldName, fieldDef] of Object.entries(schema)) {
|
|
1103
|
+
if (fieldDef && fieldDef.isVirtual) {
|
|
1104
|
+
// For virtual fields, we need to access the raw defaultValue function
|
|
1105
|
+
if (fieldDef.hasDefault) {
|
|
1106
|
+
const defaultValue = this._resolveDefault(fieldDef);
|
|
1107
|
+
if (defaultValue !== undefined) {
|
|
1108
|
+
this._setVirtualField(fieldName, defaultValue);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Set up dynamic property accessors for schema fields
|
|
1116
|
+
* @private
|
|
1117
|
+
*/
|
|
1118
|
+
_setupPropertyAccessors() {
|
|
1119
|
+
const schema = this.runtime.schema;
|
|
1120
|
+
for (const fieldName of Object.keys(schema)) {
|
|
1121
|
+
// Skip if property already exists
|
|
1122
|
+
if (this.hasOwnProperty(fieldName)) {
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
// Create getter/setter for each schema field
|
|
1126
|
+
Object.defineProperty(this, fieldName, {
|
|
1127
|
+
get() {
|
|
1128
|
+
return this.getValue(fieldName);
|
|
1129
|
+
},
|
|
1130
|
+
set(value) {
|
|
1131
|
+
this.setValue(fieldName, value);
|
|
1132
|
+
},
|
|
1133
|
+
enumerable: true,
|
|
1134
|
+
configurable: true,
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Store deep copies of JSONB fields to detect in-place modifications
|
|
1140
|
+
* This allows detection of changes to nested properties without calling setters
|
|
1141
|
+
* @private
|
|
1142
|
+
*/
|
|
1143
|
+
_trackOriginalValues() {
|
|
1144
|
+
const schema = this.runtime.schema || {};
|
|
1145
|
+
for (const [fieldName, fieldDef] of Object.entries(schema)) {
|
|
1146
|
+
if (fieldDef && !fieldDef.isVirtual) {
|
|
1147
|
+
const dbFieldName = this.runtime._getDbFieldName(fieldName);
|
|
1148
|
+
const value = this._data[dbFieldName];
|
|
1149
|
+
// Deep clone objects and arrays to track original state
|
|
1150
|
+
if (value !== null && value !== undefined && typeof value === 'object') {
|
|
1151
|
+
this._originalData[dbFieldName] = cloneRowValue(value);
|
|
1152
|
+
}
|
|
1153
|
+
else {
|
|
1154
|
+
// Clear tracking for non-object values (primitives don't need tracking)
|
|
1155
|
+
delete this._originalData[dbFieldName];
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* Detect in-place modifications to JSONB fields
|
|
1162
|
+
* For objects/arrays loaded from database, detect if they were mutated without calling setters
|
|
1163
|
+
* @private
|
|
1164
|
+
*/
|
|
1165
|
+
_detectInPlaceChanges() {
|
|
1166
|
+
// Only check persisted records (new records have no "original" state to compare)
|
|
1167
|
+
if (this._isNew)
|
|
1168
|
+
return;
|
|
1169
|
+
const schema = this.runtime.schema;
|
|
1170
|
+
for (const [fieldName, fieldDef] of Object.entries(schema)) {
|
|
1171
|
+
if (fieldDef && !fieldDef.isVirtual && !fieldName.startsWith('_')) {
|
|
1172
|
+
const dbFieldName = this.runtime._getDbFieldName(fieldName);
|
|
1173
|
+
const originalValue = this._originalData[dbFieldName];
|
|
1174
|
+
// Only check fields we're tracking (objects/arrays from DB load)
|
|
1175
|
+
if (originalValue !== undefined) {
|
|
1176
|
+
const currentValue = this.getValue(fieldName);
|
|
1177
|
+
// Compare current state to original snapshot
|
|
1178
|
+
if (!deepEqual(currentValue, originalValue)) {
|
|
1179
|
+
// Mark as changed by calling setValue with current value
|
|
1180
|
+
this.setValue(fieldName, currentValue);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Validate model data against schema
|
|
1188
|
+
* Validates types, runs custom validators, and may transform values
|
|
1189
|
+
* @private
|
|
1190
|
+
*/
|
|
1191
|
+
_validate() {
|
|
1192
|
+
const schema = this.runtime.schema;
|
|
1193
|
+
for (const [fieldName, fieldDef] of Object.entries(schema)) {
|
|
1194
|
+
if (fieldDef && !fieldDef.isVirtual) {
|
|
1195
|
+
// Use getValue/setValue for all fields to respect field mappings
|
|
1196
|
+
const value = this.getValue(fieldName);
|
|
1197
|
+
const validatedValue = fieldDef.validate(value, fieldName);
|
|
1198
|
+
// If validation transformed the value, update it and mark as changed
|
|
1199
|
+
if (!deepEqual(validatedValue, value)) {
|
|
1200
|
+
this.setValue(fieldName, validatedValue);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Validate that a database field name is safe to use in SQL queries
|
|
1207
|
+
* @param dbFieldName - Database field name to validate
|
|
1208
|
+
* @returns true if valid, false otherwise
|
|
1209
|
+
* @private
|
|
1210
|
+
*/
|
|
1211
|
+
_isValidDbFieldName(dbFieldName) {
|
|
1212
|
+
const schema = this.runtime.schema || {};
|
|
1213
|
+
// Check if it's a schema field (by schema name)
|
|
1214
|
+
if (schema[dbFieldName]) {
|
|
1215
|
+
return true;
|
|
1216
|
+
}
|
|
1217
|
+
// Check if it's a mapped database field name
|
|
1218
|
+
const mappedDbFields = new Set(this.runtime._fieldMappings.values());
|
|
1219
|
+
if (mappedDbFields.has(dbFieldName)) {
|
|
1220
|
+
return true;
|
|
1221
|
+
}
|
|
1222
|
+
// Allow standard metadata fields (for revision system, etc.)
|
|
1223
|
+
const metadataFields = new Set([
|
|
1224
|
+
'id',
|
|
1225
|
+
'_old_rev_of',
|
|
1226
|
+
'_rev_deleted',
|
|
1227
|
+
'_rev_id',
|
|
1228
|
+
'_rev_of',
|
|
1229
|
+
'_rev_date',
|
|
1230
|
+
'_rev_tags',
|
|
1231
|
+
]);
|
|
1232
|
+
if (metadataFields.has(dbFieldName)) {
|
|
1233
|
+
return true;
|
|
1234
|
+
}
|
|
1235
|
+
return false;
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Insert new record
|
|
1239
|
+
* @param options - Insert options
|
|
1240
|
+
* @private
|
|
1241
|
+
*/
|
|
1242
|
+
async _insert(options = {}) {
|
|
1243
|
+
const tableName = this.runtime.tableName;
|
|
1244
|
+
const fields = Object.keys(this._data).filter(key => this._data[key] !== undefined);
|
|
1245
|
+
// Validate all field names to prevent SQL injection via column names
|
|
1246
|
+
for (const field of fields) {
|
|
1247
|
+
if (!this._isValidDbFieldName(field)) {
|
|
1248
|
+
throw new Error(`Invalid field name '${field}' in ${tableName} model. ` +
|
|
1249
|
+
'Field is not defined in schema or field mappings.');
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
const values = fields.map(key => this._data[key]);
|
|
1253
|
+
const placeholders = fields.map((_, index) => `$${index + 1}`);
|
|
1254
|
+
const query = `
|
|
1255
|
+
INSERT INTO ${tableName} (${fields.join(', ')})
|
|
1256
|
+
VALUES (${placeholders.join(', ')})
|
|
1257
|
+
RETURNING *
|
|
1258
|
+
`;
|
|
1259
|
+
const result = await this.runtime.dal.query(query, values, options.transaction ?? null);
|
|
1260
|
+
Object.assign(this._data, result.rows[0]);
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
* Update existing record
|
|
1264
|
+
* @param options - Update options
|
|
1265
|
+
* @param options.updateSensitive - Array of sensitive field names to include in update
|
|
1266
|
+
* @param expectedRevId - When set, only update if the stored `_rev_id` still
|
|
1267
|
+
* matches; otherwise throw {@link RevisionConflictError}
|
|
1268
|
+
* @private
|
|
1269
|
+
*/
|
|
1270
|
+
async _update(options = {}, expectedRevId = null) {
|
|
1271
|
+
if (this._changed.size === 0) {
|
|
1272
|
+
return; // No changes to save
|
|
1273
|
+
}
|
|
1274
|
+
const tableName = this.runtime.tableName;
|
|
1275
|
+
const allowedSensitive = new Set(options.updateSensitive || []);
|
|
1276
|
+
const sensitiveFields = new Set(this.runtime.getSensitiveFieldNames());
|
|
1277
|
+
// Build reverse map: db field name -> schema field name
|
|
1278
|
+
const dbToSchemaMap = new Map();
|
|
1279
|
+
for (const [schemaName, dbName] of this.runtime._fieldMappings) {
|
|
1280
|
+
dbToSchemaMap.set(dbName, schemaName);
|
|
1281
|
+
}
|
|
1282
|
+
const changedFields = Array.from(this._changed).filter(dbFieldName => {
|
|
1283
|
+
const schemaFieldName = dbToSchemaMap.get(dbFieldName) || dbFieldName;
|
|
1284
|
+
if (sensitiveFields.has(schemaFieldName)) {
|
|
1285
|
+
return allowedSensitive.has(schemaFieldName);
|
|
1286
|
+
}
|
|
1287
|
+
return true;
|
|
1288
|
+
});
|
|
1289
|
+
if (changedFields.length === 0) {
|
|
1290
|
+
return; // No non-sensitive changes to save
|
|
1291
|
+
}
|
|
1292
|
+
// Validate all field names to prevent SQL injection via column names
|
|
1293
|
+
for (const field of changedFields) {
|
|
1294
|
+
if (!this._isValidDbFieldName(field)) {
|
|
1295
|
+
throw new Error(`Invalid field name '${field}' in ${tableName} model. ` +
|
|
1296
|
+
'Field is not defined in schema or field mappings.');
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
const values = changedFields.map(key => this._data[key]);
|
|
1300
|
+
const setClause = changedFields.map((key, index) => `${key} = $${index + 1}`);
|
|
1301
|
+
const client = options.transaction ?? null;
|
|
1302
|
+
const params = [...values, this.id];
|
|
1303
|
+
let whereClause = `id = $${params.length}`;
|
|
1304
|
+
if (expectedRevId) {
|
|
1305
|
+
params.push(expectedRevId);
|
|
1306
|
+
whereClause += ` AND _rev_id = $${params.length}`;
|
|
1307
|
+
}
|
|
1308
|
+
const query = `
|
|
1309
|
+
UPDATE ${tableName}
|
|
1310
|
+
SET ${setClause.join(', ')}
|
|
1311
|
+
WHERE ${whereClause}
|
|
1312
|
+
RETURNING *
|
|
1313
|
+
`;
|
|
1314
|
+
const result = await this.runtime.dal.query(query, params, client);
|
|
1315
|
+
if (result.rows.length === 0) {
|
|
1316
|
+
if (expectedRevId) {
|
|
1317
|
+
const current = await this.runtime.dal.query(`SELECT _rev_id FROM ${tableName} WHERE id = $1`, [this.id], client);
|
|
1318
|
+
if (current.rows.length > 0) {
|
|
1319
|
+
const currentRevId = current.rows[0]._rev_id ?? null;
|
|
1320
|
+
throw new RevisionConflictError(`${tableName} ${this.id} was changed by another revision ` +
|
|
1321
|
+
`(expected ${expectedRevId}, found ${currentRevId}).`, { documentId: this.id ?? null, expectedRevId, currentRevId });
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
throw new DocumentNotFound(`${tableName} with id ${this.id} not found`);
|
|
1325
|
+
}
|
|
1326
|
+
Object.assign(this._data, result.rows[0]);
|
|
1327
|
+
}
|
|
1328
|
+
// Property getters and setters
|
|
1329
|
+
get id() {
|
|
1330
|
+
const value = this._data.id;
|
|
1331
|
+
return typeof value === 'string' ? value : undefined;
|
|
1332
|
+
}
|
|
1333
|
+
set id(value) {
|
|
1334
|
+
this._data.id = value;
|
|
1335
|
+
this._changed.add('id');
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* Get property value (data or virtual)
|
|
1339
|
+
* @param key - Property name (camelCase or snake_case)
|
|
1340
|
+
* @returns Property value
|
|
1341
|
+
*/
|
|
1342
|
+
getValue(key) {
|
|
1343
|
+
if (this._virtualFields.hasOwnProperty(key)) {
|
|
1344
|
+
return this._virtualFields[key];
|
|
1345
|
+
}
|
|
1346
|
+
// Get the actual database field name
|
|
1347
|
+
const dbFieldName = this.runtime._getDbFieldName(key);
|
|
1348
|
+
return this._data[dbFieldName];
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Set property value
|
|
1352
|
+
* @param key - Property name (camelCase or snake_case)
|
|
1353
|
+
* @param value - Property value
|
|
1354
|
+
*/
|
|
1355
|
+
setValue(key, value) {
|
|
1356
|
+
const schema = this.runtime.schema;
|
|
1357
|
+
if (schema[key] && schema[key].isVirtual) {
|
|
1358
|
+
this._setVirtualField(key, value);
|
|
1359
|
+
}
|
|
1360
|
+
else {
|
|
1361
|
+
// Get the actual database field name
|
|
1362
|
+
const dbFieldName = this.runtime._getDbFieldName(key);
|
|
1363
|
+
this._data[dbFieldName] = value;
|
|
1364
|
+
this._changed.add(dbFieldName);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Apply default values defined in the schema for missing fields
|
|
1369
|
+
* @param initialData - The initial payload passed to the constructor
|
|
1370
|
+
* @private
|
|
1371
|
+
*/
|
|
1372
|
+
_applyDefaults(initialData = {}) {
|
|
1373
|
+
const schema = this.runtime.schema || {};
|
|
1374
|
+
for (const [fieldName, fieldDef] of Object.entries(schema)) {
|
|
1375
|
+
if (!fieldDef || fieldDef.isVirtual || !fieldDef.hasDefault) {
|
|
1376
|
+
continue;
|
|
1377
|
+
}
|
|
1378
|
+
const dbFieldName = this.runtime._getDbFieldName(fieldName);
|
|
1379
|
+
const hasInitialValue = Object.prototype.hasOwnProperty.call(initialData, fieldName) ||
|
|
1380
|
+
(dbFieldName !== fieldName &&
|
|
1381
|
+
Object.prototype.hasOwnProperty.call(initialData, dbFieldName));
|
|
1382
|
+
if (hasInitialValue) {
|
|
1383
|
+
continue;
|
|
1384
|
+
}
|
|
1385
|
+
const defaultValue = this._resolveDefault(fieldDef);
|
|
1386
|
+
if (defaultValue !== undefined) {
|
|
1387
|
+
this.setValue(fieldName, defaultValue);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Resolve a type default value, honoring functions that rely on instance context
|
|
1393
|
+
* @param fieldDef - Schema field definition
|
|
1394
|
+
* @returns Default value or undefined if none
|
|
1395
|
+
* @private
|
|
1396
|
+
*/
|
|
1397
|
+
_resolveDefault(fieldDef) {
|
|
1398
|
+
if (!fieldDef || !fieldDef.hasDefault) {
|
|
1399
|
+
return undefined;
|
|
1400
|
+
}
|
|
1401
|
+
if (typeof fieldDef.getDefault === 'function') {
|
|
1402
|
+
try {
|
|
1403
|
+
const value = fieldDef.getDefault();
|
|
1404
|
+
if (value !== undefined) {
|
|
1405
|
+
return value;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
catch (error) {
|
|
1409
|
+
if (typeof fieldDef.defaultValue !== 'function') {
|
|
1410
|
+
throw error;
|
|
1411
|
+
}
|
|
1412
|
+
return fieldDef.defaultValue.call(this);
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
if (typeof fieldDef.defaultValue === 'function') {
|
|
1416
|
+
return fieldDef.defaultValue.call(this);
|
|
1417
|
+
}
|
|
1418
|
+
return fieldDef.defaultValue;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
export { Model };
|
|
1422
|
+
export default Model;
|
|
1423
|
+
//# sourceMappingURL=model.js.map
|