uql-orm 0.100.3 → 0.101.0
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 +1 -1
- package/dist/dialect/abstractSqlDialect.d.ts +8 -1
- package/dist/dialect/abstractSqlDialect.js +36 -13
- package/dist/entity/metadata/definition.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/migrate/cli-config.d.ts +3 -4
- package/dist/migrate/cli-config.js +8 -6
- package/dist/mongodb/mongoDialect.js +3 -3
- package/dist/querier/abstractQuerier.d.ts +4 -0
- package/dist/querier/abstractQuerier.js +42 -37
- package/dist/util/relationQuery.util.d.ts +21 -12
- package/dist/util/relationQuery.util.js +30 -14
- package/package.json +2 -2
- package/skills/uql-orm/SKILL.md +3 -1
package/README.md
CHANGED
|
@@ -126,7 +126,7 @@ The same queries run from the browser too: [serve them over HTTP](https://uql-or
|
|
|
126
126
|
|
|
127
127
|
## Why UQL?
|
|
128
128
|
|
|
129
|
-
- **One API, everywhere it runs.** PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, MSSQL, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun's native SQL, and even MongoDB. The same code on Node
|
|
129
|
+
- **One API, everywhere it runs.** PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, MSSQL, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun's native SQL, and even MongoDB. The same code on Node 22.18+, Bun, [Cloudflare Workers](https://uql-orm.dev/cloudflare-d1), [AWS Lambda and Vercel](https://uql-orm.dev/serverless), and [the browser](https://uql-orm.dev/browser), with no native binaries on the `fetch`-based drivers.
|
|
130
130
|
- **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
|
|
131
131
|
- **Relations without N+1.** [`$populate`](https://uql-orm.dev/querying/relations) reads a to-many inside the parent's statement, so a read is one round trip. Nothing is lazy, so nothing fires behind your back in a serializer.
|
|
132
132
|
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 27 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
|
|
@@ -706,9 +706,16 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
706
706
|
private appendCorrelation;
|
|
707
707
|
/**
|
|
708
708
|
* A junction's rows pairing the parent with the relation's targets, as far as its own filters let them
|
|
709
|
-
* through, since a soft-deleted link is not a link; and the column
|
|
709
|
+
* through, since a soft-deleted link is not a link; and the column each of them holds a target's key in.
|
|
710
710
|
*/
|
|
711
711
|
private junctionRows;
|
|
712
|
+
/**
|
|
713
|
+
* Tests that the `outer` side's row has a partner among the rows of `from`, the other side's, a pair per key
|
|
714
|
+
* column: an `IN` over the one column each holds a lone key in, an `EXISTS` correlating every pair for several,
|
|
715
|
+
* which an `IN` cannot say. `from` is the junction's rows, already filtered, where the target is the outer side;
|
|
716
|
+
* `tail` writes the partner rows' own filters.
|
|
717
|
+
*/
|
|
718
|
+
private appendPartner;
|
|
712
719
|
/**
|
|
713
720
|
* A relation's rows as one JSON array, in the engine's own spelling: an aggregate over them read as
|
|
714
721
|
* a derived table ({@link derivedRelation}), or over the related table itself where the engine cannot
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { fieldOf, getMeta, relationOf
|
|
1
|
+
import { fieldOf, getMeta, relationOf } from '../entity/index.js';
|
|
2
2
|
import { COUNT_RESULT_KEY, parseQueryLock, QueryRaw, RAW_ALIAS, } from '../type/index.js';
|
|
3
3
|
import { utcTimestamp } from '../util/date.js';
|
|
4
4
|
import { isExactDecimal, isInlinedExpression, jsonKey, jsonPathKeys } from '../util/field.util.js';
|
|
5
|
-
import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch,
|
|
5
|
+
import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, raw, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
|
|
6
6
|
import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
|
|
7
7
|
import { kindOf, UqlUsageError } from '../util/uqlError.js';
|
|
8
8
|
import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
|
|
@@ -1835,11 +1835,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1835
1835
|
ctx.append(junction.from);
|
|
1836
1836
|
if (hasKeys(targetWhere)) {
|
|
1837
1837
|
const related = this.tableRef(relatedMeta, ctx.claimAlias(relKey));
|
|
1838
|
-
|
|
1839
|
-
ctx.
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1838
|
+
ctx.append(' AND ');
|
|
1839
|
+
this.appendPartner(ctx, junction.targets.map(({ key, column }) => ({
|
|
1840
|
+
junction: column,
|
|
1841
|
+
target: this.escapedColumn(related.alias, relatedMeta, key),
|
|
1842
|
+
})), 'junction', related.ref, (clause) => this.renderWhere(ctx, relatedEntity, targetWhere, { prefix: related.alias, clause }));
|
|
1843
1843
|
}
|
|
1844
1844
|
}
|
|
1845
1845
|
else {
|
|
@@ -1928,7 +1928,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1928
1928
|
correlation(meta, rel, parent, alias, joinedMeta) {
|
|
1929
1929
|
const escapedParent = this.escapeId(parent, true, true);
|
|
1930
1930
|
return parentJoins(rel, meta.ids.length)
|
|
1931
|
-
.map(({
|
|
1931
|
+
.map(({ key, column }) => `${this.escapedColumn(alias, joinedMeta, column)} = ${escapedParent}${this.escapedColumnName(meta, key)}`)
|
|
1932
1932
|
.join(' AND ');
|
|
1933
1933
|
}
|
|
1934
1934
|
/**
|
|
@@ -1994,23 +1994,46 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1994
1994
|
return;
|
|
1995
1995
|
}
|
|
1996
1996
|
const junction = this.junctionRows(ctx, meta, rel, rel.through(), parent);
|
|
1997
|
-
|
|
1998
|
-
|
|
1997
|
+
this.appendPartner(ctx, junction.targets.map(({ key, column }) => ({
|
|
1998
|
+
junction: column,
|
|
1999
|
+
target: this.escapedColumn(alias, relMeta, key),
|
|
2000
|
+
})), 'target', junction.from);
|
|
1999
2001
|
}
|
|
2000
2002
|
/**
|
|
2001
2003
|
* A junction's rows pairing the parent with the relation's targets, as far as its own filters let them
|
|
2002
|
-
* through, since a soft-deleted link is not a link; and the column
|
|
2004
|
+
* through, since a soft-deleted link is not a link; and the column each of them holds a target's key in.
|
|
2003
2005
|
*/
|
|
2004
2006
|
junctionRows(ctx, meta, rel, junction, parent) {
|
|
2005
2007
|
const junctionMeta = getMeta(junction);
|
|
2006
2008
|
const { alias, ref } = this.tableRef(junctionMeta, ctx.claimAlias(this.resolveTableAlias(junctionMeta), parent));
|
|
2007
2009
|
const scope = this.buildFragment(ctx, (fragmentCtx) => this.where(fragmentCtx, junction, {}, { prefix: alias, clause: 'AND' }));
|
|
2008
|
-
const [target] = targetKeyColumns(rel, meta.ids.length);
|
|
2009
2010
|
return {
|
|
2010
2011
|
from: `${ref} WHERE ${this.correlation(meta, rel, parent, alias, junctionMeta)}${scope}`,
|
|
2011
|
-
|
|
2012
|
+
targets: targetJoins(rel, meta.ids.length).map(({ key, column }) => ({
|
|
2013
|
+
key,
|
|
2014
|
+
column: this.escapedColumn(alias, junctionMeta, column),
|
|
2015
|
+
})),
|
|
2012
2016
|
};
|
|
2013
2017
|
}
|
|
2018
|
+
/**
|
|
2019
|
+
* Tests that the `outer` side's row has a partner among the rows of `from`, the other side's, a pair per key
|
|
2020
|
+
* column: an `IN` over the one column each holds a lone key in, an `EXISTS` correlating every pair for several,
|
|
2021
|
+
* which an `IN` cannot say. `from` is the junction's rows, already filtered, where the target is the outer side;
|
|
2022
|
+
* `tail` writes the partner rows' own filters.
|
|
2023
|
+
*/
|
|
2024
|
+
appendPartner(ctx, pairs, outer, from, tail) {
|
|
2025
|
+
const inner = outer === 'junction' ? 'target' : 'junction';
|
|
2026
|
+
if (pairs.length === 1) {
|
|
2027
|
+
ctx.append(`${pairs[0][outer]} IN (SELECT ${pairs[0][inner]} FROM ${from}`);
|
|
2028
|
+
tail?.('WHERE');
|
|
2029
|
+
}
|
|
2030
|
+
else {
|
|
2031
|
+
const links = pairs.map((pair) => `${pair.junction} = ${pair.target}`).join(' AND ');
|
|
2032
|
+
ctx.append(`EXISTS (SELECT 1 FROM ${from} ${outer === 'target' ? 'AND' : 'WHERE'} ${links}`);
|
|
2033
|
+
tail?.('AND');
|
|
2034
|
+
}
|
|
2035
|
+
ctx.append(')');
|
|
2036
|
+
}
|
|
2014
2037
|
/**
|
|
2015
2038
|
* The rows read as a derived table, their values crossing JSON and, where the aggregate orders, each
|
|
2016
2039
|
* sort term carried out beside them for it to order by, since a derived table's order is not promised
|
|
@@ -260,7 +260,7 @@ export function assertSoleId(meta, what) {
|
|
|
260
260
|
return;
|
|
261
261
|
}
|
|
262
262
|
throw new UqlUsageError(ids.length
|
|
263
|
-
? `'${meta.entity.name}' has a composite primary key (${ids.join(', ')}), which ${what} does not support
|
|
263
|
+
? `'${meta.entity.name}' has a composite primary key (${ids.join(', ')}), which ${what} does not support.`
|
|
264
264
|
: // An entity registered with `@Field` but no `@Entity` never ran the check in `defineEntity`.
|
|
265
265
|
`'${meta.entity.name}' has no primary key, which ${what} needs.`);
|
|
266
266
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,8 @@ export * from './entity/decorator/members.js';
|
|
|
4
4
|
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, removeEntity, } from './entity/metadata/definition.js';
|
|
5
5
|
export * from './namingStrategy/index.js';
|
|
6
6
|
export { type QueryError, queryErrorKind } from './querier/queryError.js';
|
|
7
|
-
export * from './type/index.js';
|
|
7
|
+
export type * from './type/index.js';
|
|
8
|
+
export { idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
8
9
|
export { withDeleted } from './util/filters.util.js';
|
|
9
10
|
export type { HookContext } from './util/hook.util.js';
|
|
10
11
|
export { DefaultLogger } from './util/logger.js';
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ export * from './entity/decorator/members.js';
|
|
|
4
4
|
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, removeEntity, } from './entity/metadata/definition.js';
|
|
5
5
|
export * from './namingStrategy/index.js';
|
|
6
6
|
export { queryErrorKind } from './querier/queryError.js';
|
|
7
|
-
export
|
|
7
|
+
export { idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
8
8
|
export { withDeleted } from './util/filters.util.js';
|
|
9
9
|
export { DefaultLogger } from './util/logger.js';
|
|
10
10
|
export { currentDate, currentTime, currentTimestamp, raw, refs, uuid, uuidv7 } from './util/raw.js';
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import type { Config } from '../type/index.js';
|
|
2
2
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
3
3
|
/**
|
|
4
|
-
* The project's own
|
|
5
|
-
* no decorators,
|
|
6
|
-
*
|
|
7
|
-
* import of its own would load the config's `uql-orm` apart from the CLI's, whose objects the other misreads.
|
|
4
|
+
* The ESM build of the project's own tsx API, where Node must load a TypeScript config: its type stripping
|
|
5
|
+
* runs no decorators. Registered, never imported through, so the config shares the CLI's `uql-orm`. Read off
|
|
6
|
+
* the export map, as `require.resolve` picks the CommonJS build, whose `register` fails on Node 22.
|
|
8
7
|
*/
|
|
9
8
|
export declare function tsxApiFor(path: string, versions: {
|
|
10
9
|
bun?: string;
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import { stat } from 'node:fs/promises';
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
|
-
import { resolve } from 'node:path';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
5
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
6
6
|
/**
|
|
7
|
-
* The project's own
|
|
8
|
-
* no decorators,
|
|
9
|
-
*
|
|
10
|
-
* import of its own would load the config's `uql-orm` apart from the CLI's, whose objects the other misreads.
|
|
7
|
+
* The ESM build of the project's own tsx API, where Node must load a TypeScript config: its type stripping
|
|
8
|
+
* runs no decorators. Registered, never imported through, so the config shares the CLI's `uql-orm`. Read off
|
|
9
|
+
* the export map, as `require.resolve` picks the CommonJS build, whose `register` fails on Node 22.
|
|
11
10
|
*/
|
|
12
11
|
export function tsxApiFor(path, versions) {
|
|
13
12
|
if (!/\.[mc]?ts$/.test(path) || versions.bun) {
|
|
14
13
|
return undefined;
|
|
15
14
|
}
|
|
16
15
|
try {
|
|
17
|
-
|
|
16
|
+
const require = createRequire(path);
|
|
17
|
+
const manifest = require.resolve('tsx/package.json');
|
|
18
|
+
const { exports } = require(manifest);
|
|
19
|
+
return join(dirname(manifest), exports['./esm/api'].import.default);
|
|
18
20
|
}
|
|
19
21
|
catch {
|
|
20
22
|
return undefined;
|
|
@@ -6,7 +6,7 @@ import { aggregateColumnField, groupPathField, resolveGroupJoins, relationSortTe
|
|
|
6
6
|
import { assertSoleId, fieldOf, getMeta, relationOf, soleIdOf } from '../entity/index.js';
|
|
7
7
|
import { COUNT_RESULT_KEY } from '../type/query.js';
|
|
8
8
|
import { QueryRaw } from '../type/queryRaw.js';
|
|
9
|
-
import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey,
|
|
9
|
+
import { aggregateOf, isSelectList, assertAggregateColumns, assertNoUndefined, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, definedEntries, getKeys, holdsForeignKey, jsonKey, jsonPathKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetJoins, textSortOf, vectorDistanceOf, } from '../util/index.js';
|
|
10
10
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
11
11
|
import { decodeBigIntsExcept } from '../util/wideNumber.js';
|
|
12
12
|
import { textLanguage } from './textLanguage.js';
|
|
@@ -303,13 +303,13 @@ export class MongoDialect extends AbstractDialect {
|
|
|
303
303
|
assertSoleId(meta, 'MongoDB');
|
|
304
304
|
assertSoleId(relMeta, 'MongoDB');
|
|
305
305
|
const [parentJoin] = parentJoins(relOpts, meta.ids.length);
|
|
306
|
-
const [targetColumn] =
|
|
306
|
+
const [{ column: targetColumn }] = targetJoins(relOpts, meta.ids.length);
|
|
307
307
|
const scope = this.renderFilter(through, this.scopedWhere(throughMeta, {}));
|
|
308
308
|
return {
|
|
309
309
|
lookup: {
|
|
310
310
|
from: this.resolveTableName(throughMeta),
|
|
311
311
|
localField: ID_KEY,
|
|
312
|
-
foreignField: this.columnOf(throughMeta, parentJoin.
|
|
312
|
+
foreignField: this.columnOf(throughMeta, parentJoin.column),
|
|
313
313
|
},
|
|
314
314
|
scope: hasKeys(scope) ? [{ $match: scope }] : [],
|
|
315
315
|
target: this.columnOf(throughMeta, targetColumn),
|
|
@@ -206,6 +206,10 @@ export declare abstract class AbstractQuerier implements Querier {
|
|
|
206
206
|
* keeping what each does not write, and the parent's other children (a junction's other links) go.
|
|
207
207
|
*/
|
|
208
208
|
private replaceChildren;
|
|
209
|
+
/** A many-to-many's links: the targets are saved, the parent's links to any other go, and the missing ones are added. */
|
|
210
|
+
private replaceLinks;
|
|
211
|
+
/** The rows a parent owns: those it does not list go, and the listed ones are saved pointing at it. */
|
|
212
|
+
private replaceOwned;
|
|
209
213
|
/** Writes each parent's children: rows pointed at their parent, or targets linked through the junction. */
|
|
210
214
|
private saveChildren;
|
|
211
215
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getMeta, idOf, namesKey, relationOf } from '../entity/index.js';
|
|
2
2
|
import { namesRows } from '../dialect/operators.js';
|
|
3
3
|
import { parseQueryLock } from '../type/index.js';
|
|
4
|
-
import { childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, forEachRequestedRelation, getKeys, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey,
|
|
4
|
+
import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, forEachRequestedRelation, getKeys, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keyJoins, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, pointAt, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetJoins, whereEach, whereIds, whereKeysIn, whereWith, withoutSoftDeleteFilter, cascadingRelations, holdsForeignKey, } from '../util/index.js';
|
|
5
5
|
import { UqlOptimisticLockError, UqlUsageError } from '../util/uqlError.js';
|
|
6
6
|
import { keysetRead } from './keyset.js';
|
|
7
7
|
import { enrichError } from './queryError.js';
|
|
@@ -28,10 +28,6 @@ function assertIdValue(entity, id) {
|
|
|
28
28
|
throw new UqlUsageError(`'${entity.name}' is addressed by an object carrying every key of its primary key (${ids.join(', ')}); missing ${missing.join(', ')}.`);
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
|
-
/** The column a write matches a parent's sole key against, on the junction or the child. */
|
|
32
|
-
function soleParentColumn(relOpts) {
|
|
33
|
-
return parentJoins(relOpts, 1)[0].joined;
|
|
34
|
-
}
|
|
35
31
|
/**
|
|
36
32
|
* A bulk write names the rows it changes: a `$where`, or a `$limit` capping how many it reaches. The
|
|
37
33
|
* caller's own clauses are what count - a filter the entity adds, soft delete's, would otherwise make
|
|
@@ -748,11 +744,9 @@ export class AbstractQuerier {
|
|
|
748
744
|
/** Writes each inserted row's children, one set of statements per relation whatever the number of rows. */
|
|
749
745
|
async insertChildren(entity, rows) {
|
|
750
746
|
const meta = getMeta(entity);
|
|
751
|
-
const [idKey] = meta.ids;
|
|
752
747
|
for (const relKey of ownedRelations(meta)) {
|
|
753
|
-
const writes = rows.flatMap((row) => (row[relKey] == null ? [] : [{ id: row
|
|
748
|
+
const writes = rows.flatMap((row) => (row[relKey] == null ? [] : [{ id: idOf(meta, row), value: row[relKey] }]));
|
|
754
749
|
if (writes.length) {
|
|
755
|
-
assertSoleId(meta, 'saving a relation');
|
|
756
750
|
await this.saveChildren(entity, relKey, writes);
|
|
757
751
|
}
|
|
758
752
|
}
|
|
@@ -762,52 +756,63 @@ export class AbstractQuerier {
|
|
|
762
756
|
* keeping what each does not write, and the parent's other children (a junction's other links) go.
|
|
763
757
|
*/
|
|
764
758
|
async replaceChildren(entity, relKey, ids, value) {
|
|
765
|
-
const
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
$where: { [parentColumn]: ids, [targetColumn]: targetIds },
|
|
779
|
-
});
|
|
780
|
-
const has = new Set(linked.map((link) => rowKey(link, [parentColumn, targetColumn])));
|
|
781
|
-
const links = ids.flatMap((id) => targetIds.map((targetId) => ({ [parentColumn]: id, [targetColumn]: targetId })));
|
|
782
|
-
const missing = links.filter((link) => !has.has(rowKey(link, [parentColumn, targetColumn])));
|
|
783
|
-
await this.insertMany(holder, missing);
|
|
759
|
+
const relOpts = relationOf(getMeta(entity), relKey);
|
|
760
|
+
await (relOpts.through
|
|
761
|
+
? this.replaceLinks(entity, relKey, relOpts, relOpts.through(), ids, listedRows(value))
|
|
762
|
+
: this.replaceOwned(entity, relKey, relOpts, ids, value));
|
|
763
|
+
}
|
|
764
|
+
/** A many-to-many's links: the targets are saved, the parent's links to any other go, and the missing ones are added. */
|
|
765
|
+
async replaceLinks(entity, relKey, relOpts, holder, ids, listed) {
|
|
766
|
+
const keyCount = getMeta(entity).ids.length;
|
|
767
|
+
const parents = parentJoins(relOpts, keyCount);
|
|
768
|
+
const targets = targetJoins(relOpts, keyCount);
|
|
769
|
+
const targetIds = await this.saveTargets(entity, relKey, listed);
|
|
770
|
+
await this.writeBatches(ids, keyCount, (batch) => this.deleteMany(holder, { $where: { ...childrenOf(parents, batch), ...(targetIds.length && childrenExcept(targets, targetIds)) } }, { hardDelete: true }));
|
|
771
|
+
if (!targetIds.length) {
|
|
784
772
|
return;
|
|
785
773
|
}
|
|
786
|
-
const
|
|
787
|
-
|
|
774
|
+
const linked = await this.internalFindMany(holder, {
|
|
775
|
+
$where: { $and: [childrenOf(parents, ids), childrenOf(targets, targetIds)] },
|
|
776
|
+
});
|
|
777
|
+
const columns = [...parents, ...targets].map(({ column }) => column);
|
|
778
|
+
const has = new Set(linked.map((link) => rowKey(link, columns)));
|
|
779
|
+
const links = ids.flatMap((id) => targetIds.map((targetId) => ({ ...pointAt(parents, id), ...pointAt(targets, targetId) })));
|
|
780
|
+
await this.insertMany(holder, links.filter((link) => !has.has(rowKey(link, columns))));
|
|
781
|
+
}
|
|
782
|
+
/** The rows a parent owns: those it does not list go, and the listed ones are saved pointing at it. */
|
|
783
|
+
async replaceOwned(entity, relKey, relOpts, ids, value) {
|
|
784
|
+
const keyCount = getMeta(entity).ids.length;
|
|
785
|
+
const relEntity = relOpts.entity();
|
|
786
|
+
const relMeta = getMeta(relEntity);
|
|
787
|
+
const parents = parentJoins(relOpts, keyCount);
|
|
788
|
+
const keptIds = listedRows(value)
|
|
789
|
+
.filter((row) => namesKey(relMeta, row))
|
|
790
|
+
.map((row) => idOf(relMeta, row));
|
|
791
|
+
await this.writeBatches(ids, keyCount, (batch) => this.deleteMany(relEntity, {
|
|
788
792
|
$where: {
|
|
789
|
-
|
|
790
|
-
...(keptIds.length &&
|
|
793
|
+
...childrenOf(parents, batch),
|
|
794
|
+
...(keptIds.length && childrenExcept(keyJoins(relMeta.ids), keptIds)),
|
|
791
795
|
},
|
|
792
796
|
}));
|
|
793
797
|
await this.saveChildren(entity, relKey, ids.map((id) => ({ id, value })));
|
|
794
798
|
}
|
|
795
799
|
/** Writes each parent's children: rows pointed at their parent, or targets linked through the junction. */
|
|
796
800
|
async saveChildren(entity, relKey, writes) {
|
|
797
|
-
const
|
|
798
|
-
const
|
|
801
|
+
const meta = getMeta(entity);
|
|
802
|
+
const relOpts = relationOf(meta, relKey);
|
|
803
|
+
const parents = parentJoins(relOpts, meta.ids.length);
|
|
799
804
|
// Each parent gets its own copies, so a row listed for two parents is written twice.
|
|
800
805
|
const children = writes.flatMap(({ id, value }) => listedRows(value).map((row) => ({ id, row })));
|
|
801
806
|
if (!children.length) {
|
|
802
807
|
return;
|
|
803
808
|
}
|
|
804
809
|
if (!relOpts.through) {
|
|
805
|
-
await this.saveMany(relOpts.entity(), children.map(({ id, row }) => ({ ...row,
|
|
810
|
+
await this.saveMany(relOpts.entity(), children.map(({ id, row }) => ({ ...row, ...pointAt(parents, id) })));
|
|
806
811
|
return;
|
|
807
812
|
}
|
|
808
813
|
const targetIds = await this.saveTargets(entity, relKey, children.map(({ row }) => row));
|
|
809
|
-
const
|
|
810
|
-
await this.insertMany(relOpts.through(), children.map(({ id }, index) => ({
|
|
814
|
+
const targets = targetJoins(relOpts, meta.ids.length);
|
|
815
|
+
await this.insertMany(relOpts.through(), children.map(({ id }, index) => ({ ...pointAt(parents, id), ...pointAt(targets, targetIds[index]) })));
|
|
811
816
|
}
|
|
812
817
|
/**
|
|
813
818
|
* Saves the rows a relation points at, each one's id what the pointer needs: a MySQL batch mixing supplied and
|
|
@@ -11,24 +11,33 @@ export type RelationRequestSummary<E> = {
|
|
|
11
11
|
export declare function isToManyRelation(relation: Pick<RelationMeta, 'cardinality'>): boolean;
|
|
12
12
|
/** Whether the entity declaring the relation holds its foreign key: an owning to-one. */
|
|
13
13
|
export declare function holdsForeignKey(relation: Pick<RelationMeta, 'cardinality' | 'mappedBy'>): boolean;
|
|
14
|
-
/**
|
|
15
|
-
export type
|
|
16
|
-
readonly
|
|
17
|
-
readonly
|
|
14
|
+
/** A key column of the entity a relation starts from or reaches, paired with the column holding it on the table joined. */
|
|
15
|
+
export type KeyJoin = {
|
|
16
|
+
readonly key: string;
|
|
17
|
+
readonly column: string;
|
|
18
18
|
};
|
|
19
19
|
/**
|
|
20
|
-
* How a relation joins its parent, one pair per key: `
|
|
20
|
+
* How a relation joins its parent, one pair per key: `key` a column of the parent's table, `column` the
|
|
21
21
|
* matching one on the table the relation reads, a junction's or the child's.
|
|
22
22
|
*/
|
|
23
|
-
export declare function parentJoins(relOpts: Pick<RelationMeta, 'references' | 'through'>, parentKeyCount: number):
|
|
24
|
-
/** The
|
|
25
|
-
export declare function
|
|
23
|
+
export declare function parentJoins(relOpts: Pick<RelationMeta, 'references' | 'through'>, parentKeyCount: number): KeyJoin[];
|
|
24
|
+
/** The same pairs for the target's key: `key` a key column of the target, `column` the junction column holding it. */
|
|
25
|
+
export declare function targetJoins(relOpts: Pick<RelationMeta, 'references'>, parentKeyCount: number): KeyJoin[];
|
|
26
26
|
/**
|
|
27
|
-
* The
|
|
28
|
-
*
|
|
29
|
-
* would pair values no parent has, and a delete would take a child of a parent that survives.
|
|
27
|
+
* The columns that make a row belong to the key `id` names, one per pair: a sole key's `id` is its value, a
|
|
28
|
+
* composite's the map of every column.
|
|
30
29
|
*/
|
|
31
|
-
export declare function
|
|
30
|
+
export declare function pointAt(joins: readonly KeyJoin[], id: unknown): Record<string, unknown>;
|
|
31
|
+
/** A key's own columns, each paired with itself: the joins of a table to the rows that name it by its own key. */
|
|
32
|
+
export declare function keyJoins(keys: readonly string[]): KeyJoin[];
|
|
33
|
+
/**
|
|
34
|
+
* The `$where` naming exactly the rows the keys `ids` identify: an `IN` over the one column a single key
|
|
35
|
+
* contributes, an OR of whole key maps for several - lists of each column apart would pair values no key
|
|
36
|
+
* has, and a delete would take a row of a key that survives.
|
|
37
|
+
*/
|
|
38
|
+
export declare function childrenOf(joins: readonly KeyJoin[], ids: readonly unknown[]): Record<string, unknown>;
|
|
39
|
+
/** The `$where` naming the rows {@link childrenOf} does not: `NOT IN` over one column, a `$nor` of whole keys for several. */
|
|
40
|
+
export declare function childrenExcept(joins: readonly KeyJoin[], ids: readonly unknown[]): Record<string, unknown>;
|
|
32
41
|
/**
|
|
33
42
|
* What a joined relation cannot carry, and why. A to-many is loaded by a query of its own, which is
|
|
34
43
|
* what gives these four a meaning there; a to-one is one row of the parent's, so every backend used
|
|
@@ -19,34 +19,50 @@ export function holdsForeignKey(relation) {
|
|
|
19
19
|
return !relation.mappedBy && !isToManyRelation(relation);
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
|
-
* How a relation joins its parent, one pair per key: `
|
|
22
|
+
* How a relation joins its parent, one pair per key: `key` a column of the parent's table, `column` the
|
|
23
23
|
* matching one on the table the relation reads, a junction's or the child's.
|
|
24
24
|
*/
|
|
25
25
|
export function parentJoins(relOpts, parentKeyCount) {
|
|
26
26
|
if (!relOpts.through) {
|
|
27
|
-
return relOpts.references.map(({ local, foreign }) => ({
|
|
27
|
+
return relOpts.references.map(({ local, foreign }) => ({ key: local, column: foreign }));
|
|
28
28
|
}
|
|
29
29
|
// A junction's pairs are the parent's followed by the target's, and how many the parent has is
|
|
30
30
|
// something its caller already knows - so the boundary is passed rather than stored on a relation.
|
|
31
|
-
return relOpts.references.slice(0, parentKeyCount).map(({ local, foreign }) => ({
|
|
31
|
+
return relOpts.references.slice(0, parentKeyCount).map(({ local, foreign }) => ({ key: foreign, column: local }));
|
|
32
32
|
}
|
|
33
|
-
/** The
|
|
34
|
-
export function
|
|
35
|
-
return relOpts.references.slice(parentKeyCount).map(({ local }) => local);
|
|
33
|
+
/** The same pairs for the target's key: `key` a key column of the target, `column` the junction column holding it. */
|
|
34
|
+
export function targetJoins(relOpts, parentKeyCount) {
|
|
35
|
+
return relOpts.references.slice(parentKeyCount).map(({ local, foreign }) => ({ key: foreign, column: local }));
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
38
|
-
* The
|
|
39
|
-
*
|
|
40
|
-
* would pair values no parent has, and a delete would take a child of a parent that survives.
|
|
38
|
+
* The columns that make a row belong to the key `id` names, one per pair: a sole key's `id` is its value, a
|
|
39
|
+
* composite's the map of every column.
|
|
41
40
|
*/
|
|
42
|
-
export function
|
|
41
|
+
export function pointAt(joins, id) {
|
|
43
42
|
const [first] = joins;
|
|
44
43
|
if (joins.length === 1) {
|
|
45
|
-
return { [first.
|
|
44
|
+
return { [first.column]: id };
|
|
46
45
|
}
|
|
47
|
-
return {
|
|
48
|
-
|
|
49
|
-
|
|
46
|
+
return Object.fromEntries(joins.map(({ key, column }) => [column, read(id, key)]));
|
|
47
|
+
}
|
|
48
|
+
/** A key's own columns, each paired with itself: the joins of a table to the rows that name it by its own key. */
|
|
49
|
+
export function keyJoins(keys) {
|
|
50
|
+
return keys.map((key) => ({ key, column: key }));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The `$where` naming exactly the rows the keys `ids` identify: an `IN` over the one column a single key
|
|
54
|
+
* contributes, an OR of whole key maps for several - lists of each column apart would pair values no key
|
|
55
|
+
* has, and a delete would take a row of a key that survives.
|
|
56
|
+
*/
|
|
57
|
+
export function childrenOf(joins, ids) {
|
|
58
|
+
return joins.length === 1 ? { [joins[0].column]: ids } : { $or: alternatives(joins, ids) };
|
|
59
|
+
}
|
|
60
|
+
/** The `$where` naming the rows {@link childrenOf} does not: `NOT IN` over one column, a `$nor` of whole keys for several. */
|
|
61
|
+
export function childrenExcept(joins, ids) {
|
|
62
|
+
return joins.length === 1 ? { [joins[0].column]: { $nin: ids } } : { $nor: alternatives(joins, ids) };
|
|
63
|
+
}
|
|
64
|
+
function alternatives(joins, ids) {
|
|
65
|
+
return ids.map((id) => pointAt(joins, id));
|
|
50
66
|
}
|
|
51
67
|
function read(row, key) {
|
|
52
68
|
return row[key];
|
package/package.json
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
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.101.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
|
-
"node": ">=
|
|
9
|
+
"node": ">=22.18"
|
|
10
10
|
},
|
|
11
11
|
"sideEffects": false,
|
|
12
12
|
"main": "./dist/index.js",
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -20,7 +20,9 @@ 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
|
|
23
|
+
ESM only (a CommonJS app loads it through `require(esm)`). Node 22.18+, Bun or an edge runtime, TypeScript 5.7+.
|
|
24
|
+
|
|
25
|
+
UQL's decorators are the TC39 standard: for them, 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`. A project already on legacy decorators (NestJS, Angular) keeps its `tsconfig.json` as it is and defines entities with `defineEntity` instead: one config cannot compile both decorator specs. NestJS: https://uql-orm.dev/nestjs.md
|
|
24
26
|
|
|
25
27
|
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
28
|
|