uql-orm 0.99.0 → 0.100.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/LICENSE.md +22 -0
- package/README.md +1 -1
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +5 -5
- package/dist/bunSql/bunSql.util.js +2 -2
- package/dist/bunSql/bunSqlQuerier.js +0 -1
- package/dist/bunSql/bunSqlQuerierPool.js +1 -1
- package/dist/cockroachdb/cockroachDialect.js +1 -0
- package/dist/context/context.browser.d.ts +5 -0
- package/dist/context/context.browser.js +21 -11
- package/dist/context/context.d.ts +5 -0
- package/dist/context/context.js +8 -3
- package/dist/dialect/abstractDialect.js +4 -2
- package/dist/dialect/abstractSqlDialect.d.ts +5 -5
- package/dist/dialect/abstractSqlDialect.js +26 -18
- package/dist/dialect/aliases.d.ts +0 -2
- package/dist/dialect/aliases.js +0 -2
- package/dist/dialect/hydrateColumn.d.ts +3 -3
- package/dist/dialect/hydrateColumn.js +1 -0
- package/dist/dialect/index.js +0 -2
- package/dist/dialect/jsonSql.d.ts +2 -3
- package/dist/dialect/jsonSql.js +4 -6
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
- package/dist/dialect/mysqlLikeSqlDialect.js +5 -3
- package/dist/dialect/operators.d.ts +2 -3
- package/dist/dialect/operators.js +3 -4
- package/dist/dialect/pgLikeSqlDialect.js +12 -12
- package/dist/entity/decorator/members.d.ts +4 -12
- package/dist/entity/metadata/definition.js +8 -5
- package/dist/http/handler.d.ts +6 -6
- package/dist/http/handler.js +20 -5
- package/dist/index.d.ts +6 -5
- package/dist/index.js +6 -5
- package/dist/{maria → mariadb}/mariadbQuerier.js +1 -1
- package/dist/migrate/builder/columnBuilder.d.ts +3 -3
- package/dist/migrate/builder/columnBuilder.js +1 -1
- package/dist/migrate/builder/index.d.ts +0 -3
- package/dist/migrate/builder/index.js +0 -3
- package/dist/migrate/builder/migrationBuilder.d.ts +6 -6
- package/dist/migrate/builder/migrationBuilder.js +7 -7
- package/dist/migrate/builder/tableBuilder.d.ts +25 -25
- package/dist/migrate/builder/tableBuilder.js +5 -5
- package/dist/migrate/builder/types.d.ts +37 -37
- package/dist/migrate/cli-config.d.ts +11 -1
- package/dist/migrate/cli-config.js +20 -6
- package/dist/migrate/cli.js +9 -18
- package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
- package/dist/migrate/codegen/migrationFile.d.ts +7 -7
- package/dist/migrate/codegen/migrationFile.js +11 -12
- package/dist/migrate/ddl/indexCapabilities.d.ts +2 -0
- package/dist/migrate/ddl/indexCapabilities.js +6 -0
- package/dist/migrate/ddl/indexDdl.d.ts +8 -0
- package/dist/migrate/ddl/indexDdl.js +22 -6
- package/dist/migrate/generator/definitionToNode.d.ts +1 -1
- package/dist/migrate/generator/definitionToNode.js +1 -1
- package/dist/migrate/index.d.ts +1 -3
- package/dist/migrate/index.js +0 -3
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +11 -15
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +13 -15
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +5 -5
- package/dist/migrate/introspection/mssqlIntrospector.js +24 -28
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +5 -5
- package/dist/migrate/introspection/mysqlIntrospector.js +31 -37
- package/dist/migrate/introspection/postgresIntrospector.d.ts +13 -13
- package/dist/migrate/introspection/postgresIntrospector.js +35 -39
- package/dist/migrate/introspection/registry.js +1 -1
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +6 -4
- package/dist/migrate/introspection/sqliteIntrospector.js +15 -12
- package/dist/migrate/migrationLock.d.ts +38 -0
- package/dist/migrate/migrationLock.js +103 -0
- package/dist/migrate/migrationTarget.d.ts +6 -2
- package/dist/migrate/migrationTarget.js +30 -14
- package/dist/migrate/migrator.d.ts +39 -23
- package/dist/migrate/migrator.js +110 -74
- package/dist/migrate/schemaGenerator.d.ts +3 -1
- package/dist/migrate/schemaGenerator.js +14 -5
- package/dist/migrate/storage/databaseStorage.d.ts +28 -20
- package/dist/migrate/storage/databaseStorage.js +36 -54
- package/dist/migrate/storage/index.d.ts +0 -1
- package/dist/migrate/storage/index.js +0 -1
- package/dist/{mongo → mongodb}/index.d.ts +0 -1
- package/dist/{mongo → mongodb}/index.js +0 -1
- package/dist/{mongo → mongodb}/mongoCommand.d.ts +17 -1
- package/dist/{mongo → mongodb}/mongoCommand.js +15 -2
- package/dist/{mongo → mongodb}/mongoDialect.js +8 -12
- package/dist/{mongo → mongodb}/mongoIntrospector.js +12 -3
- package/dist/{mongo → mongodb}/mongoMigrationStorage.d.ts +5 -5
- package/dist/{mongo → mongodb}/mongoMigrationStorage.js +8 -12
- package/dist/{mongo → mongodb}/mongoQuerier.d.ts +3 -1
- package/dist/{mongo → mongodb}/mongoSchemaGenerator.d.ts +11 -1
- package/dist/{mongo → mongodb}/mongoSchemaGenerator.js +56 -11
- package/dist/{mongo → mongodb}/mongodbQuerier.d.ts +7 -18
- package/dist/{mongo → mongodb}/mongodbQuerier.js +44 -78
- package/dist/mssql/mssqlDialect.d.ts +6 -4
- package/dist/mssql/mssqlDialect.js +20 -10
- package/dist/mssql/mssqlQuerier.d.ts +2 -2
- package/dist/mssql/mssqlQuerier.js +3 -3
- package/dist/mssql/mssqlQuerierPool.d.ts +1 -1
- package/dist/mssql/mssqlQuerierPool.js +2 -2
- package/dist/mysql/mysql2Querier.js +1 -5
- package/dist/namingStrategy/defaultNamingStrategy.d.ts +0 -1
- package/dist/namingStrategy/defaultNamingStrategy.js +0 -3
- package/dist/pglite/pgliteDialect.d.ts +3 -0
- package/dist/pglite/pgliteDialect.js +3 -1
- package/dist/pglite/pgliteQuerier.d.ts +2 -0
- package/dist/pglite/pgliteQuerier.js +4 -0
- package/dist/postgres/postgresDialect.d.ts +3 -4
- package/dist/postgres/postgresDialect.js +5 -6
- package/dist/querier/abstractQuerier.d.ts +119 -36
- package/dist/querier/abstractQuerier.js +465 -161
- package/dist/querier/abstractQuerierPool.d.ts +5 -6
- package/dist/querier/abstractQuerierPool.js +20 -6
- package/dist/querier/abstractSqlQuerier.d.ts +15 -10
- package/dist/querier/abstractSqlQuerier.js +54 -47
- package/dist/querier/abstractSqlQuerierPool.d.ts +5 -3
- package/dist/querier/abstractSqlQuerierPool.js +7 -4
- package/dist/querier/transaction.d.ts +46 -0
- package/dist/querier/transaction.js +56 -0
- package/dist/schema/canonicalType.js +2 -2
- package/dist/schema/schemaASTDiffer.d.ts +11 -3
- package/dist/schema/schemaASTDiffer.js +20 -8
- package/dist/sqlite/nodeSqliteQuerierPool.d.ts +1 -1
- package/dist/sqlite/nodeSqliteQuerierPool.js +1 -1
- package/dist/sqlite/sqliteDialect.d.ts +1 -1
- package/dist/sqlite/sqliteDialect.js +3 -1
- package/dist/sqlite/sqliteQuerier.d.ts +2 -0
- package/dist/sqlite/sqliteQuerier.js +4 -0
- package/dist/sqlite/sqliteQuerierPool.d.ts +4 -4
- package/dist/sqlite/sqliteQuerierPool.js +1 -1
- package/dist/type/dialect.d.ts +16 -2
- package/dist/type/entity.d.ts +32 -32
- package/dist/type/migration.d.ts +10 -27
- package/dist/type/namingStrategy.d.ts +0 -4
- package/dist/type/querier.d.ts +18 -10
- package/dist/type/query.d.ts +7 -22
- package/dist/type/queryRaw.d.ts +11 -6
- package/dist/type/queryRaw.js +2 -3
- package/dist/type/universalQuerier.d.ts +26 -28
- package/dist/type/utility.d.ts +7 -2
- package/dist/util/dialect.util.d.ts +2 -2
- package/dist/util/dialect.util.js +4 -1
- package/dist/util/field.util.d.ts +12 -0
- package/dist/util/field.util.js +24 -0
- package/dist/util/hook.util.d.ts +3 -2
- package/dist/util/query.util.d.ts +5 -0
- package/dist/util/query.util.js +34 -1
- package/dist/util/raw.d.ts +8 -2
- package/dist/util/raw.js +22 -0
- package/dist/util/relationQuery.util.d.ts +2 -0
- package/dist/util/relationQuery.util.js +4 -0
- package/dist/util/sql.util.d.ts +0 -5
- package/dist/util/sql.util.js +3 -9
- package/dist/util/uqlError.d.ts +0 -6
- package/dist/util/uqlError.js +0 -5
- package/package.json +20 -26
- package/skills/uql-orm/SKILL.md +13 -10
- package/dist/migrate/storage/jsonStorage.d.ts +0 -14
- package/dist/migrate/storage/jsonStorage.js +0 -33
- /package/dist/{maria → mariadb}/index.d.ts +0 -0
- /package/dist/{maria → mariadb}/index.js +0 -0
- /package/dist/{maria → mariadb}/mariaDialect.d.ts +0 -0
- /package/dist/{maria → mariadb}/mariaDialect.js +0 -0
- /package/dist/{maria → mariadb}/mariadbQuerier.d.ts +0 -0
- /package/dist/{maria → mariadb}/mariadbQuerierPool.d.ts +0 -0
- /package/dist/{maria → mariadb}/mariadbQuerierPool.js +0 -0
- /package/dist/{mongo → mongodb}/mongoDialect.d.ts +0 -0
- /package/dist/{mongo → mongodb}/mongoIntrospector.d.ts +0 -0
- /package/dist/{mongo → mongodb}/mongoQuerier.js +0 -0
- /package/dist/{mongo → mongodb}/mongodbQuerierPool.d.ts +0 -0
- /package/dist/{mongo → mongodb}/mongodbQuerierPool.js +0 -0
- /package/dist/{mongo → mongodb}/textLanguage.d.ts +0 -0
- /package/dist/{mongo → mongodb}/textLanguage.js +0 -0
- /package/dist/{mongo → mongodb}/vectorDistance.d.ts +0 -0
- /package/dist/{mongo → mongodb}/vectorDistance.js +0 -0
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { type ColumnFamily, type EntityMeta, type FieldKey, type FieldMeta, type FieldOptions, type StampEvent, type RelationAggregateSpec } from '../type/index.js';
|
|
2
2
|
/** The family of a logical field type, or `undefined` where it names none. */
|
|
3
3
|
export declare function columnFamily(type: unknown): ColumnFamily | undefined;
|
|
4
|
+
/**
|
|
5
|
+
* Whether a field reads as an exact decimal's text: a DECIMAL column not declared `Number` or `BigInt`,
|
|
6
|
+
* which opt in to a JS number, rounding where it has to.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isExactDecimal(field: Pick<FieldOptions, 'type' | 'columnType'>): boolean;
|
|
4
9
|
/**
|
|
5
10
|
* Whether a field's column holds whole numbers: a declared integer type, or a `Number` or `BigInt`
|
|
6
11
|
* with no scale, which every engine here stores as BIGINT.
|
|
@@ -56,3 +61,10 @@ export declare function fieldKeys<E>(meta: EntityMeta<E>, pick: (field: FieldMet
|
|
|
56
61
|
* only when a query asks for it. Naming one in `$select` reads it, whatever the default.
|
|
57
62
|
*/
|
|
58
63
|
export declare function defaultReadKeys<E>(meta: EntityMeta<E>): FieldKey<E>[];
|
|
64
|
+
/**
|
|
65
|
+
* A JSON document key, refused unless it is an identifier: the one shape every engine's path reads
|
|
66
|
+
* unquoted, so a key never needs escaping into SQL and never reads as path syntax.
|
|
67
|
+
*/
|
|
68
|
+
export declare function jsonKey(key: string): string;
|
|
69
|
+
/** The keys of a dotted JSON path (`settings.theme`), each a {@link jsonKey}. */
|
|
70
|
+
export declare function jsonPathKeys(path: string): string[];
|
package/dist/util/field.util.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { COLUMN_TYPES, RelationAggregate, } from '../type/index.js';
|
|
2
2
|
import { definedEntries, getKeys } from './object.util.js';
|
|
3
|
+
import { UqlUsageError } from './uqlError.js';
|
|
3
4
|
// Constructors and type strings in one map: a logical type is either, and every caller asks the same
|
|
4
5
|
// question of both.
|
|
5
6
|
const FAMILY_OF = new Map([
|
|
@@ -14,6 +15,14 @@ const FAMILY_OF = new Map([
|
|
|
14
15
|
export function columnFamily(type) {
|
|
15
16
|
return FAMILY_OF.get(typeof type === 'string' ? type.toLowerCase() : type);
|
|
16
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* Whether a field reads as an exact decimal's text: a DECIMAL column not declared `Number` or `BigInt`,
|
|
20
|
+
* which opt in to a JS number, rounding where it has to.
|
|
21
|
+
*/
|
|
22
|
+
export function isExactDecimal(field) {
|
|
23
|
+
const column = field.columnType ?? field.type;
|
|
24
|
+
return field.type !== Number && field.type !== BigInt && (column === 'decimal' || column === 'numeric');
|
|
25
|
+
}
|
|
17
26
|
/** The numeric column types that hold whole numbers. */
|
|
18
27
|
const INTEGER_COLUMN_TYPES = new Set([
|
|
19
28
|
'int',
|
|
@@ -114,3 +123,18 @@ export function fieldKeys(meta, pick) {
|
|
|
114
123
|
export function defaultReadKeys(meta) {
|
|
115
124
|
return fieldKeys(meta, (field) => field.eager ?? !aggregateOf(field));
|
|
116
125
|
}
|
|
126
|
+
const JSON_KEY = /^[\p{L}_][\p{L}\p{N}_]*$/u;
|
|
127
|
+
/**
|
|
128
|
+
* A JSON document key, refused unless it is an identifier: the one shape every engine's path reads
|
|
129
|
+
* unquoted, so a key never needs escaping into SQL and never reads as path syntax.
|
|
130
|
+
*/
|
|
131
|
+
export function jsonKey(key) {
|
|
132
|
+
if (!JSON_KEY.test(key)) {
|
|
133
|
+
throw new UqlUsageError(`'${key}' is not a JSON key: name one with letters, digits and '_', not starting with a digit`);
|
|
134
|
+
}
|
|
135
|
+
return key;
|
|
136
|
+
}
|
|
137
|
+
/** The keys of a dotted JSON path (`settings.theme`), each a {@link jsonKey}. */
|
|
138
|
+
export function jsonPathKeys(path) {
|
|
139
|
+
return path.split('.').map(jsonKey);
|
|
140
|
+
}
|
package/dist/util/hook.util.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { HookEvent, Querier, Type } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
3
|
+
* What a lifecycle hook is handed: the querier, to write in the same transaction, and `onCommit`, for what
|
|
4
|
+
* must wait until that transaction commits.
|
|
5
5
|
*/
|
|
6
6
|
export type HookContext = {
|
|
7
7
|
readonly querier: Querier;
|
|
8
|
+
readonly onCommit: Querier['onCommit'];
|
|
8
9
|
};
|
|
9
10
|
/**
|
|
10
11
|
* Run all registered hooks for the given event on each payload.
|
|
@@ -30,6 +30,11 @@ export declare function whereIds<E>(meta: EntityMeta<E>, ids: EntityId<E> | Enti
|
|
|
30
30
|
* and a scalar read as a map has no keys, so the statement would match every row.
|
|
31
31
|
*/
|
|
32
32
|
export declare function assertWhere<E>(meta: EntityMeta<E>, where: unknown): void;
|
|
33
|
+
/**
|
|
34
|
+
* Throws on an `undefined` anywhere in a filter map (`$where`, `$having`), which would otherwise render
|
|
35
|
+
* as no condition at all: `{ email: maybeEmail }` reading any row. `what` names the map in the error.
|
|
36
|
+
*/
|
|
37
|
+
export declare function assertNoUndefined(map: object, what: string): void;
|
|
33
38
|
/** A parsed `$sort` direction: whether it is descending, and where it puts nulls if it says. */
|
|
34
39
|
export type SortDirection = {
|
|
35
40
|
readonly desc: boolean;
|
package/dist/util/query.util.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { soleIdOf } from '../entity/metadata/definition.js';
|
|
2
|
-
import { entityName, isScalarId, isWhereMap } from './object.util.js';
|
|
2
|
+
import { entityName, isRecord, isScalarId, isWhereMap } from './object.util.js';
|
|
3
3
|
import { UqlUsageError } from './uqlError.js';
|
|
4
4
|
/**
|
|
5
5
|
* Maps each of `keys` to `true`, the shape of a `$select` or conflict paths. This and the builders below hold
|
|
@@ -60,6 +60,39 @@ export function assertWhere(meta, where) {
|
|
|
60
60
|
throw new UqlUsageError(`$where on '${entityName(meta)}' must be a map of conditions, such as { id: 1 }`);
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Throws on an `undefined` anywhere in a filter map (`$where`, `$having`), which would otherwise render
|
|
65
|
+
* as no condition at all: `{ email: maybeEmail }` reading any row. `what` names the map in the error.
|
|
66
|
+
*/
|
|
67
|
+
export function assertNoUndefined(map, what) {
|
|
68
|
+
const path = undefinedPath(map, []);
|
|
69
|
+
if (path) {
|
|
70
|
+
throw new UqlUsageError(`${what} holds undefined at '${path.join('.')}': leave the key out not to filter by it, or name null`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** The path to the first `undefined` in a plain object or array, read depth first. */
|
|
74
|
+
function undefinedPath(value, path) {
|
|
75
|
+
if (value === undefined) {
|
|
76
|
+
return path;
|
|
77
|
+
}
|
|
78
|
+
if (!Array.isArray(value) && !isPlainObject(value)) {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
for (const [key, item] of Object.entries(value)) {
|
|
82
|
+
const found = undefinedPath(item, [...path, key]);
|
|
83
|
+
if (found) {
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
function isPlainObject(value) {
|
|
90
|
+
if (!isRecord(value)) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
const proto = Object.getPrototypeOf(value);
|
|
94
|
+
return proto === Object.prototype || proto === null;
|
|
95
|
+
}
|
|
63
96
|
const SORT_DIRECTIONS = new Map([
|
|
64
97
|
[1, { desc: false }],
|
|
65
98
|
['asc', { desc: false }],
|
package/dist/util/raw.d.ts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
import { type EntitySql, type EntityWhere, type EntityWhereMeta, QueryRaw, type QueryRawFn, type ComputedRefs, type RefMap, type SqlValueName, type TriggerRowName, type Type } from '../type/index.js';
|
|
1
|
+
import { type EntitySql, type EntityWhere, type EntityWhereMeta, QueryRaw, type QueryRawFn, type ComputedRefs, type RefMap, type RawValue, type SqlStatement, type SqlValueName, type TriggerRowName, type Type } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Raw SQL, where an interpolated value binds, a `refs` field renders its column, and a `raw` renders
|
|
4
4
|
* in place: `raw`GREATEST(0, ${user.credits} - ${amount})``. A callback writes whatever it writes, so
|
|
5
5
|
* never build one from user input. See the Raw SQL guide.
|
|
6
6
|
*/
|
|
7
|
-
export declare function raw(strings: TemplateStringsArray, ...values: readonly
|
|
7
|
+
export declare function raw(strings: TemplateStringsArray, ...values: readonly RawValue[]): QueryRaw;
|
|
8
|
+
export declare namespace raw {
|
|
9
|
+
var join: (parts: readonly QueryRaw[], separator?: string) => QueryRaw;
|
|
10
|
+
var text: (sql: string) => QueryRaw;
|
|
11
|
+
}
|
|
8
12
|
export declare function raw(value: QueryRawFn): QueryRaw;
|
|
13
|
+
/** The statement `all` or `run` was handed: a tagged template's, or a `raw` built apart. */
|
|
14
|
+
export declare function statementOf([sql, ...values]: SqlStatement): QueryRaw;
|
|
9
15
|
/**
|
|
10
16
|
* The SQL of a `raw` that names a constant, for a DDL clause with no dialect to render against and
|
|
11
17
|
* nowhere to bind a value; `undefined` where it interpolates and so needs one.
|
package/dist/util/raw.js
CHANGED
|
@@ -7,6 +7,9 @@ export function raw(value, ...rest) {
|
|
|
7
7
|
if (!isTemplateStrings(value)) {
|
|
8
8
|
return new QueryRaw(value);
|
|
9
9
|
}
|
|
10
|
+
if (rest.some((value) => value === undefined)) {
|
|
11
|
+
throw new UqlUsageError('a raw template interpolated undefined, which binds nothing: leave it out, or write null');
|
|
12
|
+
}
|
|
10
13
|
// Writes joined by whitespace alone are still only writes, so a set-based trigger narrows each one.
|
|
11
14
|
const writes = rest.length > 0 && rest.every((v) => v instanceof TriggerWriteRaw) && value.every((part) => !part.trim());
|
|
12
15
|
return new (writes ? TriggerWriteRaw : QueryRaw)((opts) => {
|
|
@@ -23,6 +26,25 @@ export function raw(value, ...rest) {
|
|
|
23
26
|
});
|
|
24
27
|
}, undefined, rest.length === 0 ? value[0] : undefined);
|
|
25
28
|
}
|
|
29
|
+
/** `parts` one after another, `separator` between each, every part binding its own values: `raw.join(conditions, ' AND ')`. */
|
|
30
|
+
raw.join = function join(parts, separator = ', ') {
|
|
31
|
+
return new QueryRaw((opts) => {
|
|
32
|
+
parts.forEach((part, index) => {
|
|
33
|
+
if (index) {
|
|
34
|
+
opts.ctx.append(separator);
|
|
35
|
+
}
|
|
36
|
+
part.render(opts);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
};
|
|
40
|
+
/** The statement `all` or `run` was handed: a tagged template's, or a `raw` built apart. */
|
|
41
|
+
export function statementOf([sql, ...values]) {
|
|
42
|
+
return sql instanceof QueryRaw ? sql : raw(sql, ...values);
|
|
43
|
+
}
|
|
44
|
+
/** SQL held in a string, run as written, binding nothing: for trusted text only, never built from user input. */
|
|
45
|
+
raw.text = function text(sql) {
|
|
46
|
+
return new QueryRaw(() => sql, undefined, sql);
|
|
47
|
+
};
|
|
26
48
|
/**
|
|
27
49
|
* The SQL of a `raw` that names a constant, for a DDL clause with no dialect to render against and
|
|
28
50
|
* nowhere to bind a value; `undefined` where it interpolates and so needs one.
|
|
@@ -9,6 +9,8 @@ export type RelationRequestSummary<E> = {
|
|
|
9
9
|
* the one field it reads, so it answers for a relation being declared as well as for a resolved one.
|
|
10
10
|
*/
|
|
11
11
|
export declare function isToManyRelation(relation: Pick<RelationMeta, 'cardinality'>): boolean;
|
|
12
|
+
/** Whether the entity declaring the relation holds its foreign key: an owning to-one. */
|
|
13
|
+
export declare function holdsForeignKey(relation: Pick<RelationMeta, 'cardinality' | 'mappedBy'>): boolean;
|
|
12
14
|
/** One column of a parent's key, paired with the column matching it on the table being joined. */
|
|
13
15
|
export type ParentJoin = {
|
|
14
16
|
readonly parent: string;
|
|
@@ -14,6 +14,10 @@ const NOTHING_REQUESTED = Object.freeze({
|
|
|
14
14
|
export function isToManyRelation(relation) {
|
|
15
15
|
return relation.cardinality === '1m' || relation.cardinality === 'mm';
|
|
16
16
|
}
|
|
17
|
+
/** Whether the entity declaring the relation holds its foreign key: an owning to-one. */
|
|
18
|
+
export function holdsForeignKey(relation) {
|
|
19
|
+
return !relation.mappedBy && !isToManyRelation(relation);
|
|
20
|
+
}
|
|
17
21
|
/**
|
|
18
22
|
* How a relation joins its parent, one pair per key: `parent` a column of the parent's table, `joined` the
|
|
19
23
|
* matching one on the table the relation reads, a junction's or the child's.
|
package/dist/util/sql.util.d.ts
CHANGED
|
@@ -62,11 +62,6 @@ export interface BuildUpdateResultPayload {
|
|
|
62
62
|
* server (e.g. Galera, group replication) may set `auto_increment_increment` higher.
|
|
63
63
|
*/
|
|
64
64
|
insertIdIncrement?: number;
|
|
65
|
-
/**
|
|
66
|
-
* Driver-specific upsert detection from the result header.
|
|
67
|
-
* MySQL/MariaDB `ON DUPLICATE KEY UPDATE` convention: 1 = insert, 2 = update, 0 = no-op.
|
|
68
|
-
*/
|
|
69
|
-
upsertStatus?: number;
|
|
70
65
|
}
|
|
71
66
|
/**
|
|
72
67
|
* A driver's result as a {@link QueryUpdateResult}: `RETURNING` rows name their id `id`; a MySQL header's
|
package/dist/util/sql.util.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { OWNED_PREFIX
|
|
1
|
+
import { OWNED_PREFIX } from '../dialect/aliases.js';
|
|
2
2
|
import { hasKeys, isRecord } from './object.util.js';
|
|
3
3
|
import { fnv1a } from './string.util.js';
|
|
4
4
|
/** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
|
|
@@ -138,7 +138,7 @@ export function escapeSqlId(val, escapeIdChar = '`', forbidQualified, addDot) {
|
|
|
138
138
|
* (`innodb_autoinc_lock_mode` 0 or 1).
|
|
139
139
|
*/
|
|
140
140
|
export function buildUpdateResult(payload) {
|
|
141
|
-
const { rows, id, insertIdSource
|
|
141
|
+
const { rows, id, insertIdSource } = payload;
|
|
142
142
|
const changes = payload.changes ?? rows?.length ?? 0;
|
|
143
143
|
const stride = payload.insertIdIncrement && payload.insertIdIncrement > 0 ? payload.insertIdIncrement : 1;
|
|
144
144
|
// Ids from `RETURNING` are exact; otherwise from the header's first id onward, which assumes `changes`
|
|
@@ -156,13 +156,7 @@ export function buildUpdateResult(payload) {
|
|
|
156
156
|
ids = sequentialIds(id, changes, stride);
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
|
-
|
|
160
|
-
// which is unreliable under `RETURNING`, so those dialects report nothing.
|
|
161
|
-
const created = (rows?.length === 1 ? rows[0]?.[UPSERT_CREATED_ALIAS] : undefined) ??
|
|
162
|
-
(insertIdSource !== 'returning' && typeof upsertStatus === 'number' && upsertStatus >= 0 && upsertStatus <= 2
|
|
163
|
-
? upsertStatus === 1
|
|
164
|
-
: undefined);
|
|
165
|
-
return { changes, ids, firstId: ids?.[0], created };
|
|
159
|
+
return { changes, ids };
|
|
166
160
|
}
|
|
167
161
|
/** Build `count` ids starting at `first`, incrementing by `step` (bigint- and number-safe). */
|
|
168
162
|
function sequentialIds(first, count, step) {
|
package/dist/util/uqlError.d.ts
CHANGED
|
@@ -31,12 +31,6 @@ export declare class UqlSecurityError extends UqlError {
|
|
|
31
31
|
}
|
|
32
32
|
/** What a value is, for a refusal naming what `/http` handed over instead of what the types require. */
|
|
33
33
|
export declare function kindOf(value: unknown): string;
|
|
34
|
-
/**
|
|
35
|
-
* @deprecated since 0.77.1 - use {@link UqlUsageError}, which every misuse throws, lock or not. The
|
|
36
|
-
* same class under both names, so an existing `instanceof` keeps working.
|
|
37
|
-
*/
|
|
38
|
-
export declare const UqlLockUsageError: typeof UqlUsageError;
|
|
39
|
-
export type UqlLockUsageError = UqlUsageError;
|
|
40
34
|
/**
|
|
41
35
|
* Thrown when an update's `@Field({ version })` no longer matches the row: another writer moved it on,
|
|
42
36
|
* or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`
|
package/dist/util/uqlError.js
CHANGED
|
@@ -24,11 +24,6 @@ export class UqlSecurityError extends UqlError {
|
|
|
24
24
|
export function kindOf(value) {
|
|
25
25
|
return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
26
26
|
}
|
|
27
|
-
/**
|
|
28
|
-
* @deprecated since 0.77.1 - use {@link UqlUsageError}, which every misuse throws, lock or not. The
|
|
29
|
-
* same class under both names, so an existing `instanceof` keeps working.
|
|
30
|
-
*/
|
|
31
|
-
export const UqlLockUsageError = UqlUsageError;
|
|
32
27
|
/**
|
|
33
28
|
* Thrown when an update's `@Field({ version })` no longer matches the row: another writer moved it on,
|
|
34
29
|
* or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`
|
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.
|
|
6
|
+
"version": "0.100.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=24"
|
|
@@ -19,19 +19,13 @@
|
|
|
19
19
|
},
|
|
20
20
|
"exports": {
|
|
21
21
|
".": "./dist/index.js",
|
|
22
|
-
"./dialect": "./dist/dialect/index.js",
|
|
23
|
-
"./entity": "./dist/entity/index.js",
|
|
24
|
-
"./querier": "./dist/querier/index.js",
|
|
25
|
-
"./type": "./dist/type/index.js",
|
|
26
|
-
"./util": "./dist/util/index.js",
|
|
27
|
-
"./namingStrategy": "./dist/namingStrategy/index.js",
|
|
28
22
|
"./migrate": "./dist/migrate/index.js",
|
|
29
23
|
"./mysql": "./dist/mysql/index.js",
|
|
30
24
|
"./postgres": "./dist/postgres/index.js",
|
|
31
25
|
"./cockroachdb": "./dist/cockroachdb/index.js",
|
|
32
|
-
"./
|
|
26
|
+
"./mariadb": "./dist/mariadb/index.js",
|
|
33
27
|
"./sqlite": "./dist/sqlite/index.js",
|
|
34
|
-
"./
|
|
28
|
+
"./mongodb": "./dist/mongodb/index.js",
|
|
35
29
|
"./http": "./dist/http/index.js",
|
|
36
30
|
"./express": "./dist/express/index.js",
|
|
37
31
|
"./nestjs": "./dist/nestjs/index.js",
|
|
@@ -46,7 +40,7 @@
|
|
|
46
40
|
"./neon": "./dist/neon/index.js",
|
|
47
41
|
"./pglite": "./dist/pglite/index.js",
|
|
48
42
|
"./d1": "./dist/d1/index.js",
|
|
49
|
-
"./
|
|
43
|
+
"./bun-sql": "./dist/bunSql/index.js",
|
|
50
44
|
"./package.json": "./package.json",
|
|
51
45
|
"./mssql": "./dist/mssql/index.js"
|
|
52
46
|
},
|
|
@@ -64,22 +58,22 @@
|
|
|
64
58
|
"clean": "rimraf dist .tsconfig.tsbuildinfo"
|
|
65
59
|
},
|
|
66
60
|
"peerDependencies": {
|
|
67
|
-
"@electric-sql/pglite": ">=0.5.0",
|
|
68
|
-
"@libsql/client": ">=0.6.0",
|
|
69
|
-
"@neondatabase/serverless": ">=0.9.0",
|
|
70
|
-
"@nestjs/common": ">=10.0.0",
|
|
71
|
-
"@nestjs/core": ">=10.0.0",
|
|
72
|
-
"@tursodatabase/database": ">=0.8.2",
|
|
73
|
-
"@tursodatabase/serverless": ">=1.4.1",
|
|
74
|
-
"better-sqlite3": ">=9.0.0",
|
|
75
|
-
"express": ">=5.0.0",
|
|
76
|
-
"mariadb": ">=3.0.0",
|
|
77
|
-
"mongodb": ">=6.0.0",
|
|
78
|
-
"mssql": ">=11.0.0",
|
|
79
|
-
"mysql2": ">=3.0.0",
|
|
80
|
-
"pg": ">=8.0.0",
|
|
81
|
-
"pg-query-stream": ">=4.0.0",
|
|
82
|
-
"rxjs": ">=7.0.0"
|
|
61
|
+
"@electric-sql/pglite": ">=0.5.0 <0.6",
|
|
62
|
+
"@libsql/client": ">=0.6.0 <0.19",
|
|
63
|
+
"@neondatabase/serverless": ">=0.9.0 <2",
|
|
64
|
+
"@nestjs/common": ">=10.0.0 <13",
|
|
65
|
+
"@nestjs/core": ">=10.0.0 <13",
|
|
66
|
+
"@tursodatabase/database": ">=0.8.2 <0.9",
|
|
67
|
+
"@tursodatabase/serverless": ">=1.4.1 <2",
|
|
68
|
+
"better-sqlite3": ">=9.0.0 <14",
|
|
69
|
+
"express": ">=5.0.0 <6",
|
|
70
|
+
"mariadb": ">=3.0.0 <4",
|
|
71
|
+
"mongodb": ">=6.0.0 <8",
|
|
72
|
+
"mssql": ">=11.0.0 <13",
|
|
73
|
+
"mysql2": ">=3.0.0 <4",
|
|
74
|
+
"pg": ">=8.0.0 <9",
|
|
75
|
+
"pg-query-stream": ">=4.0.0 <5",
|
|
76
|
+
"rxjs": ">=7.0.0 <8"
|
|
83
77
|
},
|
|
84
78
|
"peerDependenciesMeta": {
|
|
85
79
|
"@electric-sql/pglite": {
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -20,7 +20,7 @@ The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Re
|
|
|
20
20
|
npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/client, ...
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.
|
|
23
|
+
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.7+. 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`.
|
|
24
24
|
|
|
25
25
|
Node's type stripping runs no decorators: on Node, add `tsx` (`npm i -D tsx`), which `uql-migrate` imports `uql.config.ts` through. Next.js compiles TC39 decorators only through a `babel.config.json` with `@babel/plugin-proposal-decorators` at `version: '2023-11'`. A bundle that minifies class names (Next's server build, or any bundler's `minify`) needs `@Entity({ name: 'todo' })`: a table name is the class name otherwise.
|
|
26
26
|
|
|
@@ -35,7 +35,7 @@ export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_U
|
|
|
35
35
|
export default { pool, entities: [User, Post] } satisfies Config;
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/
|
|
38
|
+
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/mariadb`, `uql-orm/sqlite`, `uql-orm/mongodb`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`, `uql-orm/bun-sql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
39
39
|
|
|
40
40
|
## Entities
|
|
41
41
|
|
|
@@ -70,7 +70,7 @@ export class Post {
|
|
|
70
70
|
}
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
-
- Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references` instead and inherits the target key's type. A `Date` is an instant, stored in UTC to the millisecond on every engine; `precision` sets other fractional digits.
|
|
73
|
+
- Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references` instead and inherits the target key's type. A `Date` is an instant, stored in UTC to the millisecond on every engine; `precision` sets other fractional digits. A `'decimal'` is exact text (`price?: string | null`); `type: Number` with `precision`/`scale` opts in to a rounding JS number. A JSON column of no fixed shape is a bare `Json`.
|
|
74
74
|
- A column is nullable unless it says `nullable: false`, and its property must admit `null` to match: `title?: string | null`. A property typed without `| null` on a nullable column is a compile error.
|
|
75
75
|
- Declare a `nullable: false` column `!` (`email!: string`): reads have it and inserts must name it, except a single-column key and a `version`, which uql fills. Declare `?` whatever an insert may leave out: a nullable, `onInsert`, `defaultValue`, `eager: false` or `computed` field, and relations.
|
|
76
76
|
- An engine's own column type is a `raw` constant, ``columnType: raw`tsvector` ``, rendered verbatim and carrying its own `length`/`precision`: never a bare string.
|
|
@@ -78,6 +78,7 @@ export class Post {
|
|
|
78
78
|
- `currentTimestamp` is the database clock, UTC to the millisecond on every engine, where a raw `CURRENT_TIMESTAMP` is not on SQLite, MySQL or SQL Server. Use it for a default, a stamp, `onUpdate` or `$where`.
|
|
79
79
|
- Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
80
80
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
|
|
81
|
+
- `cascade: true` makes writes reach a relation's rows, in one transaction. A to-one holding the key takes `'persist'` only: its target is written first, and `{ id }` links an existing one. An update replaces a to-many's rows and a many-to-many's links: the listed ones are saved or kept, the rest removed.
|
|
81
82
|
- `@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.
|
|
82
83
|
- `@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.
|
|
83
84
|
- `@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.
|
|
@@ -104,18 +105,20 @@ const users = await pool.findMany(User, {
|
|
|
104
105
|
- `$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.
|
|
105
106
|
- `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.
|
|
106
107
|
- `$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.
|
|
108
|
+
- An `undefined` anywhere in `$where` throws instead of filtering by nothing: leave the key out not to filter by it (`...(email && { email })`), or name `null`.
|
|
107
109
|
- 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 } }`.
|
|
108
110
|
- `$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'>`.
|
|
109
111
|
- 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.
|
|
110
112
|
- `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
|
|
111
113
|
- 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.
|
|
112
114
|
- 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.
|
|
113
|
-
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update's payload with its operators (`{ uses: { $inc: 1 } }`), instead of `row`; a new one inserts `row`. An empty `{}` leaves a conflicting row as it is: insert if absent. Cascaded relations write on either branch, a found row's replaced, as `updateMany` does.
|
|
114
|
-
-
|
|
115
|
+
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update's payload with its operators (`{ uses: { $inc: 1 } }`), instead of `row`; a new one inserts `row`. An empty `{}` leaves a conflicting row as it is: insert if absent. Cascaded relations write on either branch, a found row's replaced, as `updateMany` does. It resolves to the row's id.
|
|
116
|
+
- Every write takes `{ returning: { id: true, createdAt: true } }` as its last argument and then resolves to those rows (an update or delete by id: the row or `undefined`), read back in the same transaction; without it, inserts, saves and upserts resolve to ids, updates and deletes to a count.
|
|
117
|
+
- `updateMany` and `deleteMany` naming no rows - no `$where` holding a value (an empty group holds none), no `$limit` - throw; `{ unfiltered: true }` means the whole table.
|
|
115
118
|
- 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`.
|
|
116
119
|
- `$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.
|
|
117
120
|
- `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`.
|
|
118
|
-
- `
|
|
121
|
+
- ``pool.all`SELECT ... WHERE id = ${id}` `` runs a `SELECT` and ``pool.run`...` `` a write: both are tags, each interpolated value bound: a scalar, `null` or a list of them, never `undefined` or a plain object (bind `JSON.stringify(doc)`). `raw` builds a fragment to embed anywhere a value or field goes, or to compose a statement, and `raw.join(fragments, ' AND ')` joins them. `raw.text(sql)` runs trusted SQL held in a string, binding nothing: never build it from user input. Migrations write ``querier.run`CREATE TABLE ...` ``. `raw` is a tag, so ``raw(`...`)`` does not compile. A field read off `refs(Entity)` carries its type: on its own as a value it fits only a field of that type.
|
|
119
122
|
|
|
120
123
|
## Connections and transactions
|
|
121
124
|
|
|
@@ -128,7 +131,7 @@ await pool.transaction(async (querier) => {
|
|
|
128
131
|
});
|
|
129
132
|
```
|
|
130
133
|
|
|
131
|
-
|
|
134
|
+
The callback commits when it returns and rolls back when it throws; `beginTransaction` / `commitTransaction` / `rollbackTransaction` are for a transaction that opens in one place and ends in another. Inside the callback, a `pool` call runs on the callback's querier, so it is part of the transaction. A `transaction()` inside another is a savepoint, whose failure undoes its own writes alone (MongoDB, with none, refuses it). A transaction holds its connection: a statement from outside its callback waits for it. `querier.onCommit(fn)` (or a hook's `onCommit`) runs `fn` after the outermost commit, never on a rollback: use it for mails and queued jobs. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
132
135
|
|
|
133
136
|
A `findManyStream` holds its querier until the loop ends, which refuses any other statement meanwhile: inside the loop, run them on another connection; inside a transaction, or on SQLite and PGlite (one shared connection), run them after the loop. That includes an `@AfterLoad` querying through its `querier` on a streamed row. A statement binding more values than the engine takes (100 on D1, 2098 on SQL Server) is refused too: split a long `$in`.
|
|
134
137
|
|
|
@@ -137,13 +140,13 @@ A `findManyStream` holds its querier until the loop ends, which refuses any othe
|
|
|
137
140
|
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|
|
138
141
|
|
|
139
142
|
- `sync` applies what the entities imply (development only).
|
|
140
|
-
- `generate:entities` writes the diff as a migration file to review. It renames a column
|
|
141
|
-
- `up` and `down` apply and revert migrations.
|
|
143
|
+
- `generate:entities` writes the diff as a migration file to review. It renames a column a naming strategy spells otherwise (`firstName` to `first_name`); any other renamed column is a drop and an add it warns about, with the `renameColumn(table, from, to)` to write instead. It refuses a required column with no default on a table holding rows.
|
|
144
|
+
- `up` and `down` apply and revert migrations, each in its own transaction, holding a lock so concurrent instances run each migration once. From code, `await new Migrator(pool, { migrationsPath }).up()` before the app starts: it rejects with the first failing migration's error, the ones before it applied. `down()` reverts the last one; `down({ step: Infinity })` every one.
|
|
142
145
|
- `generate:from-db` writes entity classes from an existing database.
|
|
143
146
|
- `drift:check` fails when the database no longer matches.
|
|
144
147
|
- `sync --dry-run` prints only SQL on stdout, to append to a migration file another tool applies: on Cloudflare D1, wrangler's (https://uql-orm.dev/cloudflare-d1.md).
|
|
145
148
|
|
|
146
|
-
Checks, an enum's included, and triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
|
|
149
|
+
Checks, an enum's included, and triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another. On MongoDB, checks and enums are the collection's validator, which uql owns whole, and a check fails a document lacking the field it compares.
|
|
147
150
|
|
|
148
151
|
## Where to read more
|
|
149
152
|
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import type { MigrationStorage, Querier } from '../../type/index.js';
|
|
2
|
-
/**
|
|
3
|
-
* Stores migration state in a JSON file.
|
|
4
|
-
* Useful for development or environments without a database.
|
|
5
|
-
*/
|
|
6
|
-
export declare class JsonMigrationStorage implements MigrationStorage {
|
|
7
|
-
private readonly filePath;
|
|
8
|
-
constructor(filePath?: string);
|
|
9
|
-
/** The names the file records, a missing file read as none run yet; any other read failure is the caller's. */
|
|
10
|
-
executed(): Promise<string[]>;
|
|
11
|
-
logWithQuerier(_querier: Querier, migrationName: string): Promise<void>;
|
|
12
|
-
unlogWithQuerier(_querier: Querier, migrationName: string): Promise<void>;
|
|
13
|
-
private save;
|
|
14
|
-
}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import * as fs from 'node:fs/promises';
|
|
2
|
-
/**
|
|
3
|
-
* Stores migration state in a JSON file.
|
|
4
|
-
* Useful for development or environments without a database.
|
|
5
|
-
*/
|
|
6
|
-
export class JsonMigrationStorage {
|
|
7
|
-
filePath;
|
|
8
|
-
constructor(filePath = './migrations/.uql-migrations.json') {
|
|
9
|
-
this.filePath = filePath;
|
|
10
|
-
}
|
|
11
|
-
/** The names the file records, a missing file read as none run yet; any other read failure is the caller's. */
|
|
12
|
-
async executed() {
|
|
13
|
-
const content = await fs.readFile(this.filePath, 'utf-8').catch((error) => {
|
|
14
|
-
if (error.code === 'ENOENT') {
|
|
15
|
-
return '[]';
|
|
16
|
-
}
|
|
17
|
-
throw error;
|
|
18
|
-
});
|
|
19
|
-
return JSON.parse(content);
|
|
20
|
-
}
|
|
21
|
-
async logWithQuerier(_querier, migrationName) {
|
|
22
|
-
const executed = await this.executed();
|
|
23
|
-
if (!executed.includes(migrationName)) {
|
|
24
|
-
await this.save([...executed, migrationName]);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
async unlogWithQuerier(_querier, migrationName) {
|
|
28
|
-
await this.save((await this.executed()).filter((name) => name !== migrationName));
|
|
29
|
-
}
|
|
30
|
-
save(names) {
|
|
31
|
-
return fs.writeFile(this.filePath, JSON.stringify(names, null, 2), 'utf-8');
|
|
32
|
-
}
|
|
33
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|