uql-orm 0.106.1 → 0.107.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.
Files changed (32) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/uql-browser.min.js.map +1 -1
  3. package/dist/dialect/abstractSqlDialect.js +3 -3
  4. package/dist/entity/decorator/bag.d.ts +1 -1
  5. package/dist/entity/metadata/{schemaFixture → definedFixture}/animal.d.ts +2 -2
  6. package/dist/entity/metadata/{schemaFixture → definedFixture}/author.d.ts +2 -2
  7. package/dist/entity/metadata/{schemaFixture → definedFixture}/book.d.ts +4 -4
  8. package/dist/entity/metadata/definition.d.ts +18 -8
  9. package/dist/entity/metadata/definition.js +59 -38
  10. package/dist/migrate/codegen/fieldOptionsSource.js +8 -1
  11. package/dist/mongodb/mongoDialect.d.ts +0 -1
  12. package/dist/mongodb/mongoDialect.js +4 -7
  13. package/dist/mssql/mssqlDialect.js +5 -5
  14. package/dist/querier/abstractSqlQuerier.js +3 -3
  15. package/dist/schema/declaredColumn.d.ts +1 -1
  16. package/dist/schema/declaredColumn.js +1 -1
  17. package/dist/schema/schemaASTBuilder.js +3 -3
  18. package/dist/sqlite/sqliteQuerier.d.ts +1 -1
  19. package/dist/type/column.d.ts +3 -3
  20. package/dist/type/{schemaEntity.d.ts → definedEntity.d.ts} +45 -45
  21. package/dist/type/entity.d.ts +9 -7
  22. package/dist/type/index.d.ts +1 -1
  23. package/dist/type/index.js +1 -1
  24. package/dist/type/query.d.ts +1 -1
  25. package/dist/util/field.util.d.ts +4 -6
  26. package/dist/util/field.util.js +5 -9
  27. package/package.json +7 -7
  28. package/skills/uql-orm/SKILL.md +42 -6
  29. /package/dist/entity/metadata/{schemaFixture → definedFixture}/animal.js +0 -0
  30. /package/dist/entity/metadata/{schemaFixture → definedFixture}/author.js +0 -0
  31. /package/dist/entity/metadata/{schemaFixture → definedFixture}/book.js +0 -0
  32. /package/dist/type/{schemaEntity.js → definedEntity.js} +0 -0
package/README.md CHANGED
@@ -33,7 +33,7 @@
33
33
  npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @tursodatabase/serverless, @libsql/client
