@remix-run/data-table 0.1.0 → 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/README.md +307 -56
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/lib/adapter.d.ts +386 -16
- package/dist/lib/adapter.d.ts.map +1 -1
- package/dist/lib/column.d.ts +193 -0
- package/dist/lib/column.d.ts.map +1 -0
- package/dist/lib/column.js +302 -0
- package/dist/lib/database/execution-context.d.ts +10 -0
- package/dist/lib/database/execution-context.d.ts.map +1 -0
- package/dist/lib/database/execution-context.js +1 -0
- package/dist/lib/database/helpers.d.ts +26 -0
- package/dist/lib/database/helpers.d.ts.map +1 -0
- package/dist/lib/database/helpers.js +116 -0
- package/dist/lib/database/query-execution.d.ts +7 -0
- package/dist/lib/database/query-execution.d.ts.map +1 -0
- package/dist/lib/database/query-execution.js +401 -0
- package/dist/lib/database/relations.d.ts +4 -0
- package/dist/lib/database/relations.d.ts.map +1 -0
- package/dist/lib/database/relations.js +207 -0
- package/dist/lib/database/write-lifecycle.d.ts +13 -0
- package/dist/lib/database/write-lifecycle.d.ts.map +1 -0
- package/dist/lib/database/write-lifecycle.js +279 -0
- package/dist/lib/database.d.ts +141 -238
- package/dist/lib/database.d.ts.map +1 -1
- package/dist/lib/database.js +73 -1122
- package/dist/lib/errors.d.ts +9 -0
- package/dist/lib/errors.d.ts.map +1 -1
- package/dist/lib/errors.js +9 -0
- package/dist/lib/migrations/filename.d.ts +12 -0
- package/dist/lib/migrations/filename.d.ts.map +1 -0
- package/dist/lib/migrations/filename.js +20 -0
- package/dist/lib/migrations/helpers.d.ts +11 -0
- package/dist/lib/migrations/helpers.d.ts.map +1 -0
- package/dist/lib/migrations/helpers.js +77 -0
- package/dist/lib/migrations/journal-store.d.ts +15 -0
- package/dist/lib/migrations/journal-store.d.ts.map +1 -0
- package/dist/lib/migrations/journal-store.js +83 -0
- package/dist/lib/migrations/registry.d.ts +27 -0
- package/dist/lib/migrations/registry.d.ts.map +1 -0
- package/dist/lib/migrations/registry.js +51 -0
- package/dist/lib/migrations/runner.d.ts +20 -0
- package/dist/lib/migrations/runner.d.ts.map +1 -0
- package/dist/lib/migrations/runner.js +273 -0
- package/dist/lib/migrations/schema-api.d.ts +7 -0
- package/dist/lib/migrations/schema-api.d.ts.map +1 -0
- package/dist/lib/migrations/schema-api.js +326 -0
- package/dist/lib/migrations-node.d.ts +17 -0
- package/dist/lib/migrations-node.d.ts.map +1 -0
- package/dist/lib/migrations-node.js +65 -0
- package/dist/lib/migrations.d.ts +292 -0
- package/dist/lib/migrations.d.ts.map +1 -0
- package/dist/lib/migrations.js +38 -0
- package/dist/lib/operators.d.ts +3 -0
- package/dist/lib/operators.d.ts.map +1 -1
- package/dist/lib/query.d.ts +159 -0
- package/dist/lib/query.d.ts.map +1 -0
- package/dist/lib/query.js +401 -0
- package/dist/lib/references.d.ts +0 -1
- package/dist/lib/references.d.ts.map +1 -1
- package/dist/lib/sql-helpers.d.ts +50 -0
- package/dist/lib/sql-helpers.d.ts.map +1 -0
- package/dist/lib/sql-helpers.js +111 -0
- package/dist/lib/sql.d.ts +23 -6
- package/dist/lib/sql.d.ts.map +1 -1
- package/dist/lib/sql.js +19 -5
- package/dist/lib/table.d.ts +355 -40
- package/dist/lib/table.d.ts.map +1 -1
- package/dist/lib/table.js +113 -90
- package/dist/migrations/node.d.ts +2 -0
- package/dist/migrations/node.d.ts.map +1 -0
- package/dist/migrations/node.js +1 -0
- package/dist/migrations.d.ts +8 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +5 -0
- package/dist/operators.d.ts +3 -0
- package/dist/operators.d.ts.map +1 -0
- package/dist/operators.js +1 -0
- package/dist/sql-helpers.d.ts +3 -0
- package/dist/sql-helpers.d.ts.map +1 -0
- package/dist/sql-helpers.js +1 -0
- package/package.json +24 -10
- package/src/index.ts +93 -10
- package/src/lib/adapter.ts +469 -25
- package/src/lib/column.ts +384 -0
- package/src/lib/database/execution-context.ts +15 -0
- package/src/lib/database/helpers.ts +216 -0
- package/src/lib/database/query-execution.ts +638 -0
- package/src/lib/database/relations.ts +332 -0
- package/src/lib/database/write-lifecycle.ts +487 -0
- package/src/lib/database.ts +246 -1848
- package/src/lib/errors.ts +10 -0
- package/src/lib/migrations/filename.ts +25 -0
- package/src/lib/migrations/helpers.ts +108 -0
- package/src/lib/migrations/journal-store.ts +122 -0
- package/src/lib/migrations/registry.ts +62 -0
- package/src/lib/migrations/runner.ts +374 -0
- package/src/lib/migrations/schema-api.ts +417 -0
- package/src/lib/migrations-node.ts +71 -0
- package/src/lib/migrations.ts +328 -0
- package/src/lib/operators.ts +3 -0
- package/src/lib/query.ts +958 -0
- package/src/lib/references.ts +0 -1
- package/src/lib/sql-helpers.ts +146 -0
- package/src/lib/sql.ts +23 -6
- package/src/lib/table.ts +484 -156
- package/src/migrations/node.ts +1 -0
- package/src/migrations.ts +26 -0
- package/src/operators.ts +18 -0
- package/src/sql-helpers.ts +9 -0
package/dist/lib/database.js
CHANGED
|
@@ -1,20 +1,32 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { DataTableAdapterError, DataTableQueryError } from "./errors.js";
|
|
2
|
+
import { executeOperation } from "./database/execution-context.js";
|
|
3
|
+
import { asQueryTableInput, getPrimaryKeyWhere, getPrimaryKeyWhereFromRow, normalizeOrderByInput, resolveCreateRowWhere, toWriteResult, } from "./database/helpers.js";
|
|
4
|
+
import { executeQuery } from "./database/query-execution.js";
|
|
5
|
+
import { bindQueryRuntime, query as createQuery } from "./query.js";
|
|
6
|
+
import { isSqlStatement, rawSql } from "./sql.js";
|
|
7
|
+
import { getTableName } from "./table.js";
|
|
8
|
+
const createInternalDatabase = Symbol('createInternalDatabase');
|
|
9
|
+
/**
|
|
10
|
+
* High-level database runtime used to build and execute data manipulation operations.
|
|
11
|
+
*
|
|
12
|
+
* Create instances directly with `new Database(adapter, options)` or use
|
|
13
|
+
* `createDatabase(adapter, options)` as a thin wrapper.
|
|
14
|
+
*/
|
|
15
|
+
export class Database {
|
|
9
16
|
#adapter;
|
|
10
17
|
#token;
|
|
11
18
|
#now;
|
|
12
19
|
#savepointCounter;
|
|
13
|
-
constructor(options) {
|
|
14
|
-
this.#adapter =
|
|
15
|
-
this.#
|
|
16
|
-
this.#
|
|
17
|
-
|
|
20
|
+
constructor(adapter, options) {
|
|
21
|
+
this.#adapter = adapter;
|
|
22
|
+
this.#now = options?.now ?? defaultNow;
|
|
23
|
+
this.#savepointCounter = { value: 0 };
|
|
24
|
+
}
|
|
25
|
+
static [createInternalDatabase](adapter, options, internal) {
|
|
26
|
+
let database = new Database(adapter, options);
|
|
27
|
+
database.#token = internal.token;
|
|
28
|
+
database.#savepointCounter = internal.savepointCounter;
|
|
29
|
+
return database;
|
|
18
30
|
}
|
|
19
31
|
get adapter() {
|
|
20
32
|
return this.#adapter;
|
|
@@ -22,7 +34,9 @@ class DatabaseRuntime {
|
|
|
22
34
|
now() {
|
|
23
35
|
return this.#now();
|
|
24
36
|
}
|
|
25
|
-
query
|
|
37
|
+
query(table) {
|
|
38
|
+
return createQuery(table)[bindQueryRuntime](this);
|
|
39
|
+
}
|
|
26
40
|
async create(table, values, options) {
|
|
27
41
|
let touch = options?.touch;
|
|
28
42
|
let query = this.query(asQueryTableInput(table));
|
|
@@ -86,9 +100,7 @@ class DatabaseRuntime {
|
|
|
86
100
|
}
|
|
87
101
|
let query = this.query(asQueryTableInput(table));
|
|
88
102
|
if (options?.with) {
|
|
89
|
-
return query
|
|
90
|
-
.with(options.with)
|
|
91
|
-
.find(value);
|
|
103
|
+
return query.with(options.with).find(value);
|
|
92
104
|
}
|
|
93
105
|
return query.find(value);
|
|
94
106
|
}
|
|
@@ -197,20 +209,23 @@ class DatabaseRuntime {
|
|
|
197
209
|
let result = await query.delete();
|
|
198
210
|
return toWriteResult(result);
|
|
199
211
|
}
|
|
200
|
-
async exec(
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
212
|
+
async exec(statementOrInput, values = []) {
|
|
213
|
+
if (typeof statementOrInput === 'string' || isSqlStatement(statementOrInput)) {
|
|
214
|
+
let sqlStatement = isSqlStatement(statementOrInput)
|
|
215
|
+
? statementOrInput
|
|
216
|
+
: rawSql(statementOrInput, values);
|
|
217
|
+
return this[executeOperation]({
|
|
218
|
+
kind: 'raw',
|
|
219
|
+
sql: sqlStatement,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return executeQuery(this, statementOrInput);
|
|
206
223
|
}
|
|
207
224
|
async transaction(callback, options) {
|
|
208
225
|
if (!this.#token) {
|
|
209
226
|
let token = await this.#adapter.beginTransaction(options);
|
|
210
|
-
let tx =
|
|
211
|
-
adapter: this.#adapter,
|
|
227
|
+
let tx = Database[createInternalDatabase](this.#adapter, { now: this.#now }, {
|
|
212
228
|
token,
|
|
213
|
-
now: this.#now,
|
|
214
229
|
savepointCounter: this.#savepointCounter,
|
|
215
230
|
});
|
|
216
231
|
try {
|
|
@@ -240,10 +255,10 @@ class DatabaseRuntime {
|
|
|
240
255
|
throw error;
|
|
241
256
|
}
|
|
242
257
|
}
|
|
243
|
-
async [
|
|
258
|
+
async [executeOperation](operation) {
|
|
244
259
|
try {
|
|
245
260
|
return await this.#adapter.execute({
|
|
246
|
-
|
|
261
|
+
operation,
|
|
247
262
|
transaction: this.#token,
|
|
248
263
|
});
|
|
249
264
|
}
|
|
@@ -252,7 +267,7 @@ class DatabaseRuntime {
|
|
|
252
267
|
cause: error,
|
|
253
268
|
metadata: {
|
|
254
269
|
dialect: this.#adapter.dialect,
|
|
255
|
-
|
|
270
|
+
operationKind: operation.kind,
|
|
256
271
|
},
|
|
257
272
|
});
|
|
258
273
|
}
|
|
@@ -260,1109 +275,45 @@ class DatabaseRuntime {
|
|
|
260
275
|
}
|
|
261
276
|
/**
|
|
262
277
|
* Creates a database runtime from an adapter.
|
|
278
|
+
* Thin wrapper around `new Database(adapter, options)`.
|
|
263
279
|
* @param adapter Adapter implementation responsible for SQL execution.
|
|
264
280
|
* @param options Optional runtime options.
|
|
265
281
|
* @param options.now Clock function used for auto-managed timestamps.
|
|
266
|
-
* @returns A
|
|
282
|
+
* @returns A {@link Database} API instance.
|
|
283
|
+
* @example
|
|
284
|
+
* ```ts
|
|
285
|
+
* import { column as c, createDatabase, table } from 'remix/data-table'
|
|
286
|
+
*
|
|
287
|
+
* let users = table({
|
|
288
|
+
* name: 'users',
|
|
289
|
+
* columns: {
|
|
290
|
+
* id: c.integer(),
|
|
291
|
+
* email: c.varchar(255),
|
|
292
|
+
* },
|
|
293
|
+
* })
|
|
294
|
+
*
|
|
295
|
+
* let db = createDatabase(adapter)
|
|
296
|
+
* let rows = await db.query(users).where({ id: 1 }).all()
|
|
297
|
+
* ```
|
|
267
298
|
*/
|
|
268
299
|
export function createDatabase(adapter, options) {
|
|
269
|
-
|
|
270
|
-
return new DatabaseRuntime({
|
|
271
|
-
adapter,
|
|
272
|
-
token: undefined,
|
|
273
|
-
now,
|
|
274
|
-
savepointCounter: { value: 0 },
|
|
275
|
-
});
|
|
300
|
+
return new Database(adapter, options);
|
|
276
301
|
}
|
|
277
302
|
/**
|
|
278
|
-
*
|
|
303
|
+
* Creates a database runtime bound to an existing adapter transaction token.
|
|
304
|
+
* This is an internal helper used by the migration runner.
|
|
305
|
+
* @param adapter Adapter implementation responsible for SQL execution.
|
|
306
|
+
* @param token Active adapter transaction token.
|
|
307
|
+
* @param options Optional runtime options.
|
|
308
|
+
* @param options.now Clock function used for auto-managed timestamps.
|
|
309
|
+
* @returns A {@link Database} API instance bound to the provided transaction.
|
|
279
310
|
*/
|
|
280
|
-
export
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
constructor(database, table, state) {
|
|
285
|
-
this.#database = database;
|
|
286
|
-
this.#table = table;
|
|
287
|
-
this.#state = state;
|
|
288
|
-
}
|
|
289
|
-
select(...input) {
|
|
290
|
-
if (input.length === 1 &&
|
|
291
|
-
typeof input[0] === 'object' &&
|
|
292
|
-
input[0] !== null &&
|
|
293
|
-
!Array.isArray(input[0])) {
|
|
294
|
-
let selection = input[0];
|
|
295
|
-
let aliases = Object.keys(selection);
|
|
296
|
-
let select = aliases.map((alias) => ({
|
|
297
|
-
column: normalizeColumnInput(selection[alias]),
|
|
298
|
-
alias,
|
|
299
|
-
}));
|
|
300
|
-
return this.#clone({ select });
|
|
301
|
-
}
|
|
302
|
-
let columns = input;
|
|
303
|
-
return this.#clone({
|
|
304
|
-
select: columns.map((column) => ({ column, alias: column })),
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Toggles `distinct` selection.
|
|
309
|
-
* @param value When `true`, eliminates duplicate rows.
|
|
310
|
-
* @returns A cloned query builder with updated distinct state.
|
|
311
|
-
*/
|
|
312
|
-
distinct(value = true) {
|
|
313
|
-
return this.#clone({ distinct: value });
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* Adds a where predicate.
|
|
317
|
-
* @param input Predicate expression or column-value shorthand.
|
|
318
|
-
* @returns A cloned query builder with the appended where predicate.
|
|
319
|
-
*/
|
|
320
|
-
where(input) {
|
|
321
|
-
let predicate = normalizeWhereInput(input);
|
|
322
|
-
let normalizedPredicate = normalizePredicateValues(predicate, createPredicateColumnResolver([this.#table, ...this.#state.joins.map((join) => join.table)]));
|
|
323
|
-
return this.#clone({
|
|
324
|
-
where: [...this.#state.where, normalizedPredicate],
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Adds a having predicate.
|
|
329
|
-
* @param input Predicate expression or aggregate filter shorthand.
|
|
330
|
-
* @returns A cloned query builder with the appended having predicate.
|
|
331
|
-
*/
|
|
332
|
-
having(input) {
|
|
333
|
-
let predicate = normalizeWhereInput(input);
|
|
334
|
-
let normalizedPredicate = normalizePredicateValues(predicate, createPredicateColumnResolver([this.#table, ...this.#state.joins.map((join) => join.table)]));
|
|
335
|
-
return this.#clone({
|
|
336
|
-
having: [...this.#state.having, normalizedPredicate],
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Adds a join clause.
|
|
341
|
-
* @param target Target table to join.
|
|
342
|
-
* @param on Join predicate.
|
|
343
|
-
* @param type Join type.
|
|
344
|
-
* @returns A query builder whose column map includes joined table columns.
|
|
345
|
-
*/
|
|
346
|
-
join(target, on, type = 'inner') {
|
|
347
|
-
let normalizedOn = normalizePredicateValues(on, createPredicateColumnResolver([
|
|
348
|
-
this.#table,
|
|
349
|
-
...this.#state.joins.map((join) => join.table),
|
|
350
|
-
target,
|
|
351
|
-
]));
|
|
352
|
-
return new QueryBuilder(this.#database, this.#table, {
|
|
353
|
-
select: cloneSelection(this.#state.select),
|
|
354
|
-
distinct: this.#state.distinct,
|
|
355
|
-
joins: [...this.#state.joins, { type, table: target, on: normalizedOn }],
|
|
356
|
-
where: [...this.#state.where],
|
|
357
|
-
groupBy: [...this.#state.groupBy],
|
|
358
|
-
having: [...this.#state.having],
|
|
359
|
-
orderBy: [...this.#state.orderBy],
|
|
360
|
-
limit: this.#state.limit,
|
|
361
|
-
offset: this.#state.offset,
|
|
362
|
-
with: { ...this.#state.with },
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
/**
|
|
366
|
-
* Adds a left join clause.
|
|
367
|
-
* @param target Target table to join.
|
|
368
|
-
* @param on Join predicate.
|
|
369
|
-
* @returns A query builder whose column map includes joined table columns.
|
|
370
|
-
*/
|
|
371
|
-
leftJoin(target, on) {
|
|
372
|
-
return this.join(target, on, 'left');
|
|
373
|
-
}
|
|
374
|
-
/**
|
|
375
|
-
* Adds a right join clause.
|
|
376
|
-
* @param target Target table to join.
|
|
377
|
-
* @param on Join predicate.
|
|
378
|
-
* @returns A query builder whose column map includes joined table columns.
|
|
379
|
-
*/
|
|
380
|
-
rightJoin(target, on) {
|
|
381
|
-
return this.join(target, on, 'right');
|
|
382
|
-
}
|
|
383
|
-
/**
|
|
384
|
-
* Appends an order-by clause.
|
|
385
|
-
* @param column Column to sort by.
|
|
386
|
-
* @param direction Sort direction.
|
|
387
|
-
* @returns A cloned query builder with the appended order-by clause.
|
|
388
|
-
*/
|
|
389
|
-
orderBy(column, direction = 'asc') {
|
|
390
|
-
return this.#clone({
|
|
391
|
-
orderBy: [...this.#state.orderBy, { column: normalizeColumnInput(column), direction }],
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
/**
|
|
395
|
-
* Appends group-by columns.
|
|
396
|
-
* @param columns Columns to include in the grouping set.
|
|
397
|
-
* @returns A cloned query builder with appended group-by columns.
|
|
398
|
-
*/
|
|
399
|
-
groupBy(...columns) {
|
|
400
|
-
return this.#clone({
|
|
401
|
-
groupBy: [...this.#state.groupBy, ...columns.map((column) => normalizeColumnInput(column))],
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Limits returned rows.
|
|
406
|
-
* @param value Maximum number of rows to return.
|
|
407
|
-
* @returns A cloned query builder with a row limit.
|
|
408
|
-
*/
|
|
409
|
-
limit(value) {
|
|
410
|
-
return this.#clone({ limit: value });
|
|
411
|
-
}
|
|
412
|
-
/**
|
|
413
|
-
* Skips returned rows.
|
|
414
|
-
* @param value Number of rows to skip.
|
|
415
|
-
* @returns A cloned query builder with a row offset.
|
|
416
|
-
*/
|
|
417
|
-
offset(value) {
|
|
418
|
-
return this.#clone({ offset: value });
|
|
419
|
-
}
|
|
420
|
-
/**
|
|
421
|
-
* Configures eager-loaded relations.
|
|
422
|
-
* @param relations Relation map describing nested eager-load behavior.
|
|
423
|
-
* @returns A cloned query builder with relation loading configuration.
|
|
424
|
-
*/
|
|
425
|
-
with(relations) {
|
|
426
|
-
return this.#clone({
|
|
427
|
-
with: {
|
|
428
|
-
...this.#state.with,
|
|
429
|
-
...relations,
|
|
430
|
-
},
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
/**
|
|
434
|
-
* Executes the query and returns all rows.
|
|
435
|
-
* @returns All matching rows with requested eager-loaded relations.
|
|
436
|
-
*/
|
|
437
|
-
async all() {
|
|
438
|
-
let statement = this.#toSelectStatement();
|
|
439
|
-
let result = await this.#database[executeStatement](statement);
|
|
440
|
-
let rows = normalizeRows(result.rows);
|
|
441
|
-
if (Object.keys(this.#state.with).length === 0) {
|
|
442
|
-
return rows;
|
|
443
|
-
}
|
|
444
|
-
let rowsWithRelations = await loadRelationsForRows(this.#database, this.#table, rows, this.#state.with);
|
|
445
|
-
return rowsWithRelations;
|
|
446
|
-
}
|
|
447
|
-
/**
|
|
448
|
-
* Executes the query and returns the first row.
|
|
449
|
-
* @returns The first matching row, or `null` when no rows match.
|
|
450
|
-
*/
|
|
451
|
-
async first() {
|
|
452
|
-
let rows = await this.limit(1).all();
|
|
453
|
-
return rows[0] ?? null;
|
|
454
|
-
}
|
|
455
|
-
/**
|
|
456
|
-
* Loads a single row by primary key.
|
|
457
|
-
* @param value Primary-key value or composite-key object.
|
|
458
|
-
* @returns The matching row, or `null` when no row exists.
|
|
459
|
-
*/
|
|
460
|
-
async find(value) {
|
|
461
|
-
let where = getPrimaryKeyObject(this.#table, value);
|
|
462
|
-
return this.where(where).first();
|
|
463
|
-
}
|
|
464
|
-
/**
|
|
465
|
-
* Executes a count query.
|
|
466
|
-
* @returns Number of rows that match the current query scope.
|
|
467
|
-
*/
|
|
468
|
-
async count() {
|
|
469
|
-
let statement = {
|
|
470
|
-
kind: 'count',
|
|
471
|
-
table: this.#table,
|
|
472
|
-
joins: [...this.#state.joins],
|
|
473
|
-
where: [...this.#state.where],
|
|
474
|
-
groupBy: [...this.#state.groupBy],
|
|
475
|
-
having: [...this.#state.having],
|
|
476
|
-
};
|
|
477
|
-
let result = await this.#database[executeStatement](statement);
|
|
478
|
-
if (result.rows && result.rows[0] && typeof result.rows[0].count === 'number') {
|
|
479
|
-
return result.rows[0].count;
|
|
480
|
-
}
|
|
481
|
-
if (result.rows) {
|
|
482
|
-
return result.rows.length;
|
|
483
|
-
}
|
|
484
|
-
return 0;
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* Executes an existence query.
|
|
488
|
-
* @returns `true` when at least one row matches the current query scope.
|
|
489
|
-
*/
|
|
490
|
-
async exists() {
|
|
491
|
-
let statement = {
|
|
492
|
-
kind: 'exists',
|
|
493
|
-
table: this.#table,
|
|
494
|
-
joins: [...this.#state.joins],
|
|
495
|
-
where: [...this.#state.where],
|
|
496
|
-
groupBy: [...this.#state.groupBy],
|
|
497
|
-
having: [...this.#state.having],
|
|
498
|
-
};
|
|
499
|
-
let result = await this.#database[executeStatement](statement);
|
|
500
|
-
if (result.rows && result.rows[0] && typeof result.rows[0].exists === 'boolean') {
|
|
501
|
-
return result.rows[0].exists;
|
|
502
|
-
}
|
|
503
|
-
if (result.rows && result.rows[0] && typeof result.rows[0].count === 'number') {
|
|
504
|
-
return Number(result.rows[0].count) > 0;
|
|
505
|
-
}
|
|
506
|
-
return Boolean(result.rows && result.rows.length > 0);
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* Inserts one row.
|
|
510
|
-
* @param values Values to insert.
|
|
511
|
-
* @param options Insert options.
|
|
512
|
-
* @param options.returning Optional return selection for adapters that support returning.
|
|
513
|
-
* @param options.touch When `true`, manages timestamp columns automatically.
|
|
514
|
-
* @returns Insert metadata, and optionally the returned row.
|
|
515
|
-
*/
|
|
516
|
-
async insert(values, options) {
|
|
517
|
-
assertWriteState(this.#state, 'insert', {
|
|
518
|
-
where: false,
|
|
519
|
-
orderBy: false,
|
|
520
|
-
limit: false,
|
|
521
|
-
offset: false,
|
|
522
|
-
});
|
|
523
|
-
let preparedValues = prepareInsertValues(this.#table, values, this.#database.now(), options?.touch ?? true);
|
|
524
|
-
let returning = options?.returning;
|
|
525
|
-
assertReturningCapability(this.#database.adapter, 'insert', returning);
|
|
526
|
-
if (returning) {
|
|
527
|
-
let statement = {
|
|
528
|
-
kind: 'insert',
|
|
529
|
-
table: this.#table,
|
|
530
|
-
values: preparedValues,
|
|
531
|
-
returning: normalizeReturningSelection(returning),
|
|
532
|
-
};
|
|
533
|
-
let result = await this.#database[executeStatement](statement);
|
|
534
|
-
let row = (normalizeRows(result.rows)[0] ?? null);
|
|
535
|
-
return {
|
|
536
|
-
affectedRows: result.affectedRows ?? 0,
|
|
537
|
-
insertId: result.insertId,
|
|
538
|
-
row,
|
|
539
|
-
};
|
|
540
|
-
}
|
|
541
|
-
let statement = {
|
|
542
|
-
kind: 'insert',
|
|
543
|
-
table: this.#table,
|
|
544
|
-
values: preparedValues,
|
|
545
|
-
};
|
|
546
|
-
let result = await this.#database[executeStatement](statement);
|
|
547
|
-
let metadata = {
|
|
548
|
-
affectedRows: result.affectedRows ?? 0,
|
|
549
|
-
insertId: result.insertId,
|
|
550
|
-
};
|
|
551
|
-
return metadata;
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Inserts many rows.
|
|
555
|
-
* @param values Values to insert.
|
|
556
|
-
* @param options Insert options.
|
|
557
|
-
* @param options.returning Optional return selection for adapters that support returning.
|
|
558
|
-
* @param options.touch When `true`, manages timestamp columns automatically.
|
|
559
|
-
* @returns Insert metadata, and optionally the returned rows.
|
|
560
|
-
*/
|
|
561
|
-
async insertMany(values, options) {
|
|
562
|
-
assertWriteState(this.#state, 'insertMany', {
|
|
563
|
-
where: false,
|
|
564
|
-
orderBy: false,
|
|
565
|
-
limit: false,
|
|
566
|
-
offset: false,
|
|
567
|
-
});
|
|
568
|
-
let preparedValues = values.map((value) => prepareInsertValues(this.#table, value, this.#database.now(), options?.touch ?? true));
|
|
569
|
-
if (preparedValues.length > 0 &&
|
|
570
|
-
preparedValues.every((preparedValue) => Object.keys(preparedValue).length === 0)) {
|
|
571
|
-
throw new DataTableQueryError('insertMany() requires at least one explicit value across the batch');
|
|
572
|
-
}
|
|
573
|
-
let returning = options?.returning;
|
|
574
|
-
assertReturningCapability(this.#database.adapter, 'insertMany', returning);
|
|
575
|
-
if (returning) {
|
|
576
|
-
let statement = {
|
|
577
|
-
kind: 'insertMany',
|
|
578
|
-
table: this.#table,
|
|
579
|
-
values: preparedValues,
|
|
580
|
-
returning: normalizeReturningSelection(returning),
|
|
581
|
-
};
|
|
582
|
-
let result = await this.#database[executeStatement](statement);
|
|
583
|
-
return {
|
|
584
|
-
affectedRows: result.affectedRows ?? 0,
|
|
585
|
-
insertId: result.insertId,
|
|
586
|
-
rows: normalizeRows(result.rows),
|
|
587
|
-
};
|
|
588
|
-
}
|
|
589
|
-
let statement = {
|
|
590
|
-
kind: 'insertMany',
|
|
591
|
-
table: this.#table,
|
|
592
|
-
values: preparedValues,
|
|
593
|
-
};
|
|
594
|
-
let result = await this.#database[executeStatement](statement);
|
|
595
|
-
let metadata = {
|
|
596
|
-
affectedRows: result.affectedRows ?? 0,
|
|
597
|
-
insertId: result.insertId,
|
|
598
|
-
};
|
|
599
|
-
return metadata;
|
|
600
|
-
}
|
|
601
|
-
/**
|
|
602
|
-
* Updates scoped rows.
|
|
603
|
-
* @param changes Column changes to apply.
|
|
604
|
-
* @param options Update options.
|
|
605
|
-
* @param options.returning Optional return selection for adapters that support returning.
|
|
606
|
-
* @param options.touch When `true`, updates timestamp columns automatically.
|
|
607
|
-
* @returns Update metadata, and optionally the returned rows.
|
|
608
|
-
*/
|
|
609
|
-
async update(changes, options) {
|
|
610
|
-
assertWriteState(this.#state, 'update', {
|
|
611
|
-
where: true,
|
|
612
|
-
orderBy: true,
|
|
613
|
-
limit: true,
|
|
614
|
-
offset: true,
|
|
615
|
-
});
|
|
616
|
-
let preparedChanges = prepareUpdateValues(this.#table, changes, this.#database.now(), options?.touch ?? true);
|
|
617
|
-
let returning = options?.returning;
|
|
618
|
-
assertReturningCapability(this.#database.adapter, 'update', returning);
|
|
619
|
-
if (Object.keys(preparedChanges).length === 0) {
|
|
620
|
-
throw new DataTableQueryError('update() requires at least one change');
|
|
621
|
-
}
|
|
622
|
-
if (hasScopedWriteModifiers(this.#state)) {
|
|
623
|
-
let table = this.#table;
|
|
624
|
-
let queryState = this.#state;
|
|
625
|
-
return this.#database.transaction(async (tx) => {
|
|
626
|
-
let primaryKeys = await loadPrimaryKeyRowsForScope(tx, table, queryState);
|
|
627
|
-
let primaryKeyPredicate = buildPrimaryKeyPredicate(table, primaryKeys);
|
|
628
|
-
if (!primaryKeyPredicate) {
|
|
629
|
-
if (!returning) {
|
|
630
|
-
return {
|
|
631
|
-
affectedRows: 0,
|
|
632
|
-
insertId: undefined,
|
|
633
|
-
};
|
|
634
|
-
}
|
|
635
|
-
return {
|
|
636
|
-
affectedRows: 0,
|
|
637
|
-
insertId: undefined,
|
|
638
|
-
rows: [],
|
|
639
|
-
};
|
|
640
|
-
}
|
|
641
|
-
return tx.query(table).where(primaryKeyPredicate).update(changes, options);
|
|
642
|
-
});
|
|
643
|
-
}
|
|
644
|
-
let statement = {
|
|
645
|
-
kind: 'update',
|
|
646
|
-
table: this.#table,
|
|
647
|
-
changes: preparedChanges,
|
|
648
|
-
where: [...this.#state.where],
|
|
649
|
-
returning: returning ? normalizeReturningSelection(returning) : undefined,
|
|
650
|
-
};
|
|
651
|
-
let result = await this.#database[executeStatement](statement);
|
|
652
|
-
if (!returning) {
|
|
653
|
-
return {
|
|
654
|
-
affectedRows: result.affectedRows ?? 0,
|
|
655
|
-
insertId: result.insertId,
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
return {
|
|
659
|
-
affectedRows: result.affectedRows ?? 0,
|
|
660
|
-
insertId: result.insertId,
|
|
661
|
-
rows: normalizeRows(result.rows),
|
|
662
|
-
};
|
|
663
|
-
}
|
|
664
|
-
/**
|
|
665
|
-
* Deletes scoped rows.
|
|
666
|
-
* @param options Delete options.
|
|
667
|
-
* @param options.returning Optional return selection for adapters that support returning.
|
|
668
|
-
* @returns Delete metadata, and optionally the returned rows.
|
|
669
|
-
*/
|
|
670
|
-
async delete(options) {
|
|
671
|
-
assertWriteState(this.#state, 'delete', {
|
|
672
|
-
where: true,
|
|
673
|
-
orderBy: true,
|
|
674
|
-
limit: true,
|
|
675
|
-
offset: true,
|
|
676
|
-
});
|
|
677
|
-
let returning = options?.returning;
|
|
678
|
-
assertReturningCapability(this.#database.adapter, 'delete', returning);
|
|
679
|
-
if (hasScopedWriteModifiers(this.#state)) {
|
|
680
|
-
let table = this.#table;
|
|
681
|
-
let queryState = this.#state;
|
|
682
|
-
return this.#database.transaction(async (tx) => {
|
|
683
|
-
let primaryKeys = await loadPrimaryKeyRowsForScope(tx, table, queryState);
|
|
684
|
-
let primaryKeyPredicate = buildPrimaryKeyPredicate(table, primaryKeys);
|
|
685
|
-
if (!primaryKeyPredicate) {
|
|
686
|
-
if (!returning) {
|
|
687
|
-
return {
|
|
688
|
-
affectedRows: 0,
|
|
689
|
-
insertId: undefined,
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
return {
|
|
693
|
-
affectedRows: 0,
|
|
694
|
-
insertId: undefined,
|
|
695
|
-
rows: [],
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
return tx.query(table).where(primaryKeyPredicate).delete(options);
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
let statement = {
|
|
702
|
-
kind: 'delete',
|
|
703
|
-
table: this.#table,
|
|
704
|
-
where: [...this.#state.where],
|
|
705
|
-
returning: returning ? normalizeReturningSelection(returning) : undefined,
|
|
706
|
-
};
|
|
707
|
-
let result = await this.#database[executeStatement](statement);
|
|
708
|
-
if (!returning) {
|
|
709
|
-
return {
|
|
710
|
-
affectedRows: result.affectedRows ?? 0,
|
|
711
|
-
insertId: result.insertId,
|
|
712
|
-
};
|
|
713
|
-
}
|
|
714
|
-
return {
|
|
715
|
-
affectedRows: result.affectedRows ?? 0,
|
|
716
|
-
insertId: result.insertId,
|
|
717
|
-
rows: normalizeRows(result.rows),
|
|
718
|
-
};
|
|
719
|
-
}
|
|
720
|
-
/**
|
|
721
|
-
* Performs an upsert operation.
|
|
722
|
-
* @param values Values to insert.
|
|
723
|
-
* @param options Upsert options.
|
|
724
|
-
* @param options.returning Optional return selection for adapters that support returning.
|
|
725
|
-
* @param options.touch When `true`, manages timestamp columns automatically.
|
|
726
|
-
* @param options.conflictTarget Conflict target columns for adapters that require them.
|
|
727
|
-
* @param options.update Optional update payload used when a conflict occurs.
|
|
728
|
-
* @returns Upsert metadata, and optionally the returned row.
|
|
729
|
-
*/
|
|
730
|
-
async upsert(values, options) {
|
|
731
|
-
assertWriteState(this.#state, 'upsert', {
|
|
732
|
-
where: false,
|
|
733
|
-
orderBy: false,
|
|
734
|
-
limit: false,
|
|
735
|
-
offset: false,
|
|
736
|
-
});
|
|
737
|
-
if (!this.#database.adapter.capabilities.upsert) {
|
|
738
|
-
throw new DataTableQueryError('Adapter does not support upsert');
|
|
739
|
-
}
|
|
740
|
-
let preparedValues = prepareInsertValues(this.#table, values, this.#database.now(), options?.touch ?? true);
|
|
741
|
-
let updateChanges = options?.update
|
|
742
|
-
? prepareUpdateValues(this.#table, options.update, this.#database.now(), options?.touch ?? true)
|
|
743
|
-
: undefined;
|
|
744
|
-
let returning = options?.returning;
|
|
745
|
-
assertReturningCapability(this.#database.adapter, 'upsert', returning);
|
|
746
|
-
if (returning) {
|
|
747
|
-
let statement = {
|
|
748
|
-
kind: 'upsert',
|
|
749
|
-
table: this.#table,
|
|
750
|
-
values: preparedValues,
|
|
751
|
-
conflictTarget: options?.conflictTarget ? [...options.conflictTarget] : undefined,
|
|
752
|
-
update: updateChanges,
|
|
753
|
-
returning: normalizeReturningSelection(returning),
|
|
754
|
-
};
|
|
755
|
-
let result = await this.#database[executeStatement](statement);
|
|
756
|
-
let row = (normalizeRows(result.rows)[0] ?? null);
|
|
757
|
-
return {
|
|
758
|
-
affectedRows: result.affectedRows ?? 0,
|
|
759
|
-
insertId: result.insertId,
|
|
760
|
-
row,
|
|
761
|
-
};
|
|
762
|
-
}
|
|
763
|
-
let statement = {
|
|
764
|
-
kind: 'upsert',
|
|
765
|
-
table: this.#table,
|
|
766
|
-
values: preparedValues,
|
|
767
|
-
conflictTarget: options?.conflictTarget ? [...options.conflictTarget] : undefined,
|
|
768
|
-
update: updateChanges,
|
|
769
|
-
};
|
|
770
|
-
let result = await this.#database[executeStatement](statement);
|
|
771
|
-
let metadata = {
|
|
772
|
-
affectedRows: result.affectedRows ?? 0,
|
|
773
|
-
insertId: result.insertId,
|
|
774
|
-
};
|
|
775
|
-
return metadata;
|
|
776
|
-
}
|
|
777
|
-
#toSelectStatement() {
|
|
778
|
-
return {
|
|
779
|
-
kind: 'select',
|
|
780
|
-
table: this.#table,
|
|
781
|
-
select: cloneSelection(this.#state.select),
|
|
782
|
-
distinct: this.#state.distinct,
|
|
783
|
-
joins: [...this.#state.joins],
|
|
784
|
-
where: [...this.#state.where],
|
|
785
|
-
groupBy: [...this.#state.groupBy],
|
|
786
|
-
having: [...this.#state.having],
|
|
787
|
-
orderBy: [...this.#state.orderBy],
|
|
788
|
-
limit: this.#state.limit,
|
|
789
|
-
offset: this.#state.offset,
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
#clone(patch) {
|
|
793
|
-
return new QueryBuilder(this.#database, this.#table, {
|
|
794
|
-
select: patch.select ?? cloneSelection(this.#state.select),
|
|
795
|
-
distinct: patch.distinct ?? this.#state.distinct,
|
|
796
|
-
joins: patch.joins ? [...patch.joins] : [...this.#state.joins],
|
|
797
|
-
where: patch.where ? [...patch.where] : [...this.#state.where],
|
|
798
|
-
groupBy: patch.groupBy ? [...patch.groupBy] : [...this.#state.groupBy],
|
|
799
|
-
having: patch.having ? [...patch.having] : [...this.#state.having],
|
|
800
|
-
orderBy: patch.orderBy ? [...patch.orderBy] : [...this.#state.orderBy],
|
|
801
|
-
limit: patch.limit === undefined ? this.#state.limit : patch.limit,
|
|
802
|
-
offset: patch.offset === undefined ? this.#state.offset : patch.offset,
|
|
803
|
-
with: patch.with ? { ...patch.with } : { ...this.#state.with },
|
|
804
|
-
});
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
async function loadRelationsForRows(database, sourceTable, rows, relationMap) {
|
|
808
|
-
let output = rows.map((row) => ({ ...row }));
|
|
809
|
-
let relationNames = Object.keys(relationMap);
|
|
810
|
-
for (let relationName of relationNames) {
|
|
811
|
-
let relation = relationMap[relationName];
|
|
812
|
-
if (relation.sourceTable !== sourceTable) {
|
|
813
|
-
throw new DataTableQueryError('Relation "' +
|
|
814
|
-
relationName +
|
|
815
|
-
'" is not defined for source table "' +
|
|
816
|
-
getTableName(sourceTable) +
|
|
817
|
-
'"');
|
|
818
|
-
}
|
|
819
|
-
let values = await resolveRelationValues(database, output, relation);
|
|
820
|
-
let index = 0;
|
|
821
|
-
while (index < output.length) {
|
|
822
|
-
output[index][relationName] = values[index];
|
|
823
|
-
index += 1;
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
return output;
|
|
827
|
-
}
|
|
828
|
-
async function resolveRelationValues(database, sourceRows, relation) {
|
|
829
|
-
if (relation.relationKind === 'hasManyThrough') {
|
|
830
|
-
return loadHasManyThroughValues(database, sourceRows, relation);
|
|
831
|
-
}
|
|
832
|
-
return loadDirectRelationValues(database, sourceRows, relation);
|
|
833
|
-
}
|
|
834
|
-
async function loadDirectRelationValues(database, sourceRows, relation) {
|
|
835
|
-
if (sourceRows.length === 0) {
|
|
836
|
-
return [];
|
|
837
|
-
}
|
|
838
|
-
let sourceTuples = uniqueTuples(sourceRows, relation.sourceKey);
|
|
839
|
-
if (sourceTuples.length === 0) {
|
|
840
|
-
return sourceRows.map(() => (relation.cardinality === 'many' ? [] : null));
|
|
841
|
-
}
|
|
842
|
-
let query = database.query(relation.targetTable);
|
|
843
|
-
let linkPredicate = buildLinkPredicate(relation.targetKey, sourceTuples);
|
|
844
|
-
if (linkPredicate) {
|
|
845
|
-
query = query.where(linkPredicate);
|
|
846
|
-
}
|
|
847
|
-
query = applyRelationModifiers(query, relation, {
|
|
848
|
-
includePagination: false,
|
|
849
|
-
});
|
|
850
|
-
let relatedRows = (await query.all());
|
|
851
|
-
let grouped = groupRowsByTuple(relatedRows, relation.targetKey);
|
|
852
|
-
return sourceRows.map((sourceRow) => {
|
|
853
|
-
let key = getCompositeKey(sourceRow, relation.sourceKey);
|
|
854
|
-
let matches = grouped.get(key) ?? [];
|
|
855
|
-
let pagedMatches = applyPagination(matches, relation.modifiers.limit, relation.modifiers.offset);
|
|
856
|
-
if (relation.cardinality === 'many') {
|
|
857
|
-
return pagedMatches;
|
|
858
|
-
}
|
|
859
|
-
return pagedMatches[0] ?? null;
|
|
860
|
-
});
|
|
861
|
-
}
|
|
862
|
-
async function loadHasManyThroughValues(database, sourceRows, relation) {
|
|
863
|
-
if (!relation.through) {
|
|
864
|
-
throw new DataTableQueryError('hasManyThrough relation is missing through metadata');
|
|
865
|
-
}
|
|
866
|
-
if (sourceRows.length === 0) {
|
|
867
|
-
return [];
|
|
868
|
-
}
|
|
869
|
-
let throughRelation = relation.through.relation;
|
|
870
|
-
let sourceTuples = uniqueTuples(sourceRows, throughRelation.sourceKey);
|
|
871
|
-
if (sourceTuples.length === 0) {
|
|
872
|
-
return sourceRows.map(() => []);
|
|
873
|
-
}
|
|
874
|
-
let throughQuery = database.query(throughRelation.targetTable);
|
|
875
|
-
let throughPredicate = buildLinkPredicate(throughRelation.targetKey, sourceTuples);
|
|
876
|
-
if (throughPredicate) {
|
|
877
|
-
throughQuery = throughQuery.where(throughPredicate);
|
|
878
|
-
}
|
|
879
|
-
throughQuery = applyRelationModifiers(throughQuery, throughRelation, {
|
|
880
|
-
includePagination: false,
|
|
881
|
-
});
|
|
882
|
-
let throughRows = (await throughQuery.all());
|
|
883
|
-
if (throughRows.length === 0) {
|
|
884
|
-
return sourceRows.map(() => []);
|
|
885
|
-
}
|
|
886
|
-
let throughRowsBySource = groupRowsByTuple(throughRows, throughRelation.targetKey);
|
|
887
|
-
let pagedThroughRowsBySource = new Map();
|
|
888
|
-
let pagedThroughRows = [];
|
|
889
|
-
for (let sourceRow of sourceRows) {
|
|
890
|
-
let sourceKey = getCompositeKey(sourceRow, throughRelation.sourceKey);
|
|
891
|
-
let matchedThroughRows = throughRowsBySource.get(sourceKey) ?? [];
|
|
892
|
-
let pagedMatchedRows = applyPagination(matchedThroughRows, throughRelation.modifiers.limit, throughRelation.modifiers.offset);
|
|
893
|
-
pagedThroughRowsBySource.set(sourceKey, pagedMatchedRows);
|
|
894
|
-
pagedThroughRows.push(...pagedMatchedRows);
|
|
895
|
-
}
|
|
896
|
-
let throughTuples = uniqueTuples(pagedThroughRows, relation.through.throughSourceKey);
|
|
897
|
-
if (throughTuples.length === 0) {
|
|
898
|
-
return sourceRows.map(() => []);
|
|
899
|
-
}
|
|
900
|
-
let targetQuery = database.query(relation.targetTable);
|
|
901
|
-
let targetPredicate = buildLinkPredicate(relation.through.throughTargetKey, throughTuples);
|
|
902
|
-
if (targetPredicate) {
|
|
903
|
-
targetQuery = targetQuery.where(targetPredicate);
|
|
904
|
-
}
|
|
905
|
-
targetQuery = applyRelationModifiers(targetQuery, relation, {
|
|
906
|
-
includePagination: false,
|
|
907
|
-
});
|
|
908
|
-
let relatedRows = (await targetQuery.all());
|
|
909
|
-
let targetRowsByThrough = groupRowsByTuple(relatedRows, relation.through.throughTargetKey);
|
|
910
|
-
return sourceRows.map((sourceRow) => {
|
|
911
|
-
let sourceKey = getCompositeKey(sourceRow, throughRelation.sourceKey);
|
|
912
|
-
let matchedThroughRows = pagedThroughRowsBySource.get(sourceKey) ?? [];
|
|
913
|
-
let outputRows = [];
|
|
914
|
-
let seen = new Set();
|
|
915
|
-
for (let throughRow of matchedThroughRows) {
|
|
916
|
-
let throughKey = getCompositeKey(throughRow, relation.through.throughSourceKey);
|
|
917
|
-
let rowsForThrough = targetRowsByThrough.get(throughKey) ?? [];
|
|
918
|
-
for (let row of rowsForThrough) {
|
|
919
|
-
let rowIdentity = getCompositeKey(row, getTablePrimaryKey(relation.targetTable));
|
|
920
|
-
if (!seen.has(rowIdentity)) {
|
|
921
|
-
seen.add(rowIdentity);
|
|
922
|
-
outputRows.push(row);
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
return applyPagination(outputRows, relation.modifiers.limit, relation.modifiers.offset);
|
|
927
|
-
});
|
|
928
|
-
}
|
|
929
|
-
function applyRelationModifiers(query, relation, options) {
|
|
930
|
-
let next = query;
|
|
931
|
-
for (let predicate of relation.modifiers.where) {
|
|
932
|
-
next = next.where(predicate);
|
|
933
|
-
}
|
|
934
|
-
for (let clause of relation.modifiers.orderBy) {
|
|
935
|
-
next = next.orderBy(clause.column, clause.direction);
|
|
936
|
-
}
|
|
937
|
-
if (options.includePagination && relation.modifiers.limit !== undefined) {
|
|
938
|
-
next = next.limit(relation.modifiers.limit);
|
|
939
|
-
}
|
|
940
|
-
if (options.includePagination && relation.modifiers.offset !== undefined) {
|
|
941
|
-
next = next.offset(relation.modifiers.offset);
|
|
942
|
-
}
|
|
943
|
-
if (Object.keys(relation.modifiers.with).length > 0) {
|
|
944
|
-
next = next.with(relation.modifiers.with);
|
|
945
|
-
}
|
|
946
|
-
return next;
|
|
947
|
-
}
|
|
948
|
-
function applyPagination(rows, limit, offset) {
|
|
949
|
-
let offsetRows = offset === undefined ? rows : rows.slice(offset);
|
|
950
|
-
return limit === undefined ? offsetRows : offsetRows.slice(0, limit);
|
|
951
|
-
}
|
|
952
|
-
function normalizeRows(rows) {
|
|
953
|
-
if (!rows) {
|
|
954
|
-
return [];
|
|
955
|
-
}
|
|
956
|
-
return rows.map((row) => ({ ...row }));
|
|
957
|
-
}
|
|
958
|
-
function hasScopedWriteModifiers(state) {
|
|
959
|
-
return state.orderBy.length > 0 || state.limit !== undefined || state.offset !== undefined;
|
|
960
|
-
}
|
|
961
|
-
function asQueryTableInput(table) {
|
|
962
|
-
return table;
|
|
963
|
-
}
|
|
964
|
-
function getPrimaryKeyWhere(table, value) {
|
|
965
|
-
return getPrimaryKeyObject(table, value);
|
|
966
|
-
}
|
|
967
|
-
function getPrimaryKeyWhereFromRow(table, row) {
|
|
968
|
-
let where = {};
|
|
969
|
-
for (let key of getTablePrimaryKey(table)) {
|
|
970
|
-
where[key] = row[key];
|
|
971
|
-
}
|
|
972
|
-
return where;
|
|
973
|
-
}
|
|
974
|
-
function resolveCreateRowWhere(table, values, insertId) {
|
|
975
|
-
let primaryKey = getTablePrimaryKey(table);
|
|
976
|
-
if (primaryKey.length === 1) {
|
|
977
|
-
let key = primaryKey[0];
|
|
978
|
-
if (Object.prototype.hasOwnProperty.call(values, key)) {
|
|
979
|
-
return {
|
|
980
|
-
[key]: values[key],
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
if (insertId !== undefined) {
|
|
984
|
-
return {
|
|
985
|
-
[key]: insertId,
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
let where = {};
|
|
990
|
-
for (let key of primaryKey) {
|
|
991
|
-
if (!Object.prototype.hasOwnProperty.call(values, key)) {
|
|
992
|
-
throw new DataTableQueryError('create({ returnRow: true }) requires primary key values for table "' +
|
|
993
|
-
getTableName(table) +
|
|
994
|
-
'" when adapter does not support RETURNING');
|
|
995
|
-
}
|
|
996
|
-
where[key] = values[key];
|
|
997
|
-
}
|
|
998
|
-
return where;
|
|
999
|
-
}
|
|
1000
|
-
function normalizeOrderByInput(input) {
|
|
1001
|
-
if (!input) {
|
|
1002
|
-
return [];
|
|
1003
|
-
}
|
|
1004
|
-
if (input.length === 0) {
|
|
1005
|
-
return [];
|
|
1006
|
-
}
|
|
1007
|
-
if (Array.isArray(input[0])) {
|
|
1008
|
-
return input;
|
|
1009
|
-
}
|
|
1010
|
-
return [input];
|
|
1011
|
-
}
|
|
1012
|
-
function toWriteResult(result) {
|
|
1013
|
-
return {
|
|
1014
|
-
affectedRows: result.affectedRows,
|
|
1015
|
-
insertId: result.insertId,
|
|
1016
|
-
};
|
|
1017
|
-
}
|
|
1018
|
-
function assertWriteState(state, operation, policy) {
|
|
1019
|
-
let unsupported = [];
|
|
1020
|
-
if (state.select !== '*') {
|
|
1021
|
-
unsupported.push('select()');
|
|
1022
|
-
}
|
|
1023
|
-
if (state.distinct) {
|
|
1024
|
-
unsupported.push('distinct()');
|
|
1025
|
-
}
|
|
1026
|
-
if (state.joins.length > 0) {
|
|
1027
|
-
unsupported.push('join()');
|
|
1028
|
-
}
|
|
1029
|
-
if (state.groupBy.length > 0) {
|
|
1030
|
-
unsupported.push('groupBy()');
|
|
1031
|
-
}
|
|
1032
|
-
if (state.having.length > 0) {
|
|
1033
|
-
unsupported.push('having()');
|
|
1034
|
-
}
|
|
1035
|
-
if (Object.keys(state.with).length > 0) {
|
|
1036
|
-
unsupported.push('with()');
|
|
1037
|
-
}
|
|
1038
|
-
if (!policy.where && state.where.length > 0) {
|
|
1039
|
-
unsupported.push('where()');
|
|
1040
|
-
}
|
|
1041
|
-
if (!policy.orderBy && state.orderBy.length > 0) {
|
|
1042
|
-
unsupported.push('orderBy()');
|
|
1043
|
-
}
|
|
1044
|
-
if (!policy.limit && state.limit !== undefined) {
|
|
1045
|
-
unsupported.push('limit()');
|
|
1046
|
-
}
|
|
1047
|
-
if (!policy.offset && state.offset !== undefined) {
|
|
1048
|
-
unsupported.push('offset()');
|
|
1049
|
-
}
|
|
1050
|
-
if (unsupported.length > 0) {
|
|
1051
|
-
throw new DataTableQueryError(operation + '() does not support these query modifiers: ' + unsupported.join(', '));
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
async function loadPrimaryKeyRowsForScope(database, table, state) {
|
|
1055
|
-
let query = database.query(table);
|
|
1056
|
-
for (let predicate of state.where) {
|
|
1057
|
-
query = query.where(predicate);
|
|
1058
|
-
}
|
|
1059
|
-
for (let clause of state.orderBy) {
|
|
1060
|
-
query = query.orderBy(clause.column, clause.direction);
|
|
1061
|
-
}
|
|
1062
|
-
if (state.limit !== undefined) {
|
|
1063
|
-
query = query.limit(state.limit);
|
|
1064
|
-
}
|
|
1065
|
-
if (state.offset !== undefined) {
|
|
1066
|
-
query = query.offset(state.offset);
|
|
1067
|
-
}
|
|
1068
|
-
let rows = await query
|
|
1069
|
-
.select(...getTablePrimaryKey(table))
|
|
1070
|
-
.all();
|
|
1071
|
-
let primaryKeys = getTablePrimaryKey(table);
|
|
1072
|
-
return rows.map((row) => {
|
|
1073
|
-
let keyObject = {};
|
|
1074
|
-
for (let key of rowKeys(row, primaryKeys)) {
|
|
1075
|
-
keyObject[key] = row[key];
|
|
1076
|
-
}
|
|
1077
|
-
return keyObject;
|
|
311
|
+
export function createDatabaseWithTransaction(adapter, token, options) {
|
|
312
|
+
return Database[createInternalDatabase](adapter, options, {
|
|
313
|
+
token,
|
|
314
|
+
savepointCounter: { value: 0 },
|
|
1078
315
|
});
|
|
1079
316
|
}
|
|
1080
|
-
function createInitialQueryState() {
|
|
1081
|
-
return {
|
|
1082
|
-
select: '*',
|
|
1083
|
-
distinct: false,
|
|
1084
|
-
joins: [],
|
|
1085
|
-
where: [],
|
|
1086
|
-
groupBy: [],
|
|
1087
|
-
having: [],
|
|
1088
|
-
orderBy: [],
|
|
1089
|
-
with: {},
|
|
1090
|
-
};
|
|
1091
|
-
}
|
|
1092
|
-
function cloneSelection(selection) {
|
|
1093
|
-
if (selection === '*') {
|
|
1094
|
-
return '*';
|
|
1095
|
-
}
|
|
1096
|
-
return selection.map((column) => ({ ...column }));
|
|
1097
|
-
}
|
|
1098
317
|
function defaultNow() {
|
|
1099
318
|
return new Date();
|
|
1100
319
|
}
|
|
1101
|
-
function prepareInsertValues(table, values, now, touch) {
|
|
1102
|
-
let output = validateWriteValues(table, values);
|
|
1103
|
-
let timestamps = getTableTimestamps(table);
|
|
1104
|
-
let columns = getTableColumns(table);
|
|
1105
|
-
if (touch && timestamps) {
|
|
1106
|
-
let createdAt = timestamps.createdAt;
|
|
1107
|
-
let updatedAt = timestamps.updatedAt;
|
|
1108
|
-
if (Object.prototype.hasOwnProperty.call(columns, createdAt) &&
|
|
1109
|
-
output[createdAt] === undefined) {
|
|
1110
|
-
output[createdAt] = now;
|
|
1111
|
-
}
|
|
1112
|
-
if (Object.prototype.hasOwnProperty.call(columns, updatedAt) &&
|
|
1113
|
-
output[updatedAt] === undefined) {
|
|
1114
|
-
output[updatedAt] = now;
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
return output;
|
|
1118
|
-
}
|
|
1119
|
-
function prepareUpdateValues(table, values, now, touch) {
|
|
1120
|
-
let output = validateWriteValues(table, values);
|
|
1121
|
-
let timestamps = getTableTimestamps(table);
|
|
1122
|
-
let columns = getTableColumns(table);
|
|
1123
|
-
if (touch && timestamps) {
|
|
1124
|
-
let updatedAt = timestamps.updatedAt;
|
|
1125
|
-
if (Object.prototype.hasOwnProperty.call(columns, updatedAt) &&
|
|
1126
|
-
output[updatedAt] === undefined) {
|
|
1127
|
-
output[updatedAt] = now;
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
return output;
|
|
1131
|
-
}
|
|
1132
|
-
function validateWriteValues(table, values) {
|
|
1133
|
-
let columns = getTableColumns(table);
|
|
1134
|
-
let tableName = getTableName(table);
|
|
1135
|
-
let result = validatePartialRow(table, values);
|
|
1136
|
-
if ('issues' in result) {
|
|
1137
|
-
let firstIssue = result.issues[0];
|
|
1138
|
-
let issuePath = firstIssue?.path;
|
|
1139
|
-
let firstPathSegment = issuePath && issuePath.length > 0 ? issuePath[0] : undefined;
|
|
1140
|
-
let column = typeof firstPathSegment === 'string' ? firstPathSegment : undefined;
|
|
1141
|
-
if (column && !Object.prototype.hasOwnProperty.call(columns, column)) {
|
|
1142
|
-
throw new DataTableValidationError('Unknown column "' + column + '" for table "' + tableName + '"', []);
|
|
1143
|
-
}
|
|
1144
|
-
if (column) {
|
|
1145
|
-
throw new DataTableValidationError('Invalid value for column "' + column + '" in table "' + tableName + '"', result.issues, {
|
|
1146
|
-
metadata: {
|
|
1147
|
-
table: tableName,
|
|
1148
|
-
column,
|
|
1149
|
-
},
|
|
1150
|
-
});
|
|
1151
|
-
}
|
|
1152
|
-
throw new DataTableValidationError('Invalid value for table "' + tableName + '"', result.issues, {
|
|
1153
|
-
metadata: {
|
|
1154
|
-
table: tableName,
|
|
1155
|
-
},
|
|
1156
|
-
});
|
|
1157
|
-
}
|
|
1158
|
-
return result.value;
|
|
1159
|
-
}
|
|
1160
|
-
function createPredicateColumnResolver(tables) {
|
|
1161
|
-
let qualifiedColumns = new Map();
|
|
1162
|
-
let unqualifiedColumns = new Map();
|
|
1163
|
-
let ambiguousColumns = new Set();
|
|
1164
|
-
for (let table of tables) {
|
|
1165
|
-
let tableColumns = getTableColumns(table);
|
|
1166
|
-
let tableName = getTableName(table);
|
|
1167
|
-
for (let columnName in tableColumns) {
|
|
1168
|
-
if (!Object.prototype.hasOwnProperty.call(tableColumns, columnName)) {
|
|
1169
|
-
continue;
|
|
1170
|
-
}
|
|
1171
|
-
let resolvedColumn = {
|
|
1172
|
-
tableName,
|
|
1173
|
-
columnName,
|
|
1174
|
-
schema: tableColumns[columnName],
|
|
1175
|
-
};
|
|
1176
|
-
qualifiedColumns.set(tableName + '.' + columnName, resolvedColumn);
|
|
1177
|
-
if (ambiguousColumns.has(columnName)) {
|
|
1178
|
-
continue;
|
|
1179
|
-
}
|
|
1180
|
-
if (unqualifiedColumns.has(columnName)) {
|
|
1181
|
-
unqualifiedColumns.delete(columnName);
|
|
1182
|
-
ambiguousColumns.add(columnName);
|
|
1183
|
-
continue;
|
|
1184
|
-
}
|
|
1185
|
-
unqualifiedColumns.set(columnName, resolvedColumn);
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
return function resolveColumn(column) {
|
|
1189
|
-
let qualified = qualifiedColumns.get(column);
|
|
1190
|
-
if (qualified) {
|
|
1191
|
-
return qualified;
|
|
1192
|
-
}
|
|
1193
|
-
if (column.includes('.')) {
|
|
1194
|
-
throw new DataTableQueryError('Unknown predicate column "' + column + '"');
|
|
1195
|
-
}
|
|
1196
|
-
if (ambiguousColumns.has(column)) {
|
|
1197
|
-
throw new DataTableQueryError('Ambiguous predicate column "' + column + '". Use a qualified column name');
|
|
1198
|
-
}
|
|
1199
|
-
let unqualified = unqualifiedColumns.get(column);
|
|
1200
|
-
if (!unqualified) {
|
|
1201
|
-
throw new DataTableQueryError('Unknown predicate column "' + column + '"');
|
|
1202
|
-
}
|
|
1203
|
-
return unqualified;
|
|
1204
|
-
};
|
|
1205
|
-
}
|
|
1206
|
-
function normalizePredicateValues(predicate, resolveColumn) {
|
|
1207
|
-
if (predicate.type === 'comparison') {
|
|
1208
|
-
let column = resolveColumn(predicate.column);
|
|
1209
|
-
if (predicate.valueType === 'column') {
|
|
1210
|
-
resolveColumn(predicate.value);
|
|
1211
|
-
return predicate;
|
|
1212
|
-
}
|
|
1213
|
-
if ((predicate.operator === 'eq' || predicate.operator === 'ne') &&
|
|
1214
|
-
(predicate.value === null || predicate.value === undefined)) {
|
|
1215
|
-
return predicate;
|
|
1216
|
-
}
|
|
1217
|
-
if (predicate.operator === 'in' || predicate.operator === 'notIn') {
|
|
1218
|
-
if (!Array.isArray(predicate.value)) {
|
|
1219
|
-
throw new DataTableValidationError('Invalid filter value for column "' +
|
|
1220
|
-
column.columnName +
|
|
1221
|
-
'" in table "' +
|
|
1222
|
-
column.tableName +
|
|
1223
|
-
'"', [{ message: 'Expected an array value for "' + predicate.operator + '" predicate' }], {
|
|
1224
|
-
metadata: {
|
|
1225
|
-
table: column.tableName,
|
|
1226
|
-
column: column.columnName,
|
|
1227
|
-
},
|
|
1228
|
-
});
|
|
1229
|
-
}
|
|
1230
|
-
let parsedValues = predicate.value.map((value) => parsePredicateValue(column, value));
|
|
1231
|
-
return {
|
|
1232
|
-
...predicate,
|
|
1233
|
-
value: parsedValues,
|
|
1234
|
-
};
|
|
1235
|
-
}
|
|
1236
|
-
return {
|
|
1237
|
-
...predicate,
|
|
1238
|
-
value: parsePredicateValue(column, predicate.value),
|
|
1239
|
-
};
|
|
1240
|
-
}
|
|
1241
|
-
if (predicate.type === 'between') {
|
|
1242
|
-
let column = resolveColumn(predicate.column);
|
|
1243
|
-
return {
|
|
1244
|
-
...predicate,
|
|
1245
|
-
lower: parsePredicateValue(column, predicate.lower),
|
|
1246
|
-
upper: parsePredicateValue(column, predicate.upper),
|
|
1247
|
-
};
|
|
1248
|
-
}
|
|
1249
|
-
if (predicate.type === 'null') {
|
|
1250
|
-
resolveColumn(predicate.column);
|
|
1251
|
-
return predicate;
|
|
1252
|
-
}
|
|
1253
|
-
return {
|
|
1254
|
-
...predicate,
|
|
1255
|
-
predicates: predicate.predicates.map((child) => normalizePredicateValues(child, resolveColumn)),
|
|
1256
|
-
};
|
|
1257
|
-
}
|
|
1258
|
-
function parsePredicateValue(column, value) {
|
|
1259
|
-
let result = parseSafe(column.schema, value);
|
|
1260
|
-
if (!result.success) {
|
|
1261
|
-
throw new DataTableValidationError('Invalid filter value for column "' +
|
|
1262
|
-
column.columnName +
|
|
1263
|
-
'" in table "' +
|
|
1264
|
-
column.tableName +
|
|
1265
|
-
'"', result.issues, {
|
|
1266
|
-
metadata: {
|
|
1267
|
-
table: column.tableName,
|
|
1268
|
-
column: column.columnName,
|
|
1269
|
-
},
|
|
1270
|
-
});
|
|
1271
|
-
}
|
|
1272
|
-
return result.value;
|
|
1273
|
-
}
|
|
1274
|
-
function uniqueTuples(rows, columns) {
|
|
1275
|
-
let output = [];
|
|
1276
|
-
let seen = new Set();
|
|
1277
|
-
for (let row of rows) {
|
|
1278
|
-
let tuple = columns.map((column) => row[column]);
|
|
1279
|
-
let key = tuple.map(stringifyForKey).join('::');
|
|
1280
|
-
if (!seen.has(key)) {
|
|
1281
|
-
seen.add(key);
|
|
1282
|
-
output.push(tuple);
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
return output;
|
|
1286
|
-
}
|
|
1287
|
-
function buildLinkPredicate(targetColumns, tuples) {
|
|
1288
|
-
if (tuples.length === 0) {
|
|
1289
|
-
return undefined;
|
|
1290
|
-
}
|
|
1291
|
-
if (targetColumns.length === 1) {
|
|
1292
|
-
return inList(targetColumns[0], tuples.map((tuple) => tuple[0]));
|
|
1293
|
-
}
|
|
1294
|
-
let tuplePredicates = tuples.map((tuple) => {
|
|
1295
|
-
let comparisons = targetColumns.map((column, index) => eq(column, tuple[index]));
|
|
1296
|
-
return and(...comparisons);
|
|
1297
|
-
});
|
|
1298
|
-
return or(...tuplePredicates);
|
|
1299
|
-
}
|
|
1300
|
-
function groupRowsByTuple(rows, columns) {
|
|
1301
|
-
let output = new Map();
|
|
1302
|
-
for (let row of rows) {
|
|
1303
|
-
let key = getCompositeKey(row, columns);
|
|
1304
|
-
let group = output.get(key);
|
|
1305
|
-
if (group) {
|
|
1306
|
-
group.push(row);
|
|
1307
|
-
continue;
|
|
1308
|
-
}
|
|
1309
|
-
output.set(key, [row]);
|
|
1310
|
-
}
|
|
1311
|
-
return output;
|
|
1312
|
-
}
|
|
1313
|
-
function stringifyForKey(value) {
|
|
1314
|
-
if (value === null) {
|
|
1315
|
-
return 'null';
|
|
1316
|
-
}
|
|
1317
|
-
if (value === undefined) {
|
|
1318
|
-
return 'undefined';
|
|
1319
|
-
}
|
|
1320
|
-
if (value instanceof Date) {
|
|
1321
|
-
return 'date:' + value.toISOString();
|
|
1322
|
-
}
|
|
1323
|
-
if (typeof value === 'string') {
|
|
1324
|
-
return JSON.stringify(value);
|
|
1325
|
-
}
|
|
1326
|
-
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
1327
|
-
return String(value);
|
|
1328
|
-
}
|
|
1329
|
-
return JSON.stringify(value);
|
|
1330
|
-
}
|
|
1331
|
-
function normalizeReturningSelection(returning) {
|
|
1332
|
-
if (returning === '*') {
|
|
1333
|
-
return '*';
|
|
1334
|
-
}
|
|
1335
|
-
return [...returning];
|
|
1336
|
-
}
|
|
1337
|
-
function buildPrimaryKeyPredicate(table, keyObjects) {
|
|
1338
|
-
let primaryKey = getTablePrimaryKey(table);
|
|
1339
|
-
if (keyObjects.length === 0) {
|
|
1340
|
-
return undefined;
|
|
1341
|
-
}
|
|
1342
|
-
if (primaryKey.length === 1) {
|
|
1343
|
-
let key = primaryKey[0];
|
|
1344
|
-
return inList(key, keyObjects.map((objectValue) => objectValue[key]));
|
|
1345
|
-
}
|
|
1346
|
-
let predicates = keyObjects.map((objectValue) => {
|
|
1347
|
-
let comparisons = primaryKey.map((key) => {
|
|
1348
|
-
let typedKey = key;
|
|
1349
|
-
return eq(typedKey, objectValue[typedKey]);
|
|
1350
|
-
});
|
|
1351
|
-
return and(...comparisons);
|
|
1352
|
-
});
|
|
1353
|
-
return or(...predicates);
|
|
1354
|
-
}
|
|
1355
|
-
function rowKeys(row, keys) {
|
|
1356
|
-
let output = [];
|
|
1357
|
-
for (let key of keys) {
|
|
1358
|
-
if (Object.prototype.hasOwnProperty.call(row, key)) {
|
|
1359
|
-
output.push(key);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
return output;
|
|
1363
|
-
}
|
|
1364
|
-
function assertReturningCapability(adapter, operation, returning) {
|
|
1365
|
-
if (returning && !adapter.capabilities.returning) {
|
|
1366
|
-
throw new DataTableQueryError(operation + '() returning is not supported by this adapter');
|
|
1367
|
-
}
|
|
1368
|
-
}
|