uql-orm 0.100.3 → 0.101.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 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 24+, 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.
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 naming each row's target.
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, soleIdOf } from '../entity/index.js';
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, targetKeyColumns, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, raw, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.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, 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
- const targetKey = soleIdOf(relatedMeta, 'a many-to-many target');
1839
- ctx.append(` AND ${junction.target} IN (`);
1840
- ctx.append(`SELECT ${this.escapedColumn(related.alias, relatedMeta, targetKey)} FROM ${related.ref}`);
1841
- this.renderWhere(ctx, relatedEntity, targetWhere, { prefix: related.alias, clause: 'WHERE' });
1842
- ctx.append(')');
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(({ parent: key, joined }) => `${this.escapedColumn(alias, joinedMeta, joined)} = ${escapedParent}${this.escapedColumnName(meta, key)}`)
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
- const targetKey = soleIdOf(relMeta, 'a many-to-many target');
1998
- ctx.append(`${this.escapedColumn(alias, relMeta, targetKey)} IN (SELECT ${junction.target} FROM ${junction.from})`);
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 naming each row's target.
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
- target: this.escapedColumn(alias, junctionMeta, target),
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 yet.`
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
  }
@@ -1,4 +1,4 @@
1
- export * from './contract.js';
1
+ export { CRUD_ROUTES, type CrudOperation, type CrudRoute, entityPath, type HttpMethod, type RequestErrorResponse, toErrorResponse, } from './contract.js';
2
2
  export * from './fetchHandler.js';
3
3
  export * from './handler.js';
4
- export * from './query.js';
4
+ export type { WireCursors, WireFlags } from './query.js';
@@ -1,4 +1,3 @@
1
- export * from './contract.js';
1
+ export { CRUD_ROUTES, entityPath, toErrorResponse, } from './contract.js';
2
2
  export * from './fetchHandler.js';
3
3
  export * from './handler.js';
4
- export * from './query.js';
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 * from './type/index.js';
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,2 +1,2 @@
1
- export * from './libsqlDialect.js';
1
+ export { LibsqlDialect } from './libsqlDialect.js';
2
2
  export * from './libsqlQuerierPool.js';
@@ -1,2 +1,2 @@
1
- export * from './libsqlDialect.js';
1
+ export { LibsqlDialect } from './libsqlDialect.js';
2
2
  export * from './libsqlQuerierPool.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 `tsx/esm/api` where Node must load a TypeScript config: Node's type stripping runs
5
- * no decorators, and Bun transforms them natively. uql bundles no transpiler, so the project's
6
- * loader reads the project's `tsconfig.json`. Registered for the process, never imported through: an
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 `tsx/esm/api` where Node must load a TypeScript config: Node's type stripping runs
8
- * no decorators, and Bun transforms them natively. uql bundles no transpiler, so the project's
9
- * loader reads the project's `tsconfig.json`. Registered for the process, never imported through: an
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
- return createRequire(path).resolve('tsx/esm/api');
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;
@@ -1,14 +1,11 @@
1
- export type { Change, ColumnSchema, DialectName, ForeignKeySchema, IndexSchema, Migration, MigrationDefinition, MigrationResult, MigratorOptions, PrimaryKeySchema, SchemaDiff, SchemaGenerator, SchemaIntrospector, SqlDialectName, SqlQuerier, SqlQueryDialect, SyncOptions, TableSchema, } from '../type/index.js';
2
- export { type Config, isSqlQuerier } from '../type/index.js';
3
- export { acquireQuerierForMigrations } from './acquireQuerierForMigrations.js';
4
- export { assertCliConfig } from './assertCliConfig.js';
1
+ export type { Change, ColumnSchema, Config, DialectName, ForeignKeySchema, IndexSchema, Migration, MigrationDefinition, MigrationResult, MigratorOptions, PrimaryKeySchema, SchemaDiff, SchemaGenerator, SchemaIntrospector, SqlDialectName, SqlQuerier, SqlQueryDialect, SyncOptions, TableSchema, } from '../type/index.js';
5
2
  export * from './builder/index.js';
6
- export { loadConfig } from './cli-config.js';
7
- export * from './codegen/index.js';
8
- export * from './ddl/index.js';
9
- export * from './drift/index.js';
10
- export * from './introspection/index.js';
11
- export { migrationBuilderFor } from './migrationTarget.js';
3
+ export { EntityCodeGenerator, type EntityCodeGeneratorOptions, type GeneratedEntity, } from './codegen/entityCodeGenerator.js';
4
+ export { buildMigrationModule, type MigrationModuleOptions, type MigrationQuerierType, } from './codegen/migrationFile.js';
5
+ export { AbstractSqlSchemaIntrospector } from './introspection/abstractSqlSchemaIntrospector.js';
6
+ export { MsSqlSchemaIntrospector } from './introspection/mssqlIntrospector.js';
7
+ export { MariadbSchemaIntrospector, MysqlSchemaIntrospector } from './introspection/mysqlIntrospector.js';
8
+ export { CockroachSchemaIntrospector, PostgresSchemaIntrospector } from './introspection/postgresIntrospector.js';
9
+ export { SqliteSchemaIntrospector } from './introspection/sqliteIntrospector.js';
12
10
  export { type BuilderMigrationDefinition, defineBuilderMigration, defineMigration, Migrator } from './migrator.js';
13
- export { reverseDiff } from './schemaChange.js';
14
11
  export { SqlSchemaGenerator } from './schemaGenerator.js';
@@ -1,20 +1,10 @@
1
- export { isSqlQuerier } from '../type/index.js';
2
- export { acquireQuerierForMigrations } from './acquireQuerierForMigrations.js';
3
- export { assertCliConfig } from './assertCliConfig.js';
4
- // Type-safe migration builder
5
1
  export * from './builder/index.js';
6
- export { loadConfig } from './cli-config.js';
7
- // Entity code generation
8
- export * from './codegen/index.js';
9
- // Index and table DDL, per dialect family
10
- export * from './ddl/index.js';
11
- // Drift detection
12
- export * from './drift/index.js';
13
- // Schema introspection
14
- export * from './introspection/index.js';
15
- // Main migrator
16
- export { migrationBuilderFor } from './migrationTarget.js';
2
+ export { EntityCodeGenerator, } from './codegen/entityCodeGenerator.js';
3
+ export { buildMigrationModule, } from './codegen/migrationFile.js';
4
+ export { AbstractSqlSchemaIntrospector } from './introspection/abstractSqlSchemaIntrospector.js';
5
+ export { MsSqlSchemaIntrospector } from './introspection/mssqlIntrospector.js';
6
+ export { MariadbSchemaIntrospector, MysqlSchemaIntrospector } from './introspection/mysqlIntrospector.js';
7
+ export { CockroachSchemaIntrospector, PostgresSchemaIntrospector } from './introspection/postgresIntrospector.js';
8
+ export { SqliteSchemaIntrospector } from './introspection/sqliteIntrospector.js';
17
9
  export { defineBuilderMigration, defineMigration, Migrator } from './migrator.js';
18
- // Schema generators
19
- export { reverseDiff } from './schemaChange.js';
20
10
  export { SqlSchemaGenerator } from './schemaGenerator.js';
@@ -1,4 +1,4 @@
1
- export * from './mongoDialect.js';
1
+ export { MongoDialect } from './mongoDialect.js';
2
2
  export * from './mongodbQuerier.js';
3
3
  export * from './mongodbQuerierPool.js';
4
4
  export * from './mongoIntrospector.js';
@@ -1,4 +1,4 @@
1
- export * from './mongoDialect.js';
1
+ export { MongoDialect } from './mongoDialect.js';
2
2
  export * from './mongodbQuerier.js';
3
3
  export * from './mongodbQuerierPool.js';
4
4
  export * from './mongoIntrospector.js';
@@ -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, targetKeyColumns, textSortOf, vectorDistanceOf, } from '../util/index.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, 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] = targetKeyColumns(relOpts, meta.ids.length);
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.joined),
312
+ foreignField: this.columnOf(throughMeta, parentJoin.column),
313
313
  },
314
314
  scope: hasKeys(scope) ? [{ $match: scope }] : [],
315
315
  target: this.columnOf(throughMeta, targetColumn),
@@ -1,6 +1,7 @@
1
1
  import type { ClientSession, Document, MongoClient } from 'mongodb';
2
+ import type { UpsertedId } from '../querier/abstractQuerier.js';
2
3
  import { AbstractQuerier } from '../querier/index.js';
3
- import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
4
+ import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
4
5
  import type { MongoDialect } from './mongoDialect.js';
5
6
  import type { MongoQuerier } from './mongoQuerier.js';
6
7
  export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
@@ -61,7 +62,7 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
61
62
  * a concurrent one included, then takes `update`.
62
63
  */
63
64
  private upsertWithUpdate;
64
- protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(PrimaryKey | undefined)[]>;
65
+ protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[]>;
65
66
  protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
66
67
  get hasOpenTransaction(): boolean;
67
68
  /** Every read and write goes through here, which makes it where a released querier is caught. */
@@ -1,3 +1,3 @@
1
1
  export * from './pgQuerier.js';
2
2
  export * from './pgQuerierPool.js';
3
- export * from './postgresDialect.js';
3
+ export { PostgresDialect } from './postgresDialect.js';
@@ -1,3 +1,3 @@
1
1
  export * from './pgQuerier.js';
2
2
  export * from './pgQuerierPool.js';
3
- export * from './postgresDialect.js';
3
+ export { PostgresDialect } from './postgresDialect.js';
@@ -1,7 +1,14 @@
1
1
  import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
- import type { BooleanLike, CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, RelationKey, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, ReturningResult, WriteOptions, WrittenId } from '../type/index.js';
2
+ import type { BooleanLike, CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, RelationKey, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, ReturningResult, WriteOptions, PrimaryKey, WrittenId } from '../type/index.js';
3
3
  import { LoggerWrapper } from '../util/index.js';
4
4
  import { type TransactionScope } from './transaction.js';
5
+ /**
6
+ * Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
7
+ * value was never written to a row the upsert updated. A report aligns with the rows only when it
8
+ * speaks for every one: a `firstId` dialect reports nothing for a batch.
9
+ */
10
+ /** What an upsert reports of a row: the value a driver answers for a lone key, or the key the read back names. */
11
+ export type UpsertedId<E> = PrimaryKey | WrittenId<E>;
5
12
  /** Base class for all database queriers. */
6
13
  export declare abstract class AbstractQuerier implements Querier {
7
14
  #private;
@@ -174,7 +181,7 @@ export declare abstract class AbstractQuerier implements Querier {
174
181
  */
175
182
  private readThenUpsert;
176
183
  /** Upserts `payload`, answering each row's key in payload order where the engine reports every one. */
177
- protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(PrimaryKey | undefined)[] | undefined>;
184
+ protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[] | undefined>;
178
185
  deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
179
186
  /** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
180
187
  deleteMany<E extends object>(q: QuerySearch<E> & {
@@ -206,6 +213,10 @@ export declare abstract class AbstractQuerier implements Querier {
206
213
  * keeping what each does not write, and the parent's other children (a junction's other links) go.
207
214
  */
208
215
  private replaceChildren;
216
+ /** A many-to-many's links: the targets are saved, the parent's links to any other go, and the missing ones are added. */
217
+ private replaceLinks;
218
+ /** The rows a parent owns: those it does not list go, and the listed ones are saved pointing at it. */
219
+ private replaceOwned;
209
220
  /** Writes each parent's children: rows pointed at their parent, or targets linked through the junction. */
210
221
  private saveChildren;
211
222
  /**
@@ -274,7 +285,7 @@ export declare abstract class AbstractQuerier implements Querier {
274
285
  * statement that could not report them in payload order, or before a guarded upsert. A row that no
275
286
  * read row matches, or that two do, keeps `undefined`: a missing id is honest where a guessed one is not.
276
287
  */
277
- protected idsByConflict<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, rows: EntityData<E>[]): Promise<(PrimaryKey | undefined)[]>;
288
+ protected idsByConflict<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, rows: EntityData<E>[]): Promise<(WrittenId<E> | undefined)[]>;
278
289
  /**
279
290
  * Runs `write` between the event's `before`/`after` pair. The before hooks get the caller's rows, so
280
291
  * what they assign is written; `write` and the after hooks get a copy, which by then carries what
@@ -1,7 +1,7 @@
1
- import { assertSoleId, getMeta, idOf, namesKey, relationOf, soleIdOf } from '../entity/index.js';
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, targetKeyColumns, whereEach, whereIds, whereKeysIn, whereWith, withoutSoftDeleteFilter, cascadingRelations, holdsForeignKey, } from '../util/index.js';
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
@@ -103,19 +99,20 @@ function conflictAssignments(row, conflictPaths) {
103
99
  }
104
100
  return assigned;
105
101
  }
106
- /**
107
- * Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
108
- * value was never written to a row the upsert updated. A report aligns with the rows only when it
109
- * speaks for every one: a `firstId` dialect reports nothing for a batch.
110
- */
111
102
  function adoptReportedIds(meta, rows, reported) {
112
- if (meta.ids.length !== 1 || reported?.length !== rows.length) {
103
+ if (reported?.length !== rows.length) {
113
104
  return;
114
105
  }
115
106
  const [idKey] = meta.ids;
116
- for (let index = 0; index < rows.length; index++) {
117
- rows[index][idKey] ??= reported[index];
118
- }
107
+ rows.forEach((row, index) => {
108
+ const id = reported[index];
109
+ if (meta.ids.length > 1) {
110
+ Object.assign(row, id);
111
+ }
112
+ else {
113
+ row[idKey] ??= id;
114
+ }
115
+ });
119
116
  }
120
117
  /** Normalizes either call form to `[entity, query, opts]`, throwing when a query object has no `$entity`. */
121
118
  function entityArgs(args) {
@@ -748,11 +745,9 @@ export class AbstractQuerier {
748
745
  /** Writes each inserted row's children, one set of statements per relation whatever the number of rows. */
749
746
  async insertChildren(entity, rows) {
750
747
  const meta = getMeta(entity);
751
- const [idKey] = meta.ids;
752
748
  for (const relKey of ownedRelations(meta)) {
753
- const writes = rows.flatMap((row) => (row[relKey] == null ? [] : [{ id: row[idKey], value: row[relKey] }]));
749
+ const writes = rows.flatMap((row) => (row[relKey] == null ? [] : [{ id: idOf(meta, row), value: row[relKey] }]));
754
750
  if (writes.length) {
755
- assertSoleId(meta, 'saving a relation');
756
751
  await this.saveChildren(entity, relKey, writes);
757
752
  }
758
753
  }
@@ -762,52 +757,63 @@ export class AbstractQuerier {
762
757
  * keeping what each does not write, and the parent's other children (a junction's other links) go.
763
758
  */
764
759
  async replaceChildren(entity, relKey, ids, value) {
765
- const meta = getMeta(entity);
766
- assertSoleId(meta, 'saving a relation');
767
- const relOpts = relationOf(meta, relKey);
768
- const relEntity = relOpts.entity();
769
- const relMeta = getMeta(relEntity);
770
- const parentColumn = soleParentColumn(relOpts);
771
- const listed = listedRows(value);
772
- if (relOpts.through) {
773
- const holder = relOpts.through();
774
- const [targetColumn] = targetKeyColumns(relOpts, 1);
775
- const targetIds = await this.saveTargets(entity, relKey, listed);
776
- await this.writeBatches(ids, 1, (batch) => this.deleteMany(holder, { $where: { [parentColumn]: batch, ...(targetIds.length && { [targetColumn]: { $nin: targetIds } }) } }, { hardDelete: true }));
777
- const linked = await this.internalFindMany(holder, {
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);
760
+ const relOpts = relationOf(getMeta(entity), relKey);
761
+ await (relOpts.through
762
+ ? this.replaceLinks(entity, relKey, relOpts, relOpts.through(), ids, listedRows(value))
763
+ : this.replaceOwned(entity, relKey, relOpts, ids, value));
764
+ }
765
+ /** A many-to-many's links: the targets are saved, the parent's links to any other go, and the missing ones are added. */
766
+ async replaceLinks(entity, relKey, relOpts, holder, ids, listed) {
767
+ const keyCount = getMeta(entity).ids.length;
768
+ const parents = parentJoins(relOpts, keyCount);
769
+ const targets = targetJoins(relOpts, keyCount);
770
+ const targetIds = await this.saveTargets(entity, relKey, listed);
771
+ await this.writeBatches(ids, keyCount, (batch) => this.deleteMany(holder, { $where: { ...childrenOf(parents, batch), ...(targetIds.length && childrenExcept(targets, targetIds)) } }, { hardDelete: true }));
772
+ if (!targetIds.length) {
784
773
  return;
785
774
  }
786
- const keptIds = listed.filter((row) => namesKey(relMeta, row)).map((row) => idOf(relMeta, row));
787
- await this.writeBatches(ids, 1, (batch) => this.deleteMany(relEntity, {
775
+ const linked = await this.internalFindMany(holder, {
776
+ $where: { $and: [childrenOf(parents, ids), childrenOf(targets, targetIds)] },
777
+ });
778
+ const columns = [...parents, ...targets].map(({ column }) => column);
779
+ const has = new Set(linked.map((link) => rowKey(link, columns)));
780
+ const links = ids.flatMap((id) => targetIds.map((targetId) => ({ ...pointAt(parents, id), ...pointAt(targets, targetId) })));
781
+ await this.insertMany(holder, links.filter((link) => !has.has(rowKey(link, columns))));
782
+ }
783
+ /** The rows a parent owns: those it does not list go, and the listed ones are saved pointing at it. */
784
+ async replaceOwned(entity, relKey, relOpts, ids, value) {
785
+ const keyCount = getMeta(entity).ids.length;
786
+ const relEntity = relOpts.entity();
787
+ const relMeta = getMeta(relEntity);
788
+ const parents = parentJoins(relOpts, keyCount);
789
+ const keptIds = listedRows(value)
790
+ .filter((row) => namesKey(relMeta, row))
791
+ .map((row) => idOf(relMeta, row));
792
+ await this.writeBatches(ids, keyCount, (batch) => this.deleteMany(relEntity, {
788
793
  $where: {
789
- [parentColumn]: batch,
790
- ...(keptIds.length && { [soleIdOf(relMeta, 'replacing the rows of a relation')]: { $nin: keptIds } }),
794
+ ...childrenOf(parents, batch),
795
+ ...(keptIds.length && childrenExcept(keyJoins(relMeta.ids), keptIds)),
791
796
  },
792
797
  }));
793
798
  await this.saveChildren(entity, relKey, ids.map((id) => ({ id, value })));
794
799
  }
795
800
  /** Writes each parent's children: rows pointed at their parent, or targets linked through the junction. */
796
801
  async saveChildren(entity, relKey, writes) {
797
- const relOpts = relationOf(getMeta(entity), relKey);
798
- const parentColumn = soleParentColumn(relOpts);
802
+ const meta = getMeta(entity);
803
+ const relOpts = relationOf(meta, relKey);
804
+ const parents = parentJoins(relOpts, meta.ids.length);
799
805
  // Each parent gets its own copies, so a row listed for two parents is written twice.
800
806
  const children = writes.flatMap(({ id, value }) => listedRows(value).map((row) => ({ id, row })));
801
807
  if (!children.length) {
802
808
  return;
803
809
  }
804
810
  if (!relOpts.through) {
805
- await this.saveMany(relOpts.entity(), children.map(({ id, row }) => ({ ...row, [parentColumn]: id })));
811
+ await this.saveMany(relOpts.entity(), children.map(({ id, row }) => ({ ...row, ...pointAt(parents, id) })));
806
812
  return;
807
813
  }
808
814
  const targetIds = await this.saveTargets(entity, relKey, children.map(({ row }) => row));
809
- const [targetColumn] = targetKeyColumns(relOpts, 1);
810
- await this.insertMany(relOpts.through(), children.map(({ id }, index) => ({ [parentColumn]: id, [targetColumn]: targetIds[index] })));
815
+ const targets = targetJoins(relOpts, meta.ids.length);
816
+ await this.insertMany(relOpts.through(), children.map(({ id }, index) => ({ ...pointAt(parents, id), ...pointAt(targets, targetIds[index]) })));
811
817
  }
812
818
  /**
813
819
  * Saves the rows a relation points at, each one's id what the pointer needs: a MySQL batch mixing supplied and
@@ -1011,20 +1017,19 @@ export class AbstractQuerier {
1011
1017
  */
1012
1018
  async idsByConflict(entity, conflictPaths, rows) {
1013
1019
  const meta = getMeta(entity);
1014
- const [idKey] = meta.ids;
1015
1020
  const keys = getKeys(conflictPaths);
1016
1021
  // A null key never conflicts, so no row is read back for it, whether one key names the row or several.
1017
1022
  const named = rows.filter((row) => keys.every((key) => row[key] != null));
1018
1023
  const distinct = [...new Map(named.map((row) => [rowKey(row, keys), row])).values()];
1019
1024
  const found = [];
1020
1025
  for (const batch of chunk(distinct, this.dialect.keyListCapacity(keys.length))) {
1021
- const q = { $select: keySet([idKey, ...keys]), $where: whereKeysIn(keys, batch) };
1026
+ const q = { $select: keySet([...meta.ids, ...keys]), $where: whereKeysIn(keys, batch) };
1022
1027
  found.push(await this.internalFindMany(entity, q, { filters: withoutSoftDeleteFilter(undefined) }));
1023
1028
  }
1024
1029
  const byConflict = new Map();
1025
1030
  for (const row of found.flat()) {
1026
1031
  const key = rowKey(row, keys);
1027
- byConflict.set(key, byConflict.has(key) ? undefined : row[idKey]);
1032
+ byConflict.set(key, byConflict.has(key) ? undefined : idOf(meta, row));
1028
1033
  }
1029
1034
  return rows.map((row) => byConflict.get(rowKey(row, keys)));
1030
1035
  }
@@ -1,7 +1,7 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, PrimaryKey, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
2
+ import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
3
3
  import type { BuildUpdateResultPayload } from '../util/sql.util.js';
4
- import { AbstractQuerier } from './abstractQuerier.js';
4
+ import { AbstractQuerier, type UpsertedId } from './abstractQuerier.js';
5
5
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
6
6
  #private;
7
7
  readonly dialect: AbstractSqlDialect;
@@ -83,7 +83,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
83
83
  protected internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
84
84
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
85
85
  internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
86
- protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(PrimaryKey | undefined)[] | undefined>;
86
+ protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[] | undefined>;
87
87
  private runUpsert;
88
88
  protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
89
89
  protected openTransaction(opts?: TransactionOptions): Promise<void>;
@@ -313,11 +313,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
313
313
  async runUpsert(entity, conflictPaths, payload, update) {
314
314
  const meta = getMeta(entity);
315
315
  // Asked first: the statement fills an `onInsert` key into these rows whether it inserts them or not.
316
- const unnamed = meta.ids.length === 1 && payload.some((row) => !namesKey(meta, row));
316
+ const unnamed = payload.some((row) => !namesKey(meta, row));
317
317
  const { ids } = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload, update));
318
318
  const ordered = payload.length === 1 ||
319
319
  (this.dialect.insertIdSource === 'returning' && this.dialect.features.orderedUpsertReturning);
320
- if (ordered && ids?.length === payload.length) {
320
+ if (meta.ids.length === 1 && ordered && ids?.length === payload.length) {
321
321
  return ids;
322
322
  }
323
323
  // The statement's ids name its rows only in order and for every one. A MySQL batch reports a
@@ -1,6 +1,6 @@
1
1
  export * from './abstractSqliteQuerier.js';
2
2
  export * from './hranaQuerier.js';
3
3
  export * from './nodeSqliteQuerierPool.js';
4
- export * from './sqliteDialect.js';
4
+ export { SqliteDialect } from './sqliteDialect.js';
5
5
  export * from './sqliteQuerier.js';
6
6
  export * from './sqliteQuerierPool.js';
@@ -1,6 +1,6 @@
1
1
  export * from './abstractSqliteQuerier.js';
2
2
  export * from './hranaQuerier.js';
3
3
  export * from './nodeSqliteQuerierPool.js';
4
- export * from './sqliteDialect.js';
4
+ export { SqliteDialect } from './sqliteDialect.js';
5
5
  export * from './sqliteQuerier.js';
6
6
  export * from './sqliteQuerierPool.js';
@@ -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
- /** One column of a parent's key, paired with the column matching it on the table being joined. */
15
- export type ParentJoin = {
16
- readonly parent: string;
17
- readonly joined: string;
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: `parent` a column of the parent's table, `joined` the
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): ParentJoin[];
24
- /** The junction columns holding the target's key, after the parent's `parentKeyCount` ones. */
25
- export declare function targetKeyColumns(relOpts: Pick<RelationMeta, 'references'>, parentKeyCount: number): string[];
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 `$where` naming exactly the children of the rows `parentIds` identifies: an `IN` over the one
28
- * column a single key contributes, an OR of whole key maps for several - lists of each column apart
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 childrenOf(joins: readonly ParentJoin[], parentIds: readonly unknown[]): Record<string, unknown>;
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: `parent` a column of the parent's table, `joined` the
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 }) => ({ parent: local, joined: 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 }) => ({ parent: foreign, joined: local }));
31
+ return relOpts.references.slice(0, parentKeyCount).map(({ local, foreign }) => ({ key: foreign, column: local }));
32
32
  }
33
- /** The junction columns holding the target's key, after the parent's `parentKeyCount` ones. */
34
- export function targetKeyColumns(relOpts, parentKeyCount) {
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 `$where` naming exactly the children of the rows `parentIds` identifies: an `IN` over the one
39
- * column a single key contributes, an OR of whole key maps for several - lists of each column apart
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 childrenOf(joins, parentIds) {
41
+ export function pointAt(joins, id) {
43
42
  const [first] = joins;
44
43
  if (joins.length === 1) {
45
- return { [first.joined]: parentIds };
44
+ return { [first.column]: id };
46
45
  }
47
- return {
48
- $or: parentIds.map((id) => Object.fromEntries(joins.map(({ parent, joined }) => [joined, read(id, parent)]))),
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.100.3",
6
+ "version": "0.101.1",
7
7
  "type": "module",
8
8
  "engines": {
9
- "node": ">=24"
9
+ "node": ">=22.18"
10
10
  },
11
11
  "sideEffects": false,
12
12
  "main": "./dist/index.js",
@@ -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 24+, Bun 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`.
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