34
34
  ```
35
35
 
36
- That is the whole install ([setup](https://uql-orm.dev/getting-started)). No compiler flags and no `reflect-metadata`; the decorators are the [TC39 standard spec](https://uql-orm.dev/entities/basic), and an entity can be declared as data instead, its row type derived, via [`defineEntity`](https://uql-orm.dev/entities/imperative).
36
+ That is the whole install ([setup](https://uql-orm.dev/getting-started)). No compiler flags and no `reflect-metadata`; the decorators are the [TC39 standard spec](https://uql-orm.dev/entities/basic), and an entity can be declared as data instead, its row type derived, via [`defineEntity`](https://uql-orm.dev/entities/define-entity).
37
37
 
38
38
  <a href="https://uql-orm.dev">
39
39
  <picture>
@@ -154,7 +154,7 @@ Follow the [Quick Start](https://uql-orm.dev/getting-started), or [switch from](
154
154
 
155
155
  Using a coding agent? The package ships a [skill](skills/uql-orm/SKILL.md) for it, and every docs page is Markdown: [set it up](https://uql-orm.dev/ai-agents).
156
156
 
157
- Release notes live in [CHANGELOG.md](https://github.com/rogerpadilla/uql/blob/main/CHANGELOG.md).
157
+ Release notes live in [CHANGELOG.md](https://github.com/rogerpadilla/uql/blob/main/CHANGELOG.md), and the build order for what comes next in [architecture/roadmap.md](architecture/roadmap.md).
158
158
 
159
159
  ---
160
160
 
@@ -3,7 +3,7 @@
3
3
  "sources": ["../../src/browser/http/bus.ts", "../../src/type/query.ts", "../../src/type/querySql.ts", "../../src/util/object.util.ts", "../../src/util/uqlError.ts", "../../src/http/query.ts", "../../src/browser/http/http.ts", "../../src/util/string.util.ts", "../../src/http/contract.ts", "../../src/browser/querier/httpQuerier.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors = new Set<RequestCallback>();\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.add(cb);\n return (): void => {\n subscriptors.delete(cb);\n };\n}\n",
6
- "import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/**\n * query conflict paths - subset of field keys used to detect upsert conflicts.\n */\nexport type QueryConflictPaths<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and a schema's `filters`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * read in the same transaction after the write (before it, for a delete), so they hold what the database filled.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike> = {\n readonly returning?: QuerySelect<E, S, V>;\n};\n\n/** What each kind of write resolves to: its ids or its count where it names no `returning` field, else the rows it reads back. */\nexport type WriteResults<E, S, V> = [S] extends [never]\n ? {\n readonly inserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n }\n : {\n readonly inserted: ReturnedRow<E, S, V>;\n readonly affected: ReturnedRow<E, S, V> | undefined;\n readonly affectedMany: ReturnedRow<E, S, V>[];\n };\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
6
+ "import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/**\n * query conflict paths - subset of field keys used to detect upsert conflicts.\n */\nexport type QueryConflictPaths<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * read in the same transaction after the write (before it, for a delete), so they hold what the database filled.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike> = {\n readonly returning?: QuerySelect<E, S, V>;\n};\n\n/** What each kind of write resolves to: its ids or its count where it names no `returning` field, else the rows it reads back. */\nexport type WriteResults<E, S, V> = [S] extends [never]\n ? {\n readonly inserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n }\n : {\n readonly inserted: ReturnedRow<E, S, V>;\n readonly affected: ReturnedRow<E, S, V> | undefined;\n readonly affectedMany: ReturnedRow<E, S, V>[];\n };\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
7
7
  "import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, AbstractType } from './utility.js';\n\n/** What a `sql` callback receives. See {@link QuerySqlFn}. */\nexport type QuerySqlRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: AbstractType<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QuerySqlRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QuerySqlFnOptions = Partial<QuerySqlRenderOptions>;\n\n/**\n * A `sql` callback: write into `ctx`, or return a string or number to have it appended. Anything else\n * it returns is ignored, which is why the return type is `unknown` rather than `void | Scalar` - the\n * latter rejected `({ ctx }) => ctx.append(...)`, the form every computed field is written in, because\n * TypeScript's \"returning a value where void is expected\" allowance does not apply to a union.\n */\nexport type QuerySqlFn = (opts: QuerySqlRenderOptions) => unknown;\n\nexport const SQL_FN: unique symbol = Symbol('sqlFn');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const SQL_TEXT: unique symbol = Symbol('sqlText');\n/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */\nexport const SQL_VALUE_TYPE: unique symbol = Symbol('sqlValueType');\n/** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */\nexport const REF_KEY: unique symbol = Symbol('refKey');\n/** The dotted path a {@link JsonPathRef} reads down its column's document. */\nexport const JSON_PATH: unique symbol = Symbol('jsonPath');\n/** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */\nexport const JSON_VALUE: unique symbol = Symbol('jsonValue');\n\n/**\n * What a `sql` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type SqlArg = Scalar | null | readonly (Scalar | null)[] | QuerySql;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `sql` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: SqlArg[]] | readonly [sql: QuerySql];\n\nexport class QuerySql {\n readonly [SQL_FN]: QuerySqlFn;\n readonly [RAW_ALIAS]?: string;\n /**\n * The SQL verbatim, set only where it is a constant: a template that interpolates nothing binds no\n * value and reads no column, so it needs no dialect to render. What a DDL clause with nowhere to\n * bind reads - see {@link constantSql}.\n */\n readonly [SQL_TEXT]?: string;\n\n constructor(value: QuerySqlFn, { alias, text }: { readonly alias?: string; readonly text?: string } = {}) {\n this[SQL_FN] = value;\n this[RAW_ALIAS] = alias;\n this[SQL_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QuerySql {\n return new QuerySql(this[SQL_FN], { alias, text: this[SQL_TEXT] });\n }\n}\n\n/** Writes `statement` into `opts.ctx`. The alias is the projection's to write, after the term. */\nexport function renderSql(statement: QuerySql, opts: QuerySqlRenderOptions): void {\n const emitted = statement[SQL_FN](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `sql`, it\n * renders as the field's column. Its key is how an index tells a column from an expression, and `V`,\n * the field's type, is what a value slot checks it against: see {@link SqlFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n readonly [REF_KEY]: K;\n\n constructor(key: K, value: QuerySqlFn) {\n super(value);\n this[REF_KEY] = key;\n }\n}\n\n/**\n * A path inside a JSON column, read off an index's refs as the `$where` key it is: `user.settings.theme`\n * for `'settings.theme'`. `V`, the value at the path, decides how the index has to read it.\n */\nexport class JsonPathRef<V = unknown> {\n declare readonly [JSON_VALUE]?: V;\n readonly [REF_KEY]: string;\n readonly [JSON_PATH]: string;\n\n constructor(key: string, path: string) {\n this[REF_KEY] = key;\n this[JSON_PATH] = path;\n }\n}\n\n/**\n * SQL where a value of type `V` goes: bare SQL, whose type is its author's to know, or a ref to a column\n * holding one, nullability aside. `Sql` is what the transport carries, so the wire's `never` stays one.\n */\nexport type SqlFor<Sql, V> = Sql & { readonly [SQL_VALUE_TYPE]?: V | null };\n\n/**\n * A relation aggregate as SQL, read off a `computed` field's refs: `(user) => user.resources.count()`.\n * It renders as the correlated subquery a `$count` reads, so a field holding one is read, filtered and\n * sorted like any other.\n *\n * `V` is the value it reads, carried in a phantom field so the aggregate a field declares decides the\n * property's type.\n */\nexport class RelationAggregate<V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n\n constructor(\n /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */\n readonly spec: RelationAggregateSpec,\n value: QuerySqlFn,\n ) {\n super(value);\n }\n}\n\n/**\n * A write `insertInto`, `updateTable` or `deleteFrom` renders, or several joined in one `sql`. It reads a\n * set-based trigger's rows through {@link QuerySqlRenderOptions.rows}, which is how `of` and `where` narrow\n * them there; SQL of its own reads `inserted` and `deleted` whole.\n */\nexport class TriggerWriteSql extends QuerySql {}\n",
8
8
  "import type { EntityMeta, JsonScalar } from '../type/index.js';\n\n/** Whether `value` is a {@link JsonScalar}, which `$addToSet` and an `=` on a JSON path compare by equality. */\nexport function isJsonScalar(value: unknown): value is JsonScalar {\n return typeof value === 'string' || typeof value === 'boolean' || Number.isFinite(value);\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n if (!(size >= 1)) {\n throw new RangeError(`a chunk holds at least one item, not ${size}`);\n }\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** A shallow copy of `value` without `keys`. */\nexport function omitKeys<T extends object>(value: T, keys: Iterable<string>): T {\n const copy = { ...value };\n for (const key of keys) {\n Reflect.deleteProperty(copy, key);\n }\n return copy;\n}\n\n/** The value `cache` holds for `key`, computed and held the first time it is asked for. */\nexport function cachedIn<K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n compute: () => V,\n): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n",
9
9
  "/**\n * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers\n * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization\n * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the\n * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.\n */\nexport type QueryErrorKind =\n | 'uniqueViolation'\n | 'foreignKeyViolation'\n | 'notNullViolation'\n | 'checkViolation'\n | 'optimisticLock'\n | 'retryable'\n | 'usage'\n | 'security';\n\n/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */\nexport abstract class UqlError extends Error {\n abstract readonly kind: QueryErrorKind;\n abstract readonly status: number;\n}\n\n/**\n * Thrown where the caller used the API in a way no statement can carry out: an update payload with no\n * version, a `$lock` outside a transaction, a method with no version to match. A `400` over HTTP: the\n * request is malformed, not the server's failure, and an untyped client is exactly who reaches this.\n */\nexport class UqlUsageError extends UqlError {\n override name = 'UqlUsageError';\n readonly kind = 'usage';\n readonly status = 400;\n}\n\n/**\n * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.\n * Fails the statement closed.\n */\nexport class UqlSecurityError extends UqlError {\n override name = 'UqlSecurityError';\n readonly kind = 'security';\n readonly status = 403;\n}\n\n/** What a value is, for a refusal naming what `/http` handed over instead of what the types require. */\nexport function kindOf(value: unknown): string {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Thrown when an update's `f.version()` column no longer matches the row: another writer moved it on,\n * or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`\n * where there is no row left.\n */\nexport class UqlOptimisticLockError extends UqlError {\n override name = 'UqlOptimisticLockError';\n readonly kind = 'optimisticLock';\n readonly status = 409;\n\n constructor(\n message: string,\n readonly expected: unknown,\n readonly actual: unknown,\n ) {\n super(message);\n }\n}\n",
