uql-orm 0.93.0 → 0.93.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/dist/dialect/abstractSqlDialect.js +9 -2
- package/dist/migrate/ddl/index.d.ts +1 -1
- package/dist/migrate/ddl/index.js +3 -3
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +3 -1
- package/dist/migrate/ddl/mssqlTableDdl.js +4 -0
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +1 -1
- package/dist/migrate/ddl/mysqlTableDdl.js +2 -2
- package/dist/migrate/ddl/pgTableDdl.d.ts +5 -1
- package/dist/migrate/ddl/pgTableDdl.js +12 -6
- package/dist/migrate/ddl/tableDdl.d.ts +9 -6
- package/dist/migrate/ddl/tableDdl.js +15 -6
- package/dist/migrate/ddl/tableRebuild.d.ts +2 -5
- package/dist/migrate/schemaChange.d.ts +2 -5
- package/dist/migrate/schemaGenerator.js +1 -1
- package/dist/mongo/mongoDialect.d.ts +0 -2
- package/dist/mongo/mongoDialect.js +18 -14
- package/dist/querier/abstractQuerierPool.js +22 -22
- package/dist/schema/types.d.ts +2 -5
- package/dist/type/entity.d.ts +5 -5
- package/dist/type/migration.d.ts +7 -8
- package/dist/util/dialect.util.d.ts +1 -1
- package/package.json +10 -10
- package/skills/uql-orm/SKILL.md +19 -50
|
@@ -1311,9 +1311,16 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1311
1311
|
else if (isFieldUpdateOp(value)) {
|
|
1312
1312
|
const [op, operand] = fieldUpdateOf(key, value);
|
|
1313
1313
|
ctx.append(`${escapedCol} = COALESCE(${current}, 0) ${SQL_ARITHMETIC[op]} `);
|
|
1314
|
-
|
|
1314
|
+
if (operand instanceof QueryRaw) {
|
|
1315
|
+
ctx.append('(');
|
|
1316
|
+
this.getRawValue(ctx, { value: operand, escapedPrefix: qualifier });
|
|
1317
|
+
ctx.append(')');
|
|
1318
|
+
}
|
|
1319
|
+
else {
|
|
1320
|
+
ctx.addValue(operand);
|
|
1321
|
+
}
|
|
1315
1322
|
}
|
|
1316
|
-
else if (
|
|
1323
|
+
else if (value instanceof QueryRaw) {
|
|
1317
1324
|
ctx.append(`${escapedCol} = `);
|
|
1318
1325
|
this.getRawValue(ctx, { value, escapedPrefix: qualifier });
|
|
1319
1326
|
}
|
|
@@ -7,7 +7,7 @@ export { MsSqlTableDdl } from './mssqlTableDdl.js';
|
|
|
7
7
|
export { MariaIndexDdl, MySqlIndexDdl, MysqlLikeIndexDdl } from './mysqlIndexDdl.js';
|
|
8
8
|
export { MySqlTableDdl } from './mysqlTableDdl.js';
|
|
9
9
|
export { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
|
|
10
|
-
export { PgTableDdl } from './pgTableDdl.js';
|
|
10
|
+
export { CockroachTableDdl, PgTableDdl } from './pgTableDdl.js';
|
|
11
11
|
export { SqliteIndexDdl } from './sqliteIndexDdl.js';
|
|
12
12
|
export { TableDdl } from './tableDdl.js';
|
|
13
13
|
export declare function indexDdlFor(dialect: AbstractSqlDialect): IndexDdl;
|
|
@@ -4,7 +4,7 @@ import { MsSqlTableDdl } from './mssqlTableDdl.js';
|
|
|
4
4
|
import { MariaIndexDdl, MySqlIndexDdl } from './mysqlIndexDdl.js';
|
|
5
5
|
import { MySqlTableDdl } from './mysqlTableDdl.js';
|
|
6
6
|
import { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
|
|
7
|
-
import { PgTableDdl } from './pgTableDdl.js';
|
|
7
|
+
import { CockroachTableDdl, PgTableDdl } from './pgTableDdl.js';
|
|
8
8
|
import { SqliteIndexDdl } from './sqliteIndexDdl.js';
|
|
9
9
|
import { TableDdl } from './tableDdl.js';
|
|
10
10
|
export { IndexDdl } from './indexDdl.js';
|
|
@@ -13,7 +13,7 @@ export { MsSqlTableDdl } from './mssqlTableDdl.js';
|
|
|
13
13
|
export { MariaIndexDdl, MySqlIndexDdl, MysqlLikeIndexDdl } from './mysqlIndexDdl.js';
|
|
14
14
|
export { MySqlTableDdl } from './mysqlTableDdl.js';
|
|
15
15
|
export { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
|
|
16
|
-
export { PgTableDdl } from './pgTableDdl.js';
|
|
16
|
+
export { CockroachTableDdl, PgTableDdl } from './pgTableDdl.js';
|
|
17
17
|
export { SqliteIndexDdl } from './sqliteIndexDdl.js';
|
|
18
18
|
export { TableDdl } from './tableDdl.js';
|
|
19
19
|
/**
|
|
@@ -34,7 +34,7 @@ export function indexDdlFor(dialect) {
|
|
|
34
34
|
/** Each engine's table DDL, keyed by `dialectName` and exhaustive, for the same reasons as {@link INDEX_DDL}. */
|
|
35
35
|
const TABLE_DDL = {
|
|
36
36
|
postgres: PgTableDdl,
|
|
37
|
-
cockroachdb:
|
|
37
|
+
cockroachdb: CockroachTableDdl,
|
|
38
38
|
mysql: MySqlTableDdl,
|
|
39
39
|
mariadb: MySqlTableDdl,
|
|
40
40
|
mssql: MsSqlTableDdl,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ColumnSchema } from '../../type/index.js';
|
|
1
|
+
import type { Alteration, ColumnSchema } from '../../type/index.js';
|
|
2
2
|
import { TableDdl } from './tableDdl.js';
|
|
3
3
|
/**
|
|
4
4
|
* SQL Server keeps a column's `DEFAULT`, `CHECK` and `UNIQUE` as constraints under names it picks, and
|
|
@@ -17,6 +17,8 @@ export declare class MsSqlTableDdl extends TableDdl {
|
|
|
17
17
|
* constraint of its own. A `CHECK` or `UNIQUE` stays, and the server refuses a retype it blocks.
|
|
18
18
|
*/
|
|
19
19
|
alterColumn(table: string, column: ColumnSchema): string[];
|
|
20
|
+
/** One column an `ALTER COLUMN`, each with the batch {@link alterColumn} writes. */
|
|
21
|
+
alterColumns(table: string, alterations: readonly Alteration<ColumnSchema>[]): string[];
|
|
20
22
|
renameColumn(table: string, oldName: string, newName: string): string;
|
|
21
23
|
renameTable(oldName: string, newName: string): string;
|
|
22
24
|
dropIndex(table: string, index: string): string;
|
|
@@ -49,6 +49,10 @@ export class MsSqlTableDdl extends TableDdl {
|
|
|
49
49
|
}
|
|
50
50
|
return statements;
|
|
51
51
|
}
|
|
52
|
+
/** One column an `ALTER COLUMN`, each with the batch {@link alterColumn} writes. */
|
|
53
|
+
alterColumns(table, alterations) {
|
|
54
|
+
return alterations.flatMap(({ to }) => this.alterColumn(table, to));
|
|
55
|
+
}
|
|
52
56
|
renameColumn(table, oldName, newName) {
|
|
53
57
|
const qualified = `${this.dialect.escapeId(table)}.${this.dialect.escapeId(oldName)}`;
|
|
54
58
|
return /*sql*/ `EXEC sp_rename ${this.dialect.escape(qualified)}, ${this.dialect.escape(newName)}, 'COLUMN';`;
|
|
@@ -8,7 +8,7 @@ export declare class MySqlTableDdl extends TableDdl {
|
|
|
8
8
|
* is added nullable and then made required, which fails on those rows as it does on other engines.
|
|
9
9
|
*/
|
|
10
10
|
addColumnStatements(table: string, column: ColumnSchema, render: (column: ColumnSchema) => string): string[];
|
|
11
|
-
|
|
11
|
+
protected alterClauses(_column: ColumnSchema, definition: string): string[];
|
|
12
12
|
/** Ignores `schema`: MySQL reads it from the table name, which is already qualified. */
|
|
13
13
|
dropIndex(table: string, index: string): string;
|
|
14
14
|
dropForeignKey(table: string, constraint: string): string;
|
|
@@ -16,8 +16,8 @@ export class MySqlTableDdl extends TableDdl {
|
|
|
16
16
|
...this.alterColumn(table, column, render(column)),
|
|
17
17
|
];
|
|
18
18
|
}
|
|
19
|
-
|
|
20
|
-
return [`
|
|
19
|
+
alterClauses(_column, definition) {
|
|
20
|
+
return [`MODIFY COLUMN ${definition}`];
|
|
21
21
|
}
|
|
22
22
|
/** Ignores `schema`: MySQL reads it from the table name, which is already qualified. */
|
|
23
23
|
dropIndex(table, index) {
|
|
@@ -3,5 +3,9 @@ import { TableDdl } from './tableDdl.js';
|
|
|
3
3
|
/** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
|
|
4
4
|
export declare class PgTableDdl extends TableDdl {
|
|
5
5
|
/** A clause for each part that differs from `from`, the column as it was, or for every part without it. */
|
|
6
|
-
|
|
6
|
+
protected alterClauses(column: ColumnSchema, _definition: string, from?: ColumnSchema): string[];
|
|
7
|
+
}
|
|
8
|
+
/** CockroachDB refuses a rewriting retype beside any other clause, and changes a schema online anyway. */
|
|
9
|
+
export declare class CockroachTableDdl extends PgTableDdl {
|
|
10
|
+
protected alterTable(table: string, clauses: readonly string[]): string[];
|
|
7
11
|
}
|
|
@@ -3,15 +3,21 @@ import { TableDdl } from './tableDdl.js';
|
|
|
3
3
|
/** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
|
|
4
4
|
export class PgTableDdl extends TableDdl {
|
|
5
5
|
/** A clause for each part that differs from `from`, the column as it was, or for every part without it. */
|
|
6
|
-
|
|
6
|
+
alterClauses(column, _definition, from) {
|
|
7
7
|
const name = this.dialect.escapeId(column.name);
|
|
8
|
-
const alter = `ALTER
|
|
8
|
+
const alter = `ALTER COLUMN ${name}`;
|
|
9
9
|
return [
|
|
10
10
|
// Casts explicitly: Postgres converts on its own only between compatible types, and text to integer is not.
|
|
11
|
-
(!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type}
|
|
12
|
-
(!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}
|
|
11
|
+
(!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type}`,
|
|
12
|
+
(!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}`,
|
|
13
13
|
(!from || !sameDefault(column.defaultValue, from.defaultValue, this.dialect)) &&
|
|
14
|
-
(column.defaultValue === undefined ? `${alter} DROP DEFAULT
|
|
15
|
-
].filter((
|
|
14
|
+
(column.defaultValue === undefined ? `${alter} DROP DEFAULT` : `${alter} SET${this.defaultClause(column)}`),
|
|
15
|
+
].filter((clause) => clause !== false);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** CockroachDB refuses a rewriting retype beside any other clause, and changes a schema online anyway. */
|
|
19
|
+
export class CockroachTableDdl extends PgTableDdl {
|
|
20
|
+
alterTable(table, clauses) {
|
|
21
|
+
return clauses.flatMap((clause) => super.alterTable(table, [clause]));
|
|
16
22
|
}
|
|
17
23
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/abstractSqlDialect.js';
|
|
2
|
-
import type { ColumnSchema } from '../../type/index.js';
|
|
2
|
+
import type { Alteration, ColumnSchema } from '../../type/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* A column's type with the size it was read back with, unless its spelling already carries one:
|
|
5
5
|
* introspection reports `VARCHAR` and `255` apart, where a type from an entity is already whole.
|
|
@@ -20,11 +20,14 @@ export declare class TableDdl {
|
|
|
20
20
|
/** The statements that add `column`, whose definition `render` writes. */
|
|
21
21
|
addColumnStatements(table: string, column: ColumnSchema, render: (column: ColumnSchema) => string): string[];
|
|
22
22
|
dropColumn(table: string, column: string): string[];
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
/** The statements that change a column from `from`, what it was, to `column`, whose definition is `definition`. */
|
|
24
|
+
alterColumn(table: string, column: ColumnSchema, definition: string, from?: ColumnSchema): string[];
|
|
25
|
+
/** The statements making `alterations` to one table, whose new definitions `render` writes. */
|
|
26
|
+
alterColumns(table: string, alterations: readonly Alteration<ColumnSchema>[], render: (column: ColumnSchema) => string): string[];
|
|
27
|
+
/** The `ALTER TABLE` clauses that change a column, as {@link alterColumn} takes it. */
|
|
28
|
+
protected alterClauses(_column: ColumnSchema, definition: string, _from?: ColumnSchema): string[];
|
|
29
|
+
/** One `ALTER TABLE` making every clause, and none for no clause. */
|
|
30
|
+
protected alterTable(table: string, clauses: readonly string[]): string[];
|
|
28
31
|
renameColumn(table: string, oldName: string, newName: string): string;
|
|
29
32
|
renameTable(oldName: string, newName: string): string;
|
|
30
33
|
/** `schema` is the table's schema, which also holds its indexes. */
|
|
@@ -39,12 +39,21 @@ export class TableDdl {
|
|
|
39
39
|
dropColumn(table, column) {
|
|
40
40
|
return [`ALTER TABLE ${this.dialect.escapeId(table)} DROP COLUMN ${this.dialect.escapeId(column)};`];
|
|
41
41
|
}
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
42
|
+
/** The statements that change a column from `from`, what it was, to `column`, whose definition is `definition`. */
|
|
43
|
+
alterColumn(table, column, definition, from) {
|
|
44
|
+
return this.alterTable(table, this.alterClauses(column, definition, from));
|
|
45
|
+
}
|
|
46
|
+
/** The statements making `alterations` to one table, whose new definitions `render` writes. */
|
|
47
|
+
alterColumns(table, alterations, render) {
|
|
48
|
+
return this.alterTable(table, alterations.flatMap(({ from, to }) => this.alterClauses(to, render(to), from)));
|
|
49
|
+
}
|
|
50
|
+
/** The `ALTER TABLE` clauses that change a column, as {@link alterColumn} takes it. */
|
|
51
|
+
alterClauses(_column, definition, _from) {
|
|
52
|
+
return [`ALTER COLUMN ${definition}`];
|
|
53
|
+
}
|
|
54
|
+
/** One `ALTER TABLE` making every clause, and none for no clause. */
|
|
55
|
+
alterTable(table, clauses) {
|
|
56
|
+
return clauses.length ? [`ALTER TABLE ${this.dialect.escapeId(table)} ${clauses.join(', ')};`] : [];
|
|
48
57
|
}
|
|
49
58
|
renameColumn(table, oldName, newName) {
|
|
50
59
|
const [target, from, to] = [table, oldName, newName].map((name) => this.dialect.escapeId(name));
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
2
|
-
import type { RebuiltTable, Rename } from '../../type/index.js';
|
|
2
|
+
import type { Alteration, RebuiltTable, Rename } from '../../type/index.js';
|
|
3
3
|
/** What the copy reads besides the columns both sides share: renamed ones, and a default filling a column's nulls. */
|
|
4
4
|
export type RebuildCopy = {
|
|
5
5
|
readonly renames: readonly Rename[];
|
|
@@ -11,7 +11,4 @@ export type RebuildCopy = {
|
|
|
11
11
|
* key pointing at the table would delete or null its rows with the drop, so the guard fails the whole
|
|
12
12
|
* rebuild first unless foreign keys are off, as the migrator turns them off on a SQLite connection.
|
|
13
13
|
*/
|
|
14
|
-
export declare function rebuildTable(dialect: AbstractSqlDialect, table: string, { from, to }:
|
|
15
|
-
readonly from: RebuiltTable;
|
|
16
|
-
readonly to: RebuiltTable;
|
|
17
|
-
}, copy: RebuildCopy): string[];
|
|
14
|
+
export declare function rebuildTable(dialect: AbstractSqlDialect, table: string, { from, to }: Alteration<RebuiltTable>, copy: RebuildCopy): string[];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Change, ColumnSchema, SchemaDiff } from '../type/index.js';
|
|
1
|
+
import type { Alteration, Change, ColumnSchema, SchemaDiff } from '../type/index.js';
|
|
2
2
|
/** Each change's end on `side`, where it has one: what a drop half removes (`from`), or an add half creates (`to`). */
|
|
3
3
|
export declare function sides<T>(changes: readonly Change<T>[] | undefined, side: 'from' | 'to'): T[];
|
|
4
4
|
/** What the changes add: each `to` with no `from`. */
|
|
@@ -6,10 +6,7 @@ export declare function added<T>(changes?: readonly Change<T>[]): T[];
|
|
|
6
6
|
/** What the changes drop: each `from` with no `to`. */
|
|
7
7
|
export declare function dropped<T>(changes?: readonly Change<T>[]): T[];
|
|
8
8
|
/** The changes that alter an object in place, which only a column can. */
|
|
9
|
-
export declare function alterations<T>(changes?: readonly Change<T>[]):
|
|
10
|
-
readonly from: T;
|
|
11
|
-
readonly to: T;
|
|
12
|
-
}[];
|
|
9
|
+
export declare function alterations<T>(changes?: readonly Change<T>[]): Alteration<T>[];
|
|
13
10
|
/** Each column `changes` make required on the rows already there: added so, or no longer nullable. */
|
|
14
11
|
export declare function newlyRequired(changes?: readonly Change<ColumnSchema>[]): {
|
|
15
12
|
readonly from?: ColumnSchema;
|
|
@@ -200,7 +200,7 @@ export class SqlSchemaGenerator {
|
|
|
200
200
|
const name = this.escapeId(column);
|
|
201
201
|
return `UPDATE ${target} SET ${name} = ${value} WHERE ${name} IS NULL;`;
|
|
202
202
|
}),
|
|
203
|
-
...alterations(columns)
|
|
203
|
+
...this.tableDdl.alterColumns(tableName, alterations(columns), (column) => this.generateColumnDefinitionFromSchema(column)),
|
|
204
204
|
...dropped(columns).flatMap((column) => this.tableDdl.dropColumn(tableName, column.name)),
|
|
205
205
|
...this.addIndexStatements(tableName, sides(diff.indexes, 'to')),
|
|
206
206
|
...(primaryKey?.to ? [this.generateAddPrimaryKeySql(tableName, primaryKey.to.columns, primaryKey.to.name)] : []),
|
|
@@ -79,8 +79,6 @@ export declare class MongoDialect extends AbstractDialect {
|
|
|
79
79
|
* Each end is one field matched against one `_id`, so both sides must be sole-keyed.
|
|
80
80
|
*/
|
|
81
81
|
private junctionOf;
|
|
82
|
-
/** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
|
|
83
|
-
private assertNoRaw;
|
|
84
82
|
/**
|
|
85
83
|
* A dotted key addresses an embedded path, whose root must still be a declared field - otherwise it
|
|
86
84
|
* is a typo (or an injected key) that would silently match nothing, the same guard the SQL dialects
|
|
@@ -34,6 +34,15 @@ export const mongoDialectFeatures = {
|
|
|
34
34
|
};
|
|
35
35
|
/** What `toWireId` converts: the hex spelling of an `ObjectId`, and nothing looser. */
|
|
36
36
|
const HEX_24 = /^[0-9a-f]{24}$/i;
|
|
37
|
+
/** `raw()` renders SQL, which MongoDB has no equivalent of: refused rather than emitted as `{}`. */
|
|
38
|
+
function rawRefusal(place) {
|
|
39
|
+
return new UqlUsageError(`raw() in ${place} is not supported on MongoDB`);
|
|
40
|
+
}
|
|
41
|
+
function assertNoRaw(value, place) {
|
|
42
|
+
if (value instanceof QueryRaw) {
|
|
43
|
+
throw rawRefusal(place);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
37
46
|
/** How a declared column type reads in a message: `Number`, `uuid` - not its whole source. */
|
|
38
47
|
function declaredTypeName(type) {
|
|
39
48
|
return typeof type === 'function' ? type.name : String(type);
|
|
@@ -170,14 +179,14 @@ export class MongoDialect extends AbstractDialect {
|
|
|
170
179
|
filter['$text'] = { $search: $value, ...($config && { $language: textLanguage($config) }) };
|
|
171
180
|
}
|
|
172
181
|
else if (meta.relations[key]) {
|
|
173
|
-
|
|
182
|
+
assertNoRaw(val, '$where');
|
|
174
183
|
if (!lookups) {
|
|
175
184
|
throw new UqlUsageError(`filtering by relation '${key}' is not supported here on MongoDB`);
|
|
176
185
|
}
|
|
177
186
|
this.appendRelationLookup(filter, meta, key, val, lookups);
|
|
178
187
|
}
|
|
179
188
|
else {
|
|
180
|
-
|
|
189
|
+
assertNoRaw(val, '$where');
|
|
181
190
|
this.assertKnownPathRoot(meta, key);
|
|
182
191
|
if (aggregateOf(meta.fields[key])) {
|
|
183
192
|
if (!lookups) {
|
|
@@ -219,7 +228,7 @@ export class MongoDialect extends AbstractDialect {
|
|
|
219
228
|
const { join, negate } = GROUP_OPS[key];
|
|
220
229
|
const parts = groupClauses(key, val)
|
|
221
230
|
.map((filterIt) => {
|
|
222
|
-
|
|
231
|
+
assertNoRaw(filterIt, '$where');
|
|
223
232
|
return this.renderFilter(entity, filterIt, lookups);
|
|
224
233
|
})
|
|
225
234
|
.filter((part) => Object.keys(part).length > 0);
|
|
@@ -310,12 +319,6 @@ export class MongoDialect extends AbstractDialect {
|
|
|
310
319
|
target: this.columnOf(throughMeta, targetColumn),
|
|
311
320
|
};
|
|
312
321
|
}
|
|
313
|
-
/** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
|
|
314
|
-
assertNoRaw(value) {
|
|
315
|
-
if (value instanceof QueryRaw) {
|
|
316
|
-
throw new UqlUsageError('raw() in $where is not supported on MongoDB');
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
322
|
/**
|
|
320
323
|
* A dotted key addresses an embedded path, whose root must still be a declared field - otherwise it
|
|
321
324
|
* is a typo (or an injected key) that would silently match nothing, the same guard the SQL dialects
|
|
@@ -424,7 +427,7 @@ export class MongoDialect extends AbstractDialect {
|
|
|
424
427
|
return {};
|
|
425
428
|
}
|
|
426
429
|
if (isSelectList(select)) {
|
|
427
|
-
throw
|
|
430
|
+
throw rawRefusal('$select');
|
|
428
431
|
}
|
|
429
432
|
const fields = normalizeScalarFieldSelection(meta, select, exclude);
|
|
430
433
|
// Projected by column, not by field key; `normalizeId` maps them back on the way out.
|
|
@@ -1004,6 +1007,7 @@ export class MongoDialect extends AbstractDialect {
|
|
|
1004
1007
|
for (const [key, value] of Object.entries(persistable)) {
|
|
1005
1008
|
if (isFieldUpdateOp(value)) {
|
|
1006
1009
|
const [op, operand] = fieldUpdateOf(key, value);
|
|
1010
|
+
assertNoRaw(operand, 'a write');
|
|
1007
1011
|
arithmetic[key] = { [MONGO_ARITHMETIC[op]]: [{ $ifNull: [`$${key}`, 0] }, { $literal: operand }] };
|
|
1008
1012
|
continue;
|
|
1009
1013
|
}
|
|
@@ -1100,7 +1104,9 @@ export class MongoDialect extends AbstractDialect {
|
|
|
1100
1104
|
if (key === idKey)
|
|
1101
1105
|
continue;
|
|
1102
1106
|
const field = meta.fields[key];
|
|
1103
|
-
|
|
1107
|
+
const value = it[key];
|
|
1108
|
+
assertNoRaw(value, 'a write');
|
|
1109
|
+
doc[this.resolveColumnName(key, field)] = field.references ? this.toWireId(value) : value;
|
|
1104
1110
|
}
|
|
1105
1111
|
return doc;
|
|
1106
1112
|
});
|
|
@@ -1220,9 +1226,7 @@ export class MongoDialect extends AbstractDialect {
|
|
|
1220
1226
|
if (isGroupOp(key)) {
|
|
1221
1227
|
const { join, negate } = GROUP_OPS[key];
|
|
1222
1228
|
const clauses = groupClauses(key, where[key]).map((clause) => {
|
|
1223
|
-
|
|
1224
|
-
throw new UqlUsageError('raw SQL is not supported in an aggregate $where on MongoDB');
|
|
1225
|
-
}
|
|
1229
|
+
assertNoRaw(clause, 'an aggregate $where');
|
|
1226
1230
|
return this.whereExpression(meta, clause, named);
|
|
1227
1231
|
});
|
|
1228
1232
|
return negate ? { $not: [{ [join]: clauses }] } : { [join]: clauses };
|
|
@@ -86,14 +86,14 @@ export class AbstractQuerierPool {
|
|
|
86
86
|
runScoped(context, fn) {
|
|
87
87
|
return context ? withContext(context, fn) : fn();
|
|
88
88
|
}
|
|
89
|
-
findOneById = (
|
|
90
|
-
findOne = (
|
|
91
|
-
findMany = (
|
|
89
|
+
findOneById = (...args) => this.withQuerier((querier) => querier.findOneById(...args));
|
|
90
|
+
findOne = (...args) => this.withQuerier((querier) => querier.findOne(...args));
|
|
91
|
+
findMany = (...args) => this.withQuerier((querier) => querier.findMany(...args));
|
|
92
92
|
/**
|
|
93
93
|
* The connection outlives the call: it is held until the iterator is drained or closed by a `break` or
|
|
94
94
|
* `throw`. Abandoning the iterator leaks it until GC, so consume it in a `for await`.
|
|
95
95
|
*/
|
|
96
|
-
findManyStream = (
|
|
96
|
+
findManyStream = (...args) => this.streamWithQuerier((querier) => querier.findManyStream(...args));
|
|
97
97
|
async *streamWithQuerier(read) {
|
|
98
98
|
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
99
99
|
try {
|
|
@@ -110,22 +110,22 @@ export class AbstractQuerierPool {
|
|
|
110
110
|
await result_1;
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
|
-
findManyAndCount = (
|
|
114
|
-
findManyPage = (
|
|
115
|
-
count = (
|
|
116
|
-
exists = (
|
|
117
|
-
aggregate = (
|
|
118
|
-
estimatedCount = (
|
|
119
|
-
insertOne = (
|
|
120
|
-
insertMany = (
|
|
121
|
-
updateOneById = (
|
|
122
|
-
updateMany = (
|
|
123
|
-
upsertOne = (
|
|
124
|
-
upsertMany = (
|
|
125
|
-
saveOne = (
|
|
126
|
-
saveMany = (
|
|
127
|
-
deleteOneById = (
|
|
128
|
-
deleteMany = (
|
|
129
|
-
restoreOneById = (
|
|
130
|
-
restoreMany = (
|
|
113
|
+
findManyAndCount = (...args) => this.withQuerier((querier) => querier.findManyAndCount(...args));
|
|
114
|
+
findManyPage = (...args) => this.withQuerier((querier) => querier.findManyPage(...args));
|
|
115
|
+
count = (...args) => this.withQuerier((querier) => querier.count(...args));
|
|
116
|
+
exists = (...args) => this.withQuerier((querier) => querier.exists(...args));
|
|
117
|
+
aggregate = (...args) => this.withQuerier((querier) => querier.aggregate(...args));
|
|
118
|
+
estimatedCount = (...args) => this.withQuerier((querier) => querier.estimatedCount(...args));
|
|
119
|
+
insertOne = (...args) => this.withQuerier((querier) => querier.insertOne(...args));
|
|
120
|
+
insertMany = (...args) => this.withQuerier((querier) => querier.insertMany(...args));
|
|
121
|
+
updateOneById = (...args) => this.withQuerier((querier) => querier.updateOneById(...args));
|
|
122
|
+
updateMany = (...args) => this.withQuerier((querier) => querier.updateMany(...args));
|
|
123
|
+
upsertOne = (...args) => this.withQuerier((querier) => querier.upsertOne(...args));
|
|
124
|
+
upsertMany = (...args) => this.withQuerier((querier) => querier.upsertMany(...args));
|
|
125
|
+
saveOne = (...args) => this.withQuerier((querier) => querier.saveOne(...args));
|
|
126
|
+
saveMany = (...args) => this.withQuerier((querier) => querier.saveMany(...args));
|
|
127
|
+
deleteOneById = (...args) => this.withQuerier((querier) => querier.deleteOneById(...args));
|
|
128
|
+
deleteMany = (...args) => this.withQuerier((querier) => querier.deleteMany(...args));
|
|
129
|
+
restoreOneById = (...args) => this.withQuerier((querier) => querier.restoreOneById(...args));
|
|
130
|
+
restoreMany = (...args) => this.withQuerier((querier) => querier.restoreMany(...args));
|
|
131
131
|
}
|
package/dist/schema/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
|
|
1
|
+
import type { Alteration, Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
|
|
2
2
|
import type { IndexFacet } from './indexDifferences.js';
|
|
3
3
|
/**
|
|
4
4
|
* Type categories universal across SQL dialects.
|
|
@@ -175,10 +175,7 @@ export type NodeChange<T, Altered = unknown> = {
|
|
|
175
175
|
} | {
|
|
176
176
|
readonly from: T;
|
|
177
177
|
readonly to?: undefined;
|
|
178
|
-
} | (
|
|
179
|
-
readonly from: T;
|
|
180
|
-
readonly to: T;
|
|
181
|
-
} & Altered);
|
|
178
|
+
} | (Alteration<T> & Altered);
|
|
182
179
|
/** A column to create, drop or alter; an alter lists in `changed` which parts of the column differ. */
|
|
183
180
|
export type ColumnDiff = NodeChange<ColumnNode, {
|
|
184
181
|
readonly changed: readonly ColumnFacet[];
|
package/dist/type/entity.d.ts
CHANGED
|
@@ -140,14 +140,14 @@ type JsonUpdateOpFor<V, T = UnwrapJson<NonNullable<V>>> = [T] extends [never] ?
|
|
|
140
140
|
/**
|
|
141
141
|
* A scalar field's update operator, as {@link JsonUpdateOp} is a JSON field's, computed in the statement:
|
|
142
142
|
* `$inc` adds, `$mul` multiplies, a NULL counting as 0 on every engine. One per field, since their order
|
|
143
|
-
* would change the result. A `bigint` steps by a `bigint`, exactly.
|
|
144
|
-
* @example `{ stock: { $inc: -1 } }`
|
|
143
|
+
* would change the result. A `bigint` steps by a `bigint`, exactly, and the step may be SQL of the field's type.
|
|
144
|
+
* @example `{ stock: { $inc: -1 } }`, `{ total: { $inc: newRow.amount } }`
|
|
145
145
|
*/
|
|
146
|
-
export type FieldUpdateOp<T
|
|
146
|
+
export type FieldUpdateOp<T = number | bigint | QueryRaw> = ExactlyOne<Record<'$inc' | '$mul', T>>;
|
|
147
147
|
/** The {@link FieldUpdateOp} a field takes: `never` on one it has no operator for, which is any but a number. */
|
|
148
|
-
type FieldUpdateOpFor<V> = [NonNullable<V>] extends [number] ? FieldUpdateOp<number
|
|
148
|
+
type FieldUpdateOpFor<V, Raw> = [NonNullable<V>] extends [number] ? FieldUpdateOp<number | RawFor<Raw, number>> : [NonNullable<V>] extends [bigint] ? FieldUpdateOp<bigint | RawFor<Raw, bigint>> : never;
|
|
149
149
|
/** What an update takes beyond the value: `null` to clear an optional member, `raw` SQL, and update operators. */
|
|
150
|
-
type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V>;
|
|
150
|
+
type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V, Raw>;
|
|
151
151
|
/**
|
|
152
152
|
* What a whole-record write persists: the fields and relations with their declared optionality, a
|
|
153
153
|
* related row as a caller writes one, and no methods. Two mapped types, since asking each key costs a
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -187,10 +187,7 @@ export type ColumnChange = Change<ColumnSchema> & {
|
|
|
187
187
|
readonly isBreaking?: boolean;
|
|
188
188
|
};
|
|
189
189
|
/** A name changed, `from` the database's `to` the entity's. */
|
|
190
|
-
export type Rename =
|
|
191
|
-
readonly from: string;
|
|
192
|
-
readonly to: string;
|
|
193
|
-
};
|
|
190
|
+
export type Rename = Alteration<string>;
|
|
194
191
|
/** Renamed columns by qualified table name. */
|
|
195
192
|
export type ColumnRenames = ReadonlyMap<string, readonly Rename[]>;
|
|
196
193
|
/**
|
|
@@ -202,6 +199,11 @@ export interface Change<T> {
|
|
|
202
199
|
readonly from?: T;
|
|
203
200
|
readonly to?: T;
|
|
204
201
|
}
|
|
202
|
+
/** A {@link Change} with both sides: the object altered in place. */
|
|
203
|
+
export type Alteration<T> = {
|
|
204
|
+
readonly from: T;
|
|
205
|
+
readonly to: T;
|
|
206
|
+
};
|
|
205
207
|
/** A primary key, whichever side it is read from: the entities, the database, or a diff between them. */
|
|
206
208
|
export interface PrimaryKeySchema {
|
|
207
209
|
/** Its columns **in order**, which is what a composite is: `(a, b)` is not `(b, a)`. */
|
|
@@ -233,10 +235,7 @@ export interface SchemaDiff {
|
|
|
233
235
|
* The table copied into a new one, which is how an engine that {@link DialectFeatures.rebuildsTables}
|
|
234
236
|
* applies the changes above. Its column renames are carried by the copy.
|
|
235
237
|
*/
|
|
236
|
-
readonly rebuild?:
|
|
237
|
-
readonly from: RebuiltTable;
|
|
238
|
-
readonly to: RebuiltTable;
|
|
239
|
-
};
|
|
238
|
+
readonly rebuild?: Alteration<RebuiltTable>;
|
|
240
239
|
}
|
|
241
240
|
/**
|
|
242
241
|
* What every sync entry point takes: `safe` keeps it additive, `drop` lets it remove a column, and
|
|
@@ -82,7 +82,7 @@ export declare function isFieldUpdateOp(value: unknown): value is FieldUpdateOp;
|
|
|
82
82
|
* The one operator a scalar field's update carries, and its operand. Naming both throws rather than
|
|
83
83
|
* reading one: their order would change the result, and an untyped payload is how both arrive.
|
|
84
84
|
*/
|
|
85
|
-
export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint];
|
|
85
|
+
export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint | QueryRaw];
|
|
86
86
|
/** Returns a `QueryOptions.filters` value with the built-in soft-delete filter disabled (used by hard delete). */
|
|
87
87
|
export declare function withoutSoftDeleteFilter(filters: QueryOptions['filters']): QueryOptions['filters'];
|
|
88
88
|
/**
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"homepage": "https://uql-orm.dev",
|
|
4
4
|
"description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Deno, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "0.93.
|
|
6
|
+
"version": "0.93.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=24"
|
|
@@ -135,25 +135,25 @@
|
|
|
135
135
|
"@electric-sql/pglite": "0.5.8",
|
|
136
136
|
"@electric-sql/pglite-pgvector": "0.0.9",
|
|
137
137
|
"@libsql/client": "^0.18.0",
|
|
138
|
-
"@neondatabase/serverless": "^1.
|
|
139
|
-
"@nestjs/common": "^12.1.
|
|
140
|
-
"@nestjs/core": "^12.1.
|
|
141
|
-
"@nestjs/testing": "^12.1.
|
|
142
|
-
"@tursodatabase/database": "^0.
|
|
138
|
+
"@neondatabase/serverless": "^1.2.0",
|
|
139
|
+
"@nestjs/common": "^12.1.2",
|
|
140
|
+
"@nestjs/core": "^12.1.2",
|
|
141
|
+
"@nestjs/testing": "^12.1.2",
|
|
142
|
+
"@tursodatabase/database": "^0.8.1",
|
|
143
143
|
"@tursodatabase/serverless": "^1.4.0",
|
|
144
144
|
"@types/better-sqlite3": "^9.6.0",
|
|
145
145
|
"@types/express": "^5.0.6",
|
|
146
146
|
"@types/mssql": "^12.3.0",
|
|
147
147
|
"@types/pg": "^8.23.1",
|
|
148
|
-
"@types/ws": "^8.18.
|
|
148
|
+
"@types/ws": "^8.18.2",
|
|
149
149
|
"better-sqlite3": "^13.0.3",
|
|
150
150
|
"express": "^5.2.1",
|
|
151
151
|
"mariadb": "^3.5.4",
|
|
152
152
|
"mongodb": "^7.7.0",
|
|
153
153
|
"mssql": "^12",
|
|
154
|
-
"mysql2": "^3.24.
|
|
155
|
-
"pg": "^8.23.
|
|
156
|
-
"pg-query-stream": "^4.17.
|
|
154
|
+
"mysql2": "^3.24.5",
|
|
155
|
+
"pg": "^8.23.1",
|
|
156
|
+
"pg-query-stream": "^4.17.1",
|
|
157
157
|
"rxjs": "^7.8.2",
|
|
158
158
|
"sqlite-vec": "^0.1.9",
|
|
159
159
|
"ws": "^8.22.0"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -10,11 +10,9 @@ description: >
|
|
|
10
10
|
|
|
11
11
|
# UQL
|
|
12
12
|
|
|
13
|
-
Entities are classes; a query is a JSON object checked key by key against the entity; the same query runs
|
|
14
|
-
on every database UQL supports. There is no schema file, no generated client, and no query builder.
|
|
13
|
+
Entities are classes; a query is a JSON object checked key by key against the entity; the same query runs on every database UQL supports. There is no schema file, no generated client, and no query builder.
|
|
15
14
|
|
|
16
|
-
The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Read the page for the task
|
|
17
|
-
before guessing an option: every page listed there is a `.md` URL.
|
|
15
|
+
The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Read the page for the task before guessing an option: every page listed there is a `.md` URL.
|
|
18
16
|
|
|
19
17
|
## Setup
|
|
20
18
|
|
|
@@ -22,9 +20,7 @@ before guessing an option: every page listed there is a `.md` URL.
|
|
|
22
20
|
npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/client, ...
|
|
23
21
|
```
|
|
24
22
|
|
|
25
|
-
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard:
|
|
26
|
-
never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`.
|
|
27
|
-
In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
23
|
+
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard: never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`. In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
28
24
|
|
|
29
25
|
```ts
|
|
30
26
|
// uql.config.ts
|
|
@@ -37,9 +33,7 @@ export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_U
|
|
|
37
33
|
export default { pool, entities: [User, Post] } satisfies Config;
|
|
38
34
|
```
|
|
39
35
|
|
|
40
|
-
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/maria`, `uql-orm/sqlite`,
|
|
41
|
-
`uql-orm/mongo`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`,
|
|
42
|
-
`uql-orm/bunSql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
36
|
+
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/maria`, `uql-orm/sqlite`, `uql-orm/mongo`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`, `uql-orm/bunSql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
43
37
|
|
|
44
38
|
## Entities
|
|
45
39
|
|
|
@@ -83,10 +77,8 @@ export class Post {
|
|
|
83
77
|
- Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
84
78
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
|
|
85
79
|
- `@Index((post) => [post.authorId], { where: { archived: { $ne: true } } })` states a partial index's filter as the predicate the query passes, never as `raw`: a planner matches the two by shape, so `raw` that means the same thing leaves the index unused.
|
|
86
|
-
- `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock:
|
|
87
|
-
|
|
88
|
-
- `@Field({ computed })` is a value the database produces, on a `readonly` property: SQL over the row, ``(u) => raw`${u.first} || ' ' || ${u.last}` ``, or a relation aggregate, `(order) => order.items.count()`.
|
|
89
|
-
`stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
|
|
80
|
+
- `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock: an update must carry the version it read (a compile error otherwise), and one against a row someone else moved on throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409). Its updates name one row by its id; save and upsert are refused.
|
|
81
|
+
- `@Field({ computed })` is a value the database produces, on a `readonly` property: SQL over the row, ``(u) => raw`${u.first} || ' ' || ${u.last}` ``, or a relation aggregate, `(order) => order.items.count()`. `stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
|
|
90
82
|
- `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires. `run(newRow, oldRow)` returns the body, written with `insertInto`, `upsertInto` (as `upsertOne` takes it), `updateTable`, `deleteFrom` and `refuse(message)` (fails the write), which are typed by the entity written and render on every engine; `deferred: true` fires an after trigger at commit, on Postgres only; anything else is `raw` SQL over the rows, per engine where they differ. A trigger's writes skip uql's fills and entity filters, soft delete included. MongoDB has none. Details, SQL Server's per-statement shape included: https://uql-orm.dev/entities/triggers.md
|
|
91
83
|
- `defineEntity` defines the same entity without decorators: https://uql-orm.dev/entities/imperative.md
|
|
92
84
|
|
|
@@ -106,48 +98,26 @@ const users = await pool.findMany(User, {
|
|
|
106
98
|
});
|
|
107
99
|
```
|
|
108
100
|
|
|
109
|
-
- The keys are `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`;
|
|
110
|
-
|
|
111
|
-
-
|
|
112
|
-
|
|
113
|
-
`NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
|
|
114
|
-
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000
|
|
115
|
-
costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass
|
|
116
|
-
`endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique
|
|
117
|
-
`nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages
|
|
118
|
-
correctly but cannot use an index.
|
|
119
|
-
- `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`,
|
|
120
|
-
`$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`,
|
|
121
|
-
`$isNotNull`. `$and`, `$or`, `$not` and `$nor` combine clauses.
|
|
101
|
+
- The keys are `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`; `$count: { posts: true }` tallies a to-many under `_count` without loading it.
|
|
102
|
+
- `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, and `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'` or `'descNullsLast'` to say where nulls land, which reads the same on every engine (emulated where there is no `NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
|
|
103
|
+
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass `endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique `nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages correctly but cannot use an index.
|
|
104
|
+
- `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`, `$isNotNull`. `$and`, `$or`, `$not` and `$nor` combine clauses.
|
|
122
105
|
- NULL compares the way the engine compares it: on SQL, `$ne`, `$nin`, `$not` and `$nor` leave out a NULL row, where MongoDB keeps it. Name NULL where you want it, `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`; ask for NULL with `{ col: null }` and its absence with `{ col: { $ne: null } }`.
|
|
123
|
-
- `$text: { $value }` in `$where` searches text on every engine with full-text search, through the entity's
|
|
124
|
-
|
|
125
|
-
relevance, and `{ $text: { $project: 'score' } }` also returns it, typed with `WithProjection<E, 'score'>`.
|
|
126
|
-
- A result is narrowed to what the query selected and populated: reading an unselected field is a compile error.
|
|
127
|
-
Name that shape with `QueryFindResult<User, 'id' | 'email'>` rather than widening the query.
|
|
106
|
+
- `$text: { $value }` in `$where` searches text on every engine with full-text search, through the entity's `@Index(..., { type: 'fulltext', config })`, whose columns may carry a `weight`. `$sort: { $text: 'desc' }` ranks by relevance, and `{ $text: { $project: 'score' } }` also returns it, typed with `WithProjection<E, 'score'>`.
|
|
107
|
+
- A result is narrowed to what the query selected and populated: reading an unselected field is a compile error. Name that shape with `QueryFindResult<User, 'id' | 'email'>` rather than widening the query.
|
|
128
108
|
- `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
|
|
129
|
-
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`,
|
|
130
|
-
|
|
131
|
-
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`,
|
|
132
|
-
`aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`,
|
|
133
|
-
`upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first.
|
|
109
|
+
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`, whose handler serves only the entities its required `include` names.
|
|
110
|
+
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first.
|
|
134
111
|
- `upsertOne(Entity, { email: true }, row, { update })`: a conflicting row takes `update`, an update's payload with its operators, instead of `row`; a new one inserts `row`. `{ update: {} }` leaves a conflicting row as it is: insert if absent.
|
|
135
112
|
- `updateMany` and `deleteMany` naming no rows - no `$where` holding a value (an `undefined` or an empty group holds none), no `$limit` - throw; `{ unfiltered: true }` means the whole table.
|
|
136
|
-
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row
|
|
140
|
-
someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and
|
|
141
|
-
refuse it.
|
|
142
|
-
- `queryErrorKind(err)` names any failure the same on every engine - `uniqueViolation`, `foreignKeyViolation`,
|
|
143
|
-
`notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security` - so catch by kind
|
|
144
|
-
rather than by a driver's code or an `instanceof`. Every error UQL raises itself is a `UqlError`.
|
|
113
|
+
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0, so a guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. On SQL the step may be a ref or `raw` of the field's type (`{ total: { $inc: newRow.amount } }` in a trigger). JSON fields take `$set`, `$unset`, `$push`, `$pull`.
|
|
114
|
+
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
|
|
115
|
+
- `queryErrorKind(err)` names any failure the same on every engine - `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security` - so catch by kind rather than by a driver's code or an `instanceof`. Every error UQL raises itself is a `UqlError`.
|
|
145
116
|
- `raw()` embeds SQL anywhere a value or field goes; `pool.all(sql, values)` runs a raw `SELECT`. A field read off `refs(Entity)` carries its type: on its own as a value it fits only a field of that type.
|
|
146
117
|
|
|
147
118
|
## Connections and transactions
|
|
148
119
|
|
|
149
|
-
Every method is on both the pool and a querier. A pool call acquires a connection for that call and releases it.
|
|
150
|
-
To run several operations on one connection, or atomically, hold a querier:
|
|
120
|
+
Every method is on both the pool and a querier. A pool call acquires a connection for that call and releases it. To run several operations on one connection, or atomically, hold a querier:
|
|
151
121
|
|
|
152
122
|
```ts
|
|
153
123
|
await pool.transaction(async (querier) => {
|
|
@@ -156,8 +126,7 @@ await pool.transaction(async (querier) => {
|
|
|
156
126
|
});
|
|
157
127
|
```
|
|
158
128
|
|
|
159
|
-
Inside the callback, call `querier`, never `pool`: a `pool` call runs on another connection, outside the
|
|
160
|
-
transaction. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
129
|
+
Inside the callback, call `querier`, never `pool`: a `pool` call runs on another connection, outside the transaction. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
161
130
|
|
|
162
131
|
## Migrations
|
|
163
132
|
|