uql-orm 0.104.1 → 0.105.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -10
- package/dist/browser/querier/httpQuerier.d.ts +3 -3
- package/dist/browser/type/clientQuerier.d.ts +1 -1
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +9 -9
- package/dist/cockroachdb/cockroachDialect.d.ts +2 -2
- package/dist/dialect/abstractDialect.d.ts +3 -3
- package/dist/dialect/abstractSqlDialect.d.ts +39 -37
- package/dist/dialect/abstractSqlDialect.js +35 -32
- package/dist/dialect/aliases.d.ts +2 -0
- package/dist/dialect/aliases.js +2 -0
- package/dist/dialect/jsonSql.js +2 -2
- package/dist/dialect/mergeSqlDialect.d.ts +2 -2
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -7
- package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
- package/dist/dialect/operators.js +2 -4
- package/dist/dialect/queryJoins.d.ts +4 -2
- package/dist/dialect/vectorSqlDialect.d.ts +1 -1
- package/dist/dialect/vectorSqlDialect.js +1 -1
- package/dist/entity/column.d.ts +3 -0
- package/dist/entity/column.js +3 -0
- package/dist/entity/columnOptionsBuilder.d.ts +54 -0
- package/dist/entity/columnOptionsBuilder.js +108 -0
- package/dist/entity/decorator/bag.d.ts +5 -5
- package/dist/entity/decorator/entity.d.ts +3 -20
- package/dist/entity/decorator/entity.js +3 -37
- package/dist/entity/decorator/members.d.ts +46 -76
- package/dist/entity/decorator/members.js +18 -7
- package/dist/entity/index.d.ts +2 -1
- package/dist/entity/index.js +2 -1
- package/dist/entity/metadata/definition.d.ts +15 -26
- package/dist/entity/metadata/definition.js +344 -148
- package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
- package/dist/entity/metadata/schemaFixture/animal.js +7 -0
- package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
- package/dist/entity/metadata/schemaFixture/author.js +25 -0
- package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
- package/dist/entity/metadata/schemaFixture/book.js +23 -0
- package/dist/http/contract.d.ts +2 -2
- package/dist/http/handler.d.ts +2 -2
- package/dist/http/query.js +12 -13
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -1
- package/dist/mariadb/mariaDialect.d.ts +2 -2
- package/dist/mariadb/mariaDialect.js +1 -1
- package/dist/mariadb/mariadbQuerier.js +1 -3
- package/dist/migrate/builder/columnBuilder.d.ts +20 -68
- package/dist/migrate/builder/columnBuilder.js +104 -110
- package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
- package/dist/migrate/builder/migrationBuilder.js +7 -6
- package/dist/migrate/builder/tableBuilder.d.ts +3 -55
- package/dist/migrate/builder/tableBuilder.js +88 -204
- package/dist/migrate/builder/types.d.ts +52 -151
- package/dist/migrate/builder/types.js +0 -6
- package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
- package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
- package/dist/migrate/codegen/entityTypes.d.ts +2 -2
- package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
- package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
- package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
- package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
- package/dist/migrate/ddl/defaultSql.js +7 -6
- package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
- package/dist/migrate/ddl/indexCapabilities.js +26 -13
- package/dist/migrate/ddl/indexDdl.d.ts +13 -13
- package/dist/migrate/ddl/indexDdl.js +33 -30
- package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
- package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
- package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
- package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
- package/dist/migrate/drift/driftDetector.js +2 -2
- package/dist/migrate/generator/definitionToNode.d.ts +8 -2
- package/dist/migrate/generator/definitionToNode.js +4 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
- package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
- package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
- package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
- package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
- package/dist/migrate/introspection/postgresIntrospector.js +3 -4
- package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
- package/dist/migrate/introspection/tableSchemaAST.js +5 -1
- package/dist/migrate/migrator.d.ts +2 -2
- package/dist/migrate/schemaChange.d.ts +3 -3
- package/dist/migrate/schemaChange.js +3 -2
- package/dist/migrate/schemaGenerator.d.ts +5 -5
- package/dist/migrate/schemaGenerator.js +1 -1
- package/dist/migrate/storage/databaseStorage.js +4 -4
- package/dist/mongodb/mongoDialect.d.ts +41 -44
- package/dist/mongodb/mongoDialect.js +118 -32
- package/dist/mongodb/mongoIntrospector.d.ts +3 -1
- package/dist/mongodb/mongoIntrospector.js +11 -5
- package/dist/mongodb/mongoSchemaGenerator.d.ts +4 -4
- package/dist/mongodb/mongoSchemaGenerator.js +35 -27
- package/dist/mongodb/mongodbQuerier.d.ts +1 -11
- package/dist/mongodb/mongodbQuerier.js +9 -43
- package/dist/mssql/mssqlDialect.d.ts +4 -4
- package/dist/postgres/postgresDialect.d.ts +2 -2
- package/dist/querier/abstractQuerier.d.ts +0 -1
- package/dist/querier/abstractQuerier.js +1 -20
- package/dist/querier/abstractSqlQuerier.d.ts +1 -1
- package/dist/querier/keyset.js +3 -3
- package/dist/schema/declaredColumn.d.ts +11 -0
- package/dist/schema/declaredColumn.js +21 -0
- package/dist/schema/indexColumns.d.ts +0 -3
- package/dist/schema/indexColumns.js +11 -7
- package/dist/schema/indexDifferences.d.ts +10 -5
- package/dist/schema/indexDifferences.js +42 -28
- package/dist/schema/schemaASTBuilder.d.ts +4 -4
- package/dist/schema/schemaASTBuilder.js +28 -36
- package/dist/schema/schemaASTDiffer.js +8 -4
- package/dist/schema/sqlExpression.d.ts +21 -17
- package/dist/schema/sqlExpression.js +11 -23
- package/dist/type/column.d.ts +328 -0
- package/dist/type/column.js +2 -0
- package/dist/type/config.d.ts +3 -3
- package/dist/type/dialect.d.ts +15 -14
- package/dist/type/dialect.js +1 -0
- package/dist/type/entity.d.ts +292 -281
- package/dist/type/entity.js +6 -1
- package/dist/type/index.d.ts +2 -0
- package/dist/type/index.js +2 -0
- package/dist/type/migration.d.ts +11 -11
- package/dist/type/querier.d.ts +2 -2
- package/dist/type/query.d.ts +44 -40
- package/dist/type/query.js +2 -3
- package/dist/type/queryAggregate.d.ts +22 -12
- package/dist/type/querySql.d.ts +22 -6
- package/dist/type/querySql.js +27 -9
- package/dist/type/schemaEntity.d.ts +194 -0
- package/dist/type/schemaEntity.js +1 -0
- package/dist/type/utility.d.ts +4 -7
- package/dist/type/vector.d.ts +1 -1
- package/dist/util/ddlExpression.util.d.ts +12 -13
- package/dist/util/ddlExpression.util.js +12 -21
- package/dist/util/dialect.util.d.ts +11 -5
- package/dist/util/dialect.util.js +31 -37
- package/dist/util/field.util.d.ts +10 -9
- package/dist/util/field.util.js +14 -10
- package/dist/util/fieldOption.util.d.ts +11 -95
- package/dist/util/fieldOption.util.js +49 -16
- package/dist/util/hook.util.d.ts +3 -15
- package/dist/util/hook.util.js +3 -16
- package/dist/util/index.d.ts +1 -0
- package/dist/util/index.js +1 -0
- package/dist/util/indexEntry.util.d.ts +45 -0
- package/dist/util/indexEntry.util.js +138 -0
- package/dist/util/relationQuery.util.d.ts +0 -1
- package/dist/util/relationQuery.util.js +0 -5
- package/dist/util/sql.d.ts +13 -10
- package/dist/util/sql.js +34 -16
- package/dist/util/sql.util.d.ts +4 -5
- package/dist/util/sql.util.js +7 -16
- package/dist/util/string.util.d.ts +2 -0
- package/dist/util/string.util.js +4 -0
- package/dist/util/triggerWrite.d.ts +5 -5
- package/dist/util/uqlError.d.ts +1 -1
- package/dist/util/uqlError.js +1 -1
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +76 -25
- package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
package/dist/util/sql.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getMeta } from '../entity/metadata/definition.js';
|
|
2
|
-
import { ColumnRef, QuerySql, SQL_TEXT, RelationAggregate, TriggerWriteSql, } from '../type/index.js';
|
|
2
|
+
import { ColumnRef, JSON_PATH, JsonPathRef, QuerySql, REF_KEY, renderSql, SQL_TEXT, RelationAggregate, TriggerWriteSql, } from '../type/index.js';
|
|
3
3
|
import { aggregateOf, isInlinedExpression } from './field.util.js';
|
|
4
4
|
import { entityName, hasKeys } from './object.util.js';
|
|
5
5
|
import { UqlUsageError } from './uqlError.js';
|
|
@@ -20,7 +20,7 @@ export function sql(source, ...values) {
|
|
|
20
20
|
ctx.append(source[0]);
|
|
21
21
|
values.forEach((value, i) => {
|
|
22
22
|
if (value instanceof QuerySql) {
|
|
23
|
-
value
|
|
23
|
+
renderSql(value, opts);
|
|
24
24
|
}
|
|
25
25
|
else {
|
|
26
26
|
ctx.addValue(value);
|
|
@@ -36,7 +36,7 @@ sql.join = function join(parts, separator = ', ') {
|
|
|
36
36
|
if (index) {
|
|
37
37
|
opts.ctx.append(separator);
|
|
38
38
|
}
|
|
39
|
-
part
|
|
39
|
+
renderSql(part, opts);
|
|
40
40
|
});
|
|
41
41
|
});
|
|
42
42
|
};
|
|
@@ -88,27 +88,45 @@ export const SQL_VALUES = {
|
|
|
88
88
|
};
|
|
89
89
|
/**
|
|
90
90
|
* The fields of `entity` as {@link ColumnRef}s, each rendering inside `sql` as its column: named the way
|
|
91
|
-
* the dialect names it, so the naming strategy and
|
|
91
|
+
* the dialect names it, so the naming strategy and `.name()` apply, and qualified by the alias
|
|
92
92
|
* in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
|
|
93
93
|
*/
|
|
94
94
|
export function refs(entity) {
|
|
95
|
-
return
|
|
95
|
+
return refMap((key) => columnRef(entity, key));
|
|
96
|
+
}
|
|
97
|
+
/** A map answering each string key with `ref(key)`, typed as the caller's map, whose keys say what it holds. */
|
|
98
|
+
function refMap(ref) {
|
|
99
|
+
return new Proxy({}, { get: (_, key) => ref(String(key)) });
|
|
96
100
|
}
|
|
97
|
-
const MEMBER_REFS = new Proxy({}, { get: (_, key) => memberRef(String(key)) });
|
|
98
101
|
/**
|
|
99
|
-
* The refs a definition's callbacks read:
|
|
102
|
+
* The refs a definition's callbacks read: a check's, a computed field's, a predicate's. A member decorator
|
|
100
103
|
* sees no class, so these name no entity and resolve against the one rendering them.
|
|
101
104
|
*/
|
|
102
105
|
export function memberRefs() {
|
|
103
|
-
return
|
|
106
|
+
return refMap(memberRef);
|
|
104
107
|
}
|
|
105
|
-
/**
|
|
106
|
-
export function
|
|
107
|
-
return
|
|
108
|
+
/** Each to-many as a schema's aggregates read it, by key: the same refs {@link memberRefs} gives a decorated entity. */
|
|
109
|
+
export function relationRefs() {
|
|
110
|
+
return refMap(memberRef);
|
|
108
111
|
}
|
|
109
|
-
/**
|
|
110
|
-
|
|
111
|
-
|
|
112
|
+
/**
|
|
113
|
+
* The refs an index's callbacks read: each field's column, a JSON one also read into along its paths,
|
|
114
|
+
* `(user) => [user.settings.theme]`. Named for no entity, as {@link memberRefs} are.
|
|
115
|
+
*/
|
|
116
|
+
export function indexRefs() {
|
|
117
|
+
return refMap((key) => readsPaths(columnRef(undefined, key)));
|
|
118
|
+
}
|
|
119
|
+
/** `ref`, where any string key it has not got of its own reads one key further down the column's document. */
|
|
120
|
+
function readsPaths(ref) {
|
|
121
|
+
return new Proxy(ref, {
|
|
122
|
+
get: (target, prop, receiver) => {
|
|
123
|
+
if (typeof prop !== 'string' || prop in target) {
|
|
124
|
+
return Reflect.get(target, prop, receiver);
|
|
125
|
+
}
|
|
126
|
+
const path = target instanceof JsonPathRef ? `${target[JSON_PATH]}.${prop}` : prop;
|
|
127
|
+
return readsPaths(new JsonPathRef(target[REF_KEY], path));
|
|
128
|
+
},
|
|
129
|
+
});
|
|
112
130
|
}
|
|
113
131
|
/**
|
|
114
132
|
* One member as a definition reads it: a {@link ColumnRef} where it names a field, and the same object
|
|
@@ -116,7 +134,7 @@ export function entityWhere(where) {
|
|
|
116
134
|
* a member decorator sees no class and so cannot know which the key is; the types keep them apart.
|
|
117
135
|
*/
|
|
118
136
|
function memberRef(relation) {
|
|
119
|
-
const over = (op) => (pick, q) => relationAggregate({ relation, op, field: pick(memberRefs())
|
|
137
|
+
const over = (op) => (pick, q) => relationAggregate({ relation, op, field: pick(memberRefs())[REF_KEY], ...rowsOf(q) });
|
|
120
138
|
return Object.assign(columnRef(undefined, relation), {
|
|
121
139
|
count: (q) => relationAggregate({ relation, op: '$count', ...rowsOf(q) }),
|
|
122
140
|
sum: over('$sum'),
|
|
@@ -178,7 +196,7 @@ function renderColumn(meta, key, opts, qualifier) {
|
|
|
178
196
|
throw new UqlUsageError(`'${entityName(meta)}.${key}' reads a relation, which a trigger's row cannot: it fires on one row, ` +
|
|
179
197
|
'with no table in scope to correlate a subquery to. Name the columns it is derived from instead.');
|
|
180
198
|
}
|
|
181
|
-
grouped(field.computed)
|
|
199
|
+
renderSql(grouped(field.computed), scope);
|
|
182
200
|
return;
|
|
183
201
|
}
|
|
184
202
|
scope.ctx.append(scope.escapedPrefix + scope.dialect.escapeId(scope.dialect.columnOf(meta, key), true));
|
package/dist/util/sql.util.d.ts
CHANGED
|
@@ -12,6 +12,10 @@ export declare function splitQualifiedName(qualified: string): {
|
|
|
12
12
|
readonly name: string;
|
|
13
13
|
readonly schema?: string;
|
|
14
14
|
};
|
|
15
|
+
/** Hex chars of hash kept when a name has to be shortened. 24 bits over one table's constraints. */
|
|
16
|
+
export declare const NAME_HASH_LENGTH = 6;
|
|
17
|
+
/** Between table and columns, doubled: index names share one namespace per database, where `a` + `b_c` and `a_b` + `c` would collide. */
|
|
18
|
+
export declare const TABLE_SEPARATOR = "__";
|
|
15
19
|
/**
|
|
16
20
|
* Whether uql installed the object called `name`. Ownership is the prefix and nothing else, since no
|
|
17
21
|
* engine records who created one - so this is the only thing standing between a hand-written trigger or
|
|
@@ -29,11 +33,6 @@ export declare function ownedName(table: string, label: string, content: string)
|
|
|
29
33
|
* unique one. A partial index also carries a hash of its `where`, so an edited predicate is a new name.
|
|
30
34
|
*/
|
|
31
35
|
export declare function derivedIndexName(table: string, columns: readonly string[], unique?: boolean, where?: string): string;
|
|
32
|
-
/**
|
|
33
|
-
* Whether uql named the index `name` itself from `columns`: `derivedIndexName`'s forms, with a predicate's hash or
|
|
34
|
-
* without, and the `idx_<table>_<columns>` spelling an older uql gave one.
|
|
35
|
-
*/
|
|
36
|
-
export declare function isDerivedIndexName(table: string, columns: readonly string[], name: string): boolean;
|
|
37
36
|
/**
|
|
38
37
|
* The constraint name a primary key gets when we name one: `Enrolment__studentId_courseId_pk`.
|
|
39
38
|
*
|
package/dist/util/sql.util.js
CHANGED
|
@@ -21,19 +21,22 @@ export function splitQualifiedName(qualified) {
|
|
|
21
21
|
*/
|
|
22
22
|
const MAX_IDENTIFIER_LENGTH = 63;
|
|
23
23
|
/** Hex chars of hash kept when a name has to be shortened. 24 bits over one table's constraints. */
|
|
24
|
-
const NAME_HASH_LENGTH = 6;
|
|
24
|
+
export const NAME_HASH_LENGTH = 6;
|
|
25
25
|
/**
|
|
26
26
|
* The name of a derived index or constraint, such as `Order__total_idx`, with the kind last as Postgres names
|
|
27
27
|
* its own. It leaves out the table's schema, since it is a single identifier. The AST, the DDL and a `DROP`
|
|
28
28
|
* all use this one rule.
|
|
29
29
|
*/
|
|
30
30
|
function derivedConstraintName(table, parts, kind) {
|
|
31
|
-
const
|
|
32
|
-
const body = parts.length ? `${name}${TABLE_SEPARATOR}${parts.join('_')}` : name;
|
|
31
|
+
const body = parts.length ? `${tableStem(table)}${parts.join('_')}` : splitQualifiedName(table).name;
|
|
33
32
|
return clampIdentifier(`${body}_${kind}`);
|
|
34
33
|
}
|
|
34
|
+
/** What a derived name over parts starts with: its table, unqualified, and the separator. */
|
|
35
|
+
function tableStem(table) {
|
|
36
|
+
return splitQualifiedName(table).name + TABLE_SEPARATOR;
|
|
37
|
+
}
|
|
35
38
|
/** Between table and columns, doubled: index names share one namespace per database, where `a` + `b_c` and `a_b` + `c` would collide. */
|
|
36
|
-
const TABLE_SEPARATOR = '__';
|
|
39
|
+
export const TABLE_SEPARATOR = '__';
|
|
37
40
|
/** What every name uql installs begins with, so the two ends asking about one cannot spell it apart. */
|
|
38
41
|
const OWNED_START = `${OWNED_PREFIX}_`;
|
|
39
42
|
/**
|
|
@@ -74,18 +77,6 @@ export function derivedIndexName(table, columns, unique = false, where) {
|
|
|
74
77
|
const parts = where === undefined ? columns : [...columns, hashIdentifier(where)];
|
|
75
78
|
return derivedConstraintName(table, parts, unique ? 'uk' : 'idx');
|
|
76
79
|
}
|
|
77
|
-
/** The hash a partial index's derived name carries before its kind. */
|
|
78
|
-
const PREDICATE_HASH = new RegExp(`_[0-9a-f]{${NAME_HASH_LENGTH}}(?=_(?:idx|uk)$)`);
|
|
79
|
-
/**
|
|
80
|
-
* Whether uql named the index `name` itself from `columns`: `derivedIndexName`'s forms, with a predicate's hash or
|
|
81
|
-
* without, and the `idx_<table>_<columns>` spelling an older uql gave one.
|
|
82
|
-
*/
|
|
83
|
-
export function isDerivedIndexName(table, columns, name) {
|
|
84
|
-
const plain = [derivedIndexName(table, columns), derivedIndexName(table, columns, true)];
|
|
85
|
-
return (plain.includes(name) ||
|
|
86
|
-
plain.includes(name.replace(PREDICATE_HASH, '')) ||
|
|
87
|
-
name === `idx_${table}_${columns.join('_')}`);
|
|
88
|
-
}
|
|
89
80
|
/**
|
|
90
81
|
* The constraint name a primary key gets when we name one: `Enrolment__studentId_courseId_pk`.
|
|
91
82
|
*
|
|
@@ -31,3 +31,5 @@ export declare function pluralize(name: string): string;
|
|
|
31
31
|
* browser and edge entries cannot reach `node:crypto`. It is not a security hash; it only tells inputs apart.
|
|
32
32
|
*/
|
|
33
33
|
export declare function fnv1a(value: string): number;
|
|
34
|
+
/** `text` as a regex matching it literally. */
|
|
35
|
+
export declare function escapeRegExp(text: string): string;
|
package/dist/util/string.util.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { type EntityPredicate, type QueryConflictPaths, type QuerySql, type TriggerWrite, type
|
|
1
|
+
import { type EntityPredicate, type QueryConflictPaths, type QuerySql, type TriggerWrite, type AbstractType, type UpdatePayload, type WritableKey, type WriteRow } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* A row inserted by a trigger's body, into any table: `insertInto(PostAudit, { postId: newRow.id })`.
|
|
4
4
|
* Each value is a literal or SQL, a row's ref most often, and every engine renders it, SQL Server's
|
|
5
5
|
* set-based trigger included, where it inserts one row for each the statement touched.
|
|
6
6
|
*/
|
|
7
|
-
export declare function insertInto<E extends object>(entity:
|
|
7
|
+
export declare function insertInto<E extends object>(entity: AbstractType<E>, row: WriteRow<E>): QuerySql;
|
|
8
8
|
/**
|
|
9
9
|
* A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
|
|
10
10
|
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { count: { $inc: 1 } })`.
|
|
11
11
|
*/
|
|
12
|
-
export declare function upsertInto<E extends object>(entity:
|
|
12
|
+
export declare function upsertInto<E extends object>(entity: AbstractType<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>, update?: UpdatePayload<E, QuerySql, WritableKey<E>, never>): QuerySql;
|
|
13
13
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
|
14
|
-
export declare function updateTable<E extends object>(entity:
|
|
14
|
+
export declare function updateTable<E extends object>(entity: AbstractType<E>, q: {
|
|
15
15
|
readonly $where: EntityPredicate<E>;
|
|
16
16
|
}, set: UpdatePayload<E, QuerySql, WritableKey<E>, never>): QuerySql;
|
|
17
17
|
/** The rows `q.$where` names deleted by a trigger's body, outright: a soft delete is an `updateTable`. */
|
|
18
|
-
export declare function deleteFrom<E extends object>(entity:
|
|
18
|
+
export declare function deleteFrom<E extends object>(entity: AbstractType<E>, q: {
|
|
19
19
|
readonly $where: EntityPredicate<E>;
|
|
20
20
|
}): QuerySql;
|
|
21
21
|
/**
|
package/dist/util/uqlError.d.ts
CHANGED
|
@@ -32,7 +32,7 @@ export declare class UqlSecurityError extends UqlError {
|
|
|
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
34
|
/**
|
|
35
|
-
* Thrown when an update's
|
|
35
|
+
* Thrown when an update's `f.version()` column no longer matches the row: another writer moved it on,
|
|
36
36
|
* or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`
|
|
37
37
|
* where there is no row left.
|
|
38
38
|
*/
|
package/dist/util/uqlError.js
CHANGED
|
@@ -25,7 +25,7 @@ export function kindOf(value) {
|
|
|
25
25
|
return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
|
-
* Thrown when an update's
|
|
28
|
+
* Thrown when an update's `f.version()` column no longer matches the row: another writer moved it on,
|
|
29
29
|
* or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`
|
|
30
30
|
* where there is no row left.
|
|
31
31
|
*/
|
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, 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.105.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -10,7 +10,7 @@ description: >
|
|
|
10
10
|
|
|
11
11
|
# UQL
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
An entity is a decorated class, or a schema its row type is derived from. A query is a JSON object checked key by key against the entity, and it runs the same on every supported database. There is no schema file, no generated client and no query builder.
|
|
14
14
|
|
|
15
15
|
Full docs are Markdown: the index at https://uql-orm.dev/llms.txt, and each page at its URL plus `.md`. Read the page for the task before guessing an option.
|
|
16
16
|
|
|
@@ -42,14 +42,19 @@ Driver entry points: `uql-orm/postgres`, `mysql`, `mariadb`, `sqlite`, `mongodb`
|
|
|
42
42
|
## Entities
|
|
43
43
|
|
|
44
44
|
```ts
|
|
45
|
-
import { Entity,
|
|
45
|
+
import { Entity, f, Field, ManyToOne, OneToMany } from 'uql-orm';
|
|
46
46
|
|
|
47
47
|
@Entity()
|
|
48
48
|
export class User {
|
|
49
|
-
@
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
49
|
+
@Field(
|
|
50
|
+
f
|
|
51
|
+
.uuid()
|
|
52
|
+
.id()
|
|
53
|
+
.onInsert(() => crypto.randomUUID()),
|
|
54
|
+
)
|
|
55
|
+
id?: string;
|
|
56
|
+
|
|
57
|
+
@Field(f.string().unique())
|
|
53
58
|
email!: string;
|
|
54
59
|
|
|
55
60
|
@OneToMany({ entity: () => Post, mappedBy: (post) => post.author })
|
|
@@ -58,13 +63,13 @@ export class User {
|
|
|
58
63
|
|
|
59
64
|
@Entity()
|
|
60
65
|
export class Post {
|
|
61
|
-
@
|
|
62
|
-
id
|
|
66
|
+
@Field(f.number().id())
|
|
67
|
+
id?: number;
|
|
63
68
|
|
|
64
|
-
@Field(
|
|
69
|
+
@Field(f.string().nullable())
|
|
65
70
|
title?: string | null;
|
|
66
71
|
|
|
67
|
-
@Field(
|
|
72
|
+
@Field(f.references(() => User).nullable())
|
|
68
73
|
authorId?: string | null;
|
|
69
74
|
|
|
70
75
|
@ManyToOne({ entity: () => User, references: (post) => post.authorId })
|
|
@@ -72,20 +77,66 @@ export class Post {
|
|
|
72
77
|
}
|
|
73
78
|
```
|
|
74
79
|
|
|
75
|
-
- A
|
|
76
|
-
-
|
|
77
|
-
-
|
|
78
|
-
-
|
|
79
|
-
-
|
|
80
|
-
-
|
|
81
|
-
- `Date` is an instant, stored in UTC to the millisecond on every engine. `
|
|
82
|
-
- Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
80
|
+
- A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal()`, `f.decimal(precision)`, `f.decimal(precision, scale)`, `f.boolean()`, `f.date()`, `f.json(shape?)`, `f.jsonb(shape?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other column type, and `f.references(() => Target)` for a foreign key, which takes the target's key type. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A bound holds in either order around `.columnType('char')`, but not around a `sql` type, which carries its own.
|
|
81
|
+
- A column is NOT NULL unless `.nullable()`; its property then admits `null` (`title?: string | null`).
|
|
82
|
+
- Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable, `.eager(false)`, computed fields and relations. uql fills a single-column key and a version.
|
|
83
|
+
- A NOT NULL field a default fills (`.default()`, `.onInsert()`) is `!` and listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
|
|
84
|
+
- `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included.
|
|
85
|
+
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... }) abstract class`, or a schema's `abstract: true`. A query or write on one does not compile: query the entities extending it.
|
|
86
|
+
- `Date` is an instant, stored in UTC to the millisecond on every engine. `f.decimal()` is exact text (`price?: string | null`). `f.number().precision(10).scale(2)` opts into a rounding JS number.
|
|
87
|
+
- Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`. Either may be left out where only one member fits: a decorated many-to-one's one foreign key to its target, a one-to-many's one many-to-one pointing back.
|
|
83
88
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows in the same transaction; an update replaces a to-many's rows.
|
|
84
|
-
- **MongoDB:** a key declared `
|
|
85
|
-
- Optimistic lock: `@Field(
|
|
86
|
-
- Computed fields are `readonly` and read in any query that names them. As SQL over the row
|
|
87
|
-
- Partial index: `@
|
|
88
|
-
-
|
|
89
|
+
- **MongoDB:** a key declared `f.number()` and left to the database is refused, since MongoDB only generates ObjectIds. Declare the key a string, or give it an `.onInsert()` generator.
|
|
90
|
+
- Optimistic lock: `@Field(f.version())` with `[versionKey]?: 'version'` on the class. An update must carry the version it read. A stale one throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409).
|
|
91
|
+
- Computed fields are `readonly` and read in any query that names them. As SQL over the row, ``@Computed((u) => f.string().as(sql`${u.first} || ' ' || ${u.last}`))``, `.stored()` making a generated column, or as a relation aggregate: `@Computed((user) => user.resources.count())`.
|
|
92
|
+
- Indexes, checks, filters and triggers are `@Entity` options, each entry made by the helper the callback is handed. Partial index: `@Entity({ indexes: (post, index) => [index([post.authorId], { where: { archived: { $ne: true } } })] })`; a string second argument is the index's name. Write the predicate as a query, not `sql`.
|
|
93
|
+
- JSON path index: read the path off the column's ref, `index([user.settings.theme])` for text, `index([{ column: user.settings.rating, type: Number }])` for any other value, `type: [String]` for an array's elements. MySQL keys a text path or element as `CHAR(n)`, `{ column: user.tags, type: [String], charLength: 64 }`, and a `TEXT` column by a prefix, `{ column: post.body, prefixLength: 64 }`.
|
|
94
|
+
- Triggers run in the database: `@Entity({ triggers: (post, trigger) => [trigger({ on: 'afterUpdate', of: [post.status], run })] })`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. A trigger's writes skip uql's fills and entity filters. MongoDB has no triggers: https://uql-orm.dev/entities/triggers.md
|
|
95
|
+
|
|
96
|
+
### Schema entities
|
|
97
|
+
|
|
98
|
+
The same entities declared as data, the row type derived:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { defineEntity, f, sql } from 'uql-orm';
|
|
102
|
+
|
|
103
|
+
export const Author = defineEntity({
|
|
104
|
+
name: 'Author',
|
|
105
|
+
fields: {
|
|
106
|
+
id: f.number().id(),
|
|
107
|
+
name: f.string(),
|
|
108
|
+
settings: f.json({ theme: String, 'bio?': String }).nullable(),
|
|
109
|
+
},
|
|
110
|
+
}).relations(
|
|
111
|
+
(rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }),
|
|
112
|
+
(agg) => ({ bookCount: () => agg.books.count(), topStock: () => agg.books.max((book) => book.stock) }),
|
|
113
|
+
);
|
|
114
|
+
export type Author = InstanceType<typeof Author>;
|
|
115
|
+
|
|
116
|
+
export const Book = defineEntity({
|
|
117
|
+
name: 'Book',
|
|
118
|
+
fields: {
|
|
119
|
+
id: f.number().id(),
|
|
120
|
+
title: f.string(),
|
|
121
|
+
stock: f.number().default(0),
|
|
122
|
+
authorId: f.number(),
|
|
123
|
+
editorId: f.number().nullable(),
|
|
124
|
+
},
|
|
125
|
+
})
|
|
126
|
+
.computed((book) => ({ shout: f.string().as(sql`upper(${book.title})`) }))
|
|
127
|
+
.indexes((book, index) => [index([book.title])])
|
|
128
|
+
.hooks({ beforeInsert: [(book) => void (book.stock ??= 0)] })
|
|
129
|
+
.references({ editorId: { entity: () => Author, onDelete: 'SET NULL' } })
|
|
130
|
+
.relations((rel) => ({ author: () => rel.manyToOne(Author, { references: (book) => book.authorId }) }));
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- Each field is a column builder, as in the decorated form. The row follows from them: a key, a version and a NOT NULL column are always present, a `.nullable()` one reads `| null`; a default (`.default()`, `.onInsert()`, `.autoIncrement()`) makes it optional on insert; `f.enum()` gives the literal union. No `!`, `?` or brands to write.
|
|
134
|
+
- The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `references` points a foreign key with no relation at its target; `relations` comes last, but for a `filters` that reads through them: `.relations(...).filters({ byActiveAuthor: { where: { author: { active: true } } } })`. `defineEntity` itself takes `name` (the class name, which a naming strategy derives the table from), `table`, `schema`, `extends` and `fields`.
|
|
135
|
+
- Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. `manyToOne` names its `references`; `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
|
|
136
|
+
- `relations`' second callback reads values over a to-many as columns: `(agg) => ({ bookCount: () => agg.books.count() })`.
|
|
137
|
+
- A hook is a function of the row and `{ querier, onCommit }`.
|
|
138
|
+
- A JSON column's payload is its shape, `f.json(shape)`: `String`, `Number` or `Boolean`, an object of shapes, `[shape]` for an array, `'key?'` for an optional member. Without one, any path reads.
|
|
139
|
+
- Behaviour is a function of the row, `label(author: Author)`: a row reads back as a plain object, so a method would never be there.
|
|
89
140
|
|
|
90
141
|
## Queries
|
|
91
142
|
|
|
@@ -103,7 +154,7 @@ const users = await pool.findMany(User, {
|
|
|
103
154
|
});
|
|
104
155
|
```
|
|
105
156
|
|
|
106
|
-
- Query keys: `$select`, `$
|
|
157
|
+
- Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`. `$count: { posts: true }` counts a to-many under `_count` without loading it. `$select: { password: false }` reads every field but `password`.
|
|
107
158
|
- 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, or the query's `$entity`. Signatures: https://uql-orm.dev/querying/methods.md
|
|
108
159
|
- Results are narrowed to what the query selected and populated, at every depth of `$populate`. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing by typing it `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`; typed `Query<E>`, it reads whole rows.
|
|
109
160
|
- `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list, empty when there are no children. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
|
|
@@ -111,7 +162,7 @@ const users = await pool.findMany(User, {
|
|
|
111
162
|
- `$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`. Combine with `$and`, `$or`, `$not`, `$nor`. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
|
|
112
163
|
- An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
|
|
113
164
|
- NULL compares as the engine does: on SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.
|
|
114
|
-
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does. It returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique
|
|
165
|
+
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does. It returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique NOT NULL field, and takes no `$skip`.
|
|
115
166
|
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update payload with operators. Without `update`, a conflicting row takes the payload but keeps its own key. Resolves to the row's id.
|
|
116
167
|
- Writes take `{ returning: { id: true } }` as their last argument and resolve to those rows. Without it, inserts and upserts resolve to ids, and updates and deletes to a count.
|
|
117
168
|
- `updateMany` and `deleteMany` that name no rows throw: no `$where` holding a value, and no `$limit`. Pass `{ unfiltered: true }` to mean the whole table.
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { IndexNode } from '../../schema/types.js';
|
|
2
|
-
/**
|
|
3
|
-
* Whether `@Field({ index })` can carry the whole index. It says only "this column is indexed under
|
|
4
|
-
* this name", and `unique` beside it that the index is unique, so anything else the index declares - an
|
|
5
|
-
* expression, a predicate, an access method, stored columns, a stored order - has to be written out as
|
|
6
|
-
* an `@Index` instead.
|
|
7
|
-
*/
|
|
8
|
-
export declare function isPlainFieldIndex(index: IndexNode): boolean;
|
|
9
|
-
/**
|
|
10
|
-
* One `@Index((user) => [...])` as source, for an index no `@Field` can express, its columns read off the
|
|
11
|
-
* refs `param` names. Emits `sql` for an expression entry, so callers import `sql` when
|
|
12
|
-
* {@link indexNeedsRaw} holds.
|
|
13
|
-
*/
|
|
14
|
-
export declare function buildIndexDecoratorSource(index: IndexNode, propertyName: (column: string) => string, param: string): string;
|
|
15
|
-
/** Whether emitting this index needs `sql` imported alongside `Index`. */
|
|
16
|
-
export declare function indexNeedsRaw(index: IndexNode): boolean;
|