@@ -1,9 +1,9 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
- import { soleId, valueFieldOf } from '../entity/metadata/definition.js';
2
+ import { generatesKey, soleId, valueFieldOf } from '../entity/metadata/definition.js';
3
3
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, renderSql, RAW_ALIAS, } from '../type/index.js';
4
4
  import { utcTimestamp } from '../util/date.js';
5
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
6
- import { isAutoIncrement, RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, upsertAssigned, } from '../util/index.js';
6
+ import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, upsertAssigned, } from '../util/index.js';
7
7
  import { cachedIn, isJsonScalar } from '../util/object.util.js';
8
8
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
9
9
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
@@ -1549,7 +1549,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1549
1549
  }
1550
1550
  return this.insertIdSource === 'returning'
1551
1551
  ? rows === 1 || this.features.orderedUpsertReturning
1552
- : rows === 1 && isAutoIncrement(id.field, true);
1552
+ : rows === 1 && generatesKey(meta);
1553
1553
  }
1554
1554
  /** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
1555
1555
  upsertUpdateBindsInPlace = false;
@@ -1,7 +1,7 @@
1
1
  import type { FieldOptions, HookDeclaration, HookEvent, RelationRegistration, AbstractType } from '../../type/index.js';
2
2
  /**
3
3
  * What the member decorators record for one class, until `@Entity()` or a subclass's registration drains it: the
4
- * only channel from a member decorator to its class, and what a schema's members are registered as too.
4
+ * only channel from a member decorator to its class, and what a defined entity's members are registered as too.
5
5
  */
6
6
  export type MemberRegistrations = {
7
7
  readonly fields: Record<string, FieldOptions>;
@@ -1,4 +1,4 @@
1
- export declare const Animal: import("../../../index.js").SchemaEntity<object & {
1
+ export declare const Animal: import("../../../index.js").DefinedEntity<object & {
2
2
  id: number;
3
3
  name: string;
4
4
  } & {} & import("../../../index.js").Brands<{
@@ -14,7 +14,7 @@ export declare const Animal: import("../../../index.js").SchemaEntity<object & {
14
14
  id: number;
15
15
  name: string;
16
16
  } & {}, object>;
17
- export declare const Dog: import("../../../index.js").SchemaEntity<import("../../../index.js").Except<object & {
17
+ export declare const Dog: import("../../../index.js").DefinedEntity<import("../../../index.js").Except<object & {
18
18
  id: number;
19
19
  name: string;
20
20
  } & {} & import("../../../index.js").Brands<{
@@ -24,7 +24,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
24
24
  readonly defaultValue: unknown;
25
25
  }, Date>;
26
26
  }, object> & import("../../../index.js").RelationRow<{
27
- readonly books: () => import("../../../index.js").SchemaRelation<object & {
27
+ readonly books: () => import("../../../index.js").DefinedRelation<object & {
28
28
  id: number;
29
29
  title: string;
30
30
  stock: number;
@@ -59,7 +59,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
59
59
  }, object> & {
60
60
  readonly shout: string | null;
61
61
  } & {} & import("../../../index.js").RelationRow<{
62
- readonly author: () => import("../../../index.js").SchemaRelation<object & {
62
+ readonly author: () => import("../../../index.js").DefinedRelation<object & {
63
63
  id: number;
64
64
  name: string;
65
65
  createdAt: Date;
@@ -1,4 +1,4 @@
1
- export declare const Book: import("../../../index.js").SchemaClass<object & {
1
+ export declare const Book: import("../../../index.js").DefinedClass<object & {
2
2
  id: number;
3
3
  title: string;
4
4
  stock: number;
@@ -33,7 +33,7 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
33
33
  }, object> & {
34
34
  readonly shout: string | null;
35
35
  } & {} & import("../../../index.js").RelationRow<{
36
- readonly author: () => import("../../../index.js").SchemaRelation<object & {
36
+ readonly author: () => import("../../../index.js").DefinedRelation<object & {
37
37
  id: number;
38
38
  name: string;
39
39
  createdAt: Date;
@@ -59,7 +59,7 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
59
59
  readonly defaultValue: unknown;
60
60
  }, Date>;
61
61
  }, object> & import("../../../index.js").RelationRow<{
62
- readonly books: () => import("../../../index.js").SchemaRelation<object & {
62
+ readonly books: () => import("../../../index.js").DefinedRelation<object & {
63
63
  id: number;
64
64
  title: string;
65
65
  stock: number;
@@ -132,7 +132,7 @@ export declare const Book: import("../../../index.js").SchemaClass<object & {
132
132
  readonly defaultValue: unknown;
133
133
  }, Date>;
134
134
  }, object> & import("../../../index.js").RelationRow<{
135
- readonly books: () => import("../../../index.js").SchemaRelation<object & {
135
+ readonly books: () => import("../../../index.js").DefinedRelation<object & {
136
136
  id: number;
137
137
  title: string;
138
138
  stock: number;
@@ -1,4 +1,4 @@
1
- import { type EntityGetter, type EntityMeta, type EntityOptions, type Except, type FieldMeta, type IdKey, type KeyMap, type RelationKey, type RelationMeta, type RelationOptions, type RelationRegistration, type SchemaEntityOptions, type Brands, type EntityBrand, type ColumnRow, type SchemaFields, type SchemaKey, type Type, type AbstractType, type WrittenId, type SchemaEntity } from '../../type/index.js';
1
+ import { type EntityGetter, type EntityMeta, type EntityOptions, type Except, type FieldMeta, type IdKey, type KeyMap, type RelationKey, type RelationMeta, type RelationOptions, type RelationRegistration, type DefineEntityOptions, type Brands, type EntityBrand, type ColumnRow, type DefinedFields, type DefinedKey, type Type, type AbstractType, type WrittenId, type DefinedEntity } from '../../type/index.js';
2
2
  import { type MemberRegistrations } from '../decorator/bag.js';
3
3
  /**
4
4
  * `opts` as the registry takes them: `mappedBy` and `references` read off their key maps down to the
@@ -11,18 +11,18 @@ export declare function relationRegistration<T extends object, O>({ mappedBy, re
11
11
  * entity names one, since a selector follows a rename and a string does not.
12
12
  */
13
13
  export declare function keyOf<E, K extends keyof E>(pick: (keys: KeyMap<E>) => K): K;
14
- type DeclaredRow<F extends SchemaFields, B> = Except<B, EntityBrand & keyof B> & ColumnRow<F> & Brands<F, B>;
14
+ type DeclaredRow<F extends DefinedFields, B> = Except<B, EntityBrand & keyof B> & ColumnRow<F> & Brands<F, B>;
15
15
  /**
16
- * Declares an entity by its schema and returns its class, whose row type the schema derives, so nothing is
16
+ * Declares an entity by its options and returns its class, whose row type the columns derive, so nothing is
17
17
  * written twice: its columns now, then each section, `.indexes()` and so on, `.relations()` last but for
18
18
  * `.filters()`. It registers on first read, with every section in, and its relations once each target exists.
19
19
  */
20
- export declare function defineEntity<const F extends SchemaFields, B = object, BK = unknown, BC = unknown>(schema: SchemaEntityOptions<F, B, BK, BC> & {
20
+ export declare function defineEntity<const F extends DefinedFields, B = object, BK = unknown, BC = unknown>(options: DefineEntityOptions<F, B, BK, BC> & {
21
21
  readonly abstract: true;
22
- }): SchemaEntity<DeclaredRow<F, B>, SchemaKey<F, BK>, BC & ColumnRow<F>, B, true>;
23
- export declare function defineEntity<const F extends SchemaFields, B = object, BK = unknown, BC = unknown>(schema: SchemaEntityOptions<F, B, BK, BC>): SchemaEntity<DeclaredRow<F, B>, SchemaKey<F, BK>, BC & ColumnRow<F>, B>;
22
+ }): DefinedEntity<DeclaredRow<F, B>, DefinedKey<F, BK>, BC & ColumnRow<F>, B, true>;
23
+ export declare function defineEntity<const F extends DefinedFields, B = object, BK = unknown, BC = unknown>(options: DefineEntityOptions<F, B, BK, BC>): DefinedEntity<DeclaredRow<F, B>, DefinedKey<F, BK>, BC & ColumnRow<F>, B>;
24
24
  /**
25
- * The registration both forms share, a schema's `members` given as the decorators would register them. Built
25
+ * The registration both forms share, a defined entity's `members` given as the decorators would register them. Built
26
26
  * apart and stored once it passes, so a rejected definition leaves the registry as it was.
27
27
  */
28
28
  export declare function registerEntity<E>(entity: AbstractType<E>, opts?: EntityOptions<E>, members?: Partial<MemberRegistrations>): EntityMeta<E>;
@@ -61,7 +61,7 @@ export declare function idOf<E>(meta: EntityMeta<E>, row: KeyedRow<E>): WrittenI
61
61
  * Forgets an entity, and reports whether there was one - for a registry that grows at runtime, where a
62
62
  * deleted content type would otherwise keep its metadata for the life of the process. Nothing rewrites
63
63
  * what pointed at it, and a decorated class does not come back (its decorators drained at first
64
- * registration). See the Runtime Schemas guide.
64
+ * registration). See the Runtime Entities guide.
65
65
  */
66
66
  export declare function removeEntity<E>(entity: AbstractType<E>): boolean;
67
67
  export declare function getEntities(): Type<object>[];
@@ -72,4 +72,14 @@ export declare function getMeta<E>(entity: AbstractType<E>): EntityMeta<E>;
72
72
  * schema build constrains and a junction joins by, settling the relations holding them first.
73
73
  */
74
74
  export declare function foreignKeysOf<E>(meta: EntityMeta<E>): RelationMeta[];
75
+ /**
76
+ * The fields holding another entity's primary key: each column of a foreign key paired with a column of its
77
+ * target's key, whether `f.references()` or a relation declares it. Per entity, not per field: an entity
78
+ * extending another may join by other columns. Kept once resolved.
79
+ */
80
+ export declare function referenceKeys<E>(meta: EntityMeta<E>): ReadonlySet<string>;
81
+ /** Whether `key` is `meta`'s whole primary key and its own, not the key of the row it references. */
82
+ export declare function ownsSoleKey<E>(meta: EntityMeta<E>, key: string): boolean;
83
+ /** Whether the database generates `meta`'s key on insert: the one answer every insert path reads. */
84
+ export declare function generatesKey<E>(meta: EntityMeta<E>): boolean;
75
85
  export {};
@@ -1,5 +1,5 @@
1
1
  import { COLUMN_OPTIONS, REF_KEY, RelationAggregate, SECTION_ENTRY, SOFT_DELETE_FILTER, } from '../../type/index.js';
2
- import { aggregateField, defaultReadKeys, fieldKeys, isInlinedExpression } from '../../util/field.util.js';
2
+ import { aggregateField, defaultReadKeys, fieldKeys, isAutoIncrement, isInlinedExpression, } from '../../util/field.util.js';
3
3
  import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, isRecord, whereWith, } from '../../util/index.js';
4
4
  import { UqlUsageError } from '../../util/uqlError.js';
5
5
  import { ownRegistrations } from '../decorator/bag.js';
@@ -124,7 +124,7 @@ function addFilter(meta, name, opts) {
124
124
  }
125
125
  (meta.filters ??= {})[name] = opts;
126
126
  }
127
- /** Registers the fields, relations and hooks decorators or a schema declared, before anything is finalized. */
127
+ /** Registers the fields, relations and hooks decorators or `defineEntity` declared, before anything is finalized. */
128
128
  function applyMembers(meta, members) {
129
129
  for (const [key, spec] of definedEntries(members?.fields ?? {})) {
130
130
  addField(meta, key, spec);
@@ -157,16 +157,16 @@ function resolvedHook(entity, event, hook) {
157
157
  }
158
158
  return 'methodName' in hook && hook.methodName !== undefined ? methodHook(entity, event, hook.methodName) : hook;
159
159
  }
160
- const declaredSchemas = new WeakMap();
161
- export function defineEntity(schema) {
162
- const base = schema.extends ?? Object;
163
- // Its rows are read by key alone, which is what the registry types an erased schema's columns by.
160
+ const declaredEntities = new WeakMap();
161
+ export function defineEntity(options) {
162
+ const base = options.extends ?? Object;
163
+ // Its rows are read by key alone, which is what the registry types erased options' columns by.
164
164
  const entity = {
165
- [schema.name]: class extends base {
165
+ [options.name]: class extends base {
166
166
  },
167
- }[schema.name];
167
+ }[options.name];
168
168
  metas.set(entity, { ...emptyMeta(entity), stage: 'declared' });
169
- declaredSchemas.set(entity, { schema, sections: {} });
169
+ declaredEntities.set(entity, { options, sections: {} });
170
170
  for (const section of SECTIONS) {
171
171
  Object.defineProperty(entity, section, {
172
172
  value(declared, derived) {
@@ -180,11 +180,11 @@ export function defineEntity(schema) {
180
180
  }
181
181
  return entity;
182
182
  }
183
- /** The sections a schema declares as methods. `derived` is no method: `relations` takes it as its second argument. */
183
+ /** The sections a defined entity declares as methods. `derived` is no method: `relations` takes it as its second argument. */
184
184
  const SECTIONS = ['computed', 'indexes', 'checks', 'triggers', 'filters', 'hooks', 'relations'];
185
- /** Records one section of a pending schema, refusing a second of it and one declared after the entity was read. */
185
+ /** Records one section of a pending defined entity, refusing a second of it and one declared after the entity was read. */
186
186
  function declareSection(entity, section, declared) {
187
- const pending = pendingSchema(entity);
187
+ const pending = pendingEntity(entity);
188
188
  if (!pending) {
189
189
  throw new UqlUsageError(`'${entity.name}' was read already: declare its ${section} before its first use`);
190
190
  }
@@ -193,33 +193,33 @@ function declareSection(entity, section, declared) {
193
193
  }
194
194
  Object.assign(pending.sections, { [section]: declared });
195
195
  }
196
- /** What `entity` declared as a schema, while it is not registered yet. */
197
- function pendingSchema(entity) {
198
- return metas.get(entity)?.stage === 'declared' ? declaredSchemas.get(entity) : undefined;
196
+ /** What `entity` declared with `defineEntity`, while it is not registered yet. */
197
+ function pendingEntity(entity) {
198
+ return metas.get(entity)?.stage === 'declared' ? declaredEntities.get(entity) : undefined;
199
199
  }
200
- /** Registers a pending schema, its base's first; a failure leaves it pending, so a later read reports it again. */
201
- function settleSchema(entity) {
202
- const pending = pendingSchema(entity);
200
+ /** Registers a pending defined entity, its base's first; a failure leaves it pending, so a later read reports it again. */
201
+ function settleEntity(entity) {
202
+ const pending = pendingEntity(entity);
203
203
  if (!pending) {
204
204
  return;
205
205
  }
206
- const { schema, sections } = pending;
207
- const fields = fieldsOf(schema.name, schema.fields);
206
+ const { options, sections } = pending;
207
+ const fields = fieldsOf(options.name, options.fields);
208
208
  const refs = memberRefs();
209
209
  for (const added of [
210
- fieldsOf(schema.name, sections.computed?.(refs) ?? {}),
211
- fieldsOf(schema.name, readDerived(sections.derived, refs)),
210
+ fieldsOf(options.name, sections.computed?.(refs) ?? {}),
211
+ fieldsOf(options.name, readDerived(sections.derived, refs)),
212
212
  ]) {
213
213
  const taken = Object.keys(added).find((key) => key in fields);
214
214
  if (taken) {
215
- throw new UqlUsageError(`'${schema.name}.${taken}' is declared twice: name each member once`);
215
+ throw new UqlUsageError(`'${options.name}.${taken}' is declared twice: name each member once`);
216
216
  }
217
217
  Object.assign(fields, added);
218
218
  }
219
219
  registerEntity(entity, {
220
- name: schema.table,
221
- schema: schema.schema,
222
- abstract: schema.abstract,
220
+ name: options.table,
221
+ schema: options.schema,
222
+ abstract: options.abstract,
223
223
  indexes: sections.indexes,
224
224
  checks: sections.checks,
225
225
  triggers: sections.triggers,
@@ -267,7 +267,7 @@ const RELATION_BUILDER = {
267
267
  manyToMany: (target, options) => ({ target, cardinality: 'mm', options }),
268
268
  };
269
269
  /**
270
- * Settles an entity's relations, once: its schema's, read now that each target exists, beside those its decorators
270
+ * Settles an entity's relations, once: those `defineEntity` declared, read now that each target exists, beside those its decorators
271
271
  * registered, then a copy of each its base settled that it does not declare itself. The one place either form
272
272
  * inherits a relation. Marked after, so a read after a failure reports the same mistake again.
273
273
  */
@@ -277,7 +277,7 @@ function settleRelations(meta) {
277
277
  }
278
278
  const parent = parentOf(meta.entity);
279
279
  const inherited = parent && metas.has(parent) ? registeredMeta(parent).relations : {};
280
- const declared = declaredSchemas.get(meta.entity)?.sections.relations;
280
+ const declared = declaredEntities.get(meta.entity)?.sections.relations;
281
281
  for (const [key, read] of Object.entries(declared?.(RELATION_BUILDER) ?? {})) {
282
282
  const { target, cardinality, options } = read();
283
283
  addRelation(meta, key, relationRegistration({ ...options, cardinality, entity: () => tableOf(target) }));
@@ -291,7 +291,7 @@ function settleRelations(meta) {
291
291
  meta.stage = 'settled';
292
292
  }
293
293
  /**
294
- * The registration both forms share, a schema's `members` given as the decorators would register them. Built
294
+ * The registration both forms share, a defined entity's `members` given as the decorators would register them. Built
295
295
  * apart and stored once it passes, so a rejected definition leaves the registry as it was.
296
296
  */
297
297
  export function registerEntity(entity, opts = {}, members) {
@@ -433,21 +433,21 @@ export function idOf(meta, row) {
433
433
  * Forgets an entity, and reports whether there was one - for a registry that grows at runtime, where a
434
434
  * deleted content type would otherwise keep its metadata for the life of the process. Nothing rewrites
435
435
  * what pointed at it, and a decorated class does not come back (its decorators drained at first
436
- * registration). See the Runtime Schemas guide.
436
+ * registration). See the Runtime Entities guide.
437
437
  */
438
438
  export function removeEntity(entity) {
439
439
  return metas.delete(entity);
440
440
  }
441
441
  export function getEntities() {
442
442
  for (const entity of metas.keys()) {
443
- settleSchema(entity);
443
+ settleEntity(entity);
444
444
  }
445
445
  return [...metas.values()]
446
446
  .filter((meta) => meta.ids.length)
447
447
  .map((meta) => meta.entity)
448
448
  .filter(isTable);
449
449
  }
450
- /** The class a schema relation targets, refused where it is abstract: a relation needs a table to join. */
450
+ /** The class a defined relation targets, refused where it is abstract: a relation needs a table to join. */
451
451
  function tableOf(target) {
452
452
  if (!isTable(target)) {
453
453
  throw new UqlUsageError(`'${target.name}' is abstract: a relation needs a table to join`);
@@ -458,9 +458,9 @@ function tableOf(target) {
458
458
  function isTable(entity) {
459
459
  return !metas.get(entity)?.abstract;
460
460
  }
461
- /** The metadata `entity` has, a pending schema registered first, without settling anything further. */
461
+ /** The metadata `entity` has, a pending defined entity registered first, without settling anything further. */
462
462
  function knownMeta(entity) {
463
- settleSchema(entity);
463
+ settleEntity(entity);
464
464
  return ensureMeta(entity);
465
465
  }
466
466
  function ensureMeta(entity) {
@@ -488,12 +488,15 @@ export function getMeta(entity) {
488
488
  // reads other entities without resolving them, so no entity is ever read half resolved.
489
489
  fillRelations(meta);
490
490
  meta.readKeys = defaultReadKeys(meta);
491
+ // A column `references` names is a foreign key with or without a relation over it, and one cannot point
492
+ // at a composite key: refused on first read, as a relation that cannot join is, not at the schema build.
493
+ meta.referenceKeys = referenceKeys(meta);
491
494
  meta.stage = 'resolved';
492
495
  return meta;
493
496
  }
494
497
  /** The metadata `entity` registered, however much of it is resolved. */
495
498
  function registeredMeta(entity) {
496
- settleSchema(entity);
499
+ settleEntity(entity);
497
500
  const meta = metas.get(entity);
498
501
  if (!meta) {
499
502
  throw new UqlUsageError(`'${entity.name}' is not an entity`);
@@ -516,9 +519,6 @@ function fillRelations(meta) {
516
519
  "'persist' only: cascade a delete from the side that owns the rows.");
517
520
  }
518
521
  }
519
- // A column `references` names is a foreign key with or without a relation over it, and one cannot point
520
- // at a composite key: refused on first read, as a relation that cannot join is, not at the schema build.
521
- foreignKeysOf(meta);
522
522
  }
523
523
  /**
524
524
  * The pairs a relation joins on, settled on first read, whether its own entity is being resolved or another
@@ -694,6 +694,27 @@ export function foreignKeysOf(meta) {
694
694
  });
695
695
  return [...owning, ...columns];
696
696
  }
697
+ /**
698
+ * The fields holding another entity's primary key: each column of a foreign key paired with a column of its
699
+ * target's key, whether `f.references()` or a relation declares it. Per entity, not per field: an entity
700
+ * extending another may join by other columns. Kept once resolved.
701
+ */
702
+ export function referenceKeys(meta) {
703
+ return (meta.referenceKeys ??
704
+ new Set(foreignKeysOf(meta).flatMap(({ entity, references }) => {
705
+ const { ids } = knownMeta(entity());
706
+ return references.filter(({ foreign }) => ids.some((id) => id === foreign)).map(({ local }) => local);
707
+ })));
708
+ }
709
+ /** Whether `key` is `meta`'s whole primary key and its own, not the key of the row it references. */
710
+ export function ownsSoleKey(meta, key) {
711
+ return soleId(meta)?.key === key && !referenceKeys(meta).has(key);
712
+ }
713
+ /** Whether the database generates `meta`'s key on insert: the one answer every insert path reads. */
714
+ export function generatesKey(meta) {
715
+ const sole = soleId(meta);
716
+ return !!sole && isAutoIncrement(sole.field, ownsSoleKey(meta, sole.key));
717
+ }
697
718
  /** The kinds a column of `type` holds as a join compares them, as `JoinKind` does: a bigint is a number, which BIGINT widens. */
698
719
  function joinedKinds(type) {
699
720
  const types = valueTypesOf(type);
@@ -19,7 +19,7 @@ const METHOD_SOURCE = {
19
19
  nullable: (col) => (col.nullable && !col.isPrimaryKey ? ['.nullable()'] : []),
20
20
  isPrimaryKey: (col) => (col.isPrimaryKey ? ['.id()'] : []),
21
21
  // Generates where `isAutoIncrement` says, which only a column the database treats otherwise contradicts.
22
- isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, col.isPrimaryKey && col.table.primaryKey?.columns.length === 1) === col.isAutoIncrement
22
+ isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, ownsSoleKey(col)) === col.isAutoIncrement
23
23
  ? []
24
24
  : [col.isAutoIncrement ? '.autoIncrement()' : '.autoIncrement(false)'],
25
25
  isUnique: (col) => (col.isUnique ? ['.unique()'] : []),
@@ -33,6 +33,13 @@ const METHOD_SOURCE = {
33
33
  // The graph link: a foreign key becomes a relation decorator, emitted beside the field rather than in it.
34
34
  table: null,
35
35
  };
36
+ /** The AST's reading of the entity's `ownsSoleKey`: the table's whole key, and not the key of a row it references. */
37
+ function ownsSoleKey(col) {
38
+ const { primaryKey, outgoingRelations } = col.table;
39
+ return (col.isPrimaryKey &&
40
+ primaryKey?.columns.length === 1 &&
41
+ !outgoingRelations.some(({ from }) => from.columns.includes(col)));
42
+ }
36
43
  /** Whether to write `type`'s precision: not for a timestamp at a `Date`'s milliseconds, its default. */
37
44
  function writesPrecision(type) {
38
45
  return type.precision !== undefined && !(type.category === 'timestamp' && type.precision === DATE_PRECISION);
@@ -213,7 +213,6 @@ export declare class MongoDialect extends AbstractDialect {
213
213
  private renamedColumns;
214
214
  /** Each relation's key, the field its rows are read from, and its entity, memoized per entity for `normalizeId`. */
215
215
  private relationReads;
216
- private referenceKeys;
217
216
  normalizeIds<E extends Document>(meta: EntityMeta<E>, docs: Document[]): E[];
218
217
  /** `doc` is the wire shape - `_id`, stored names, `ObjectId`s - and what comes back is the code's. */
219
218
  normalizeId<E extends Document>(meta: EntityMeta<E>, doc: Document): E;