uql-orm 0.107.0 → 0.107.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,10 +30,10 @@
30
30
  ---
31
31
 
32
32
  ```sh
33
- npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @tursodatabase/serverless, @libsql/client
33
+ npm install uql-orm pg
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, `pg` swapped for your database's driver: `mysql2`, `mariadb`, `better-sqlite3`, `mongodb`, `@tursodatabase/serverless` or `@libsql/client` ([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>
@@ -86,6 +86,8 @@ export class Post {
86
86
  Or declare one as data, its row type derived:
87
87
 
88
88
  ```ts
89
+ import { defineEntity, f } from 'uql-orm';
90
+
89
91
  export const Post = defineEntity({
90
92
  name: 'Post',
91
93
  fields: {
@@ -94,7 +96,12 @@ export const Post = defineEntity({
94
96
  likes: f.number().nullable(),
95
97
  authorId: f.number().nullable(),
96
98
  },
97
- }).relations((rel) => ({ author: () => rel.manyToOne(User, { references: (post) => post.authorId }) }));
99
+ }).relations((rel) => ({
100
+ author: () => rel.manyToOne(User, { references: (post) => post.authorId }),
101
+ }));
102
+
103
+ // One name for the entity and its rows, as a class has: a function takes `post: Post`.
104
+ export type Post = InstanceType<typeof Post>;
98
105
  ```
99
106
 
100
107
  ### 2. A pool, and the migrations it drives
@@ -112,7 +119,7 @@ export default { pool, entities: [User, Post] } satisfies Config;
112
119
 
113
120
  ```sh
114
121
  npm i -D tsx # Node only: the CLI loads uql.config.ts through it
115
- npx uql-migrate generate:entities initial # diffs the entities against the database into a migration you review
122
+ npx uql-migrate generate:entities initial # writes the diff against the database, to review
116
123
  npx uql-migrate up # applies it
117
124
  ```
118
125
 
@@ -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,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>[];
@@ -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) {
@@ -496,7 +496,7 @@ export function getMeta(entity) {
496
496
  }
497
497
  /** The metadata `entity` registered, however much of it is resolved. */
498
498
  function registeredMeta(entity) {
499
- settleSchema(entity);
499
+ settleEntity(entity);
500
500
  const meta = metas.get(entity);
501
501
  if (!meta) {
502
502
  throw new UqlUsageError(`'${entity.name}' is not an entity`);
@@ -1,8 +1,8 @@
1
1
  import type { ForeignKeyAction } from '../schema/types.js';
2
2
  import type { TYPE_BOUNDS, VALUE_DECIDERS } from '../util/fieldOption.util.js';
3
+ import type { ReferencedKey } from './definedEntity.js';
3
4
  import type { BlobColumnType, BooleanColumnType, ColumnType, DateColumnType, DdlDefault, JsonColumnType, NumericColumnType, StringColumnType, VectorColumnType, FieldOptions, HasCompositeKey, IdValue, JoinKind, OnFieldCallback, StampEvent } from './entity.js';
4
5
  import type { QuerySql } from './querySql.js';
5
- import type { ReferencedKey } from './schemaEntity.js';
6
6
  import type { StandardSchemaV1 } from './standardSchema.js';
7
7
  import type { Type, Json, AbstractType } from './utility.js';
8
8
  import type { VectorDistance } from './vector.js';
@@ -62,7 +62,7 @@ interface Builders<O, V> {
62
62
  readonly json: ColumnBuilder<O, V, 'json'>;
63
63
  readonly blob: ColumnBuilder<O, V, 'blob'>;
64
64
  readonly vector: VectorColumn<O, V>;
65
- /** A column whose family is known only at run time: a foreign key's is its target key's, a runtime schema's its data's. */
65
+ /** A column whose family is known only at run time: a foreign key's is its target key's, an entity defined at run time, its data's. */
66
66
  readonly any: ColumnBuilder<O, V, 'any'>;
67
67
  }
68
68
  type Family = keyof Builders<unknown, unknown>;
@@ -317,7 +317,7 @@ export type ColumnFactory = {
317
317
  column(type: BlobColumnType): ColumnBuilder<{
318
318
  readonly type: BlobColumnType;
319
319
  }, Uint8Array, 'blob'>;
320
- /** A column whose type is data, as a schema built at run time declares one. */
320
+ /** A column whose type is data, as an entity defined at run time declares one. */
321
321
  column(type: ColumnType): ColumnBuilder<{
322
322
  readonly type: ColumnType;
323
323
  }, unknown, 'any'>;
@@ -3,11 +3,11 @@ import type { BrandNames, CheckSection, FilterSection, filledKey, HookContext, H
3
3
  import type { QuerySql, RelationAggregate } from './querySql.js';
4
4
  import type { Type, AbstractType } from './utility.js';
5
5
  /**
6
- * A schema entity's columns, each an `f` builder. A foreign key's target is a relation in `.relations()`, read lazily:
6
+ * A defined entity's columns, each an `f` builder. A foreign key's target is a relation in `.relations()`, read lazily:
7
7
  * a column naming its target here would read it while it is still being inferred. A computed column is declared in
8
8
  * `.computed()`, where its row is read-only.
9
9
  */
10
- export type SchemaFields = {
10
+ export type DefinedFields = {
11
11
  readonly [key: string]: Column<{
12
12
  readonly references?: undefined;
13
13
  readonly computed?: undefined;
@@ -15,9 +15,9 @@ export type SchemaFields = {
15
15
  readonly [key: string]: unknown;
16
16
  }>;
17
17
  };
18
- /** The key a class holds: carried beside a schema's, so a cycle never reads its row; read off a decorated one's. */
18
+ /** The key a class holds: carried beside a defined one's, so a cycle never reads its row; read off a decorated one's. */
19
19
  export type ReferencedKey<C> = C extends {
20
- readonly [schemaShape]?: {
20
+ readonly [definedShape]?: {
21
21
  readonly key: infer K;
22
22
  };
23
23
  } ? unknown extends K ? RowKey<C> : K : RowKey<C>;
@@ -48,13 +48,13 @@ type IsEager<F> = F extends RelationAggregate<unknown> ? true : ColumnOptionsOf<
48
48
  readonly eager: false;
49
49
  } ? false : true;
50
50
  /** What `.computed()` returns: columns the database computes, `f.string().as(sql`...`)`. */
51
- type SchemaComputed = {
51
+ type DefinedComputed = {
52
52
  readonly [key: string]: Column<{
53
53
  readonly computed: QuerySql;
54
54
  }>;
55
55
  };
56
- /** A relation as a schema declares it: what `rel.*` returns, its target carried for the row. */
57
- export type SchemaRelation<T = object, C extends RelationCardinality = RelationCardinality, Columns = T> = {
56
+ /** A relation as a defined entity declares it: what `rel.*` returns, its target carried for the row. */
57
+ export type DefinedRelation<T = object, C extends RelationCardinality = RelationCardinality, Columns = T> = {
58
58
  readonly target: Type<T>;
59
59
  readonly cardinality: C;
60
60
  /** Checked by the builder's signature, so held erased: the registry reads them back as any relation's options. */
@@ -69,7 +69,7 @@ type AggregateRefs<R> = {
69
69
  readonly columns?: infer Columns;
70
70
  } ? RelationRef<Columns> : never;
71
71
  };
72
- type RelationValue<P> = P extends () => SchemaRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
72
+ type RelationValue<P> = P extends () => DefinedRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
73
73
  /** A relation's derived field as its callback declares it: a thunk, so it is read lazily like a relation is. */
74
74
  export type DerivedFields = {
75
75
  readonly [key: string]: () => RelationAggregate<unknown> | Column<{
@@ -80,7 +80,7 @@ export type DerivedFields = {
80
80
  export type DerivedRow<A> = {
81
81
  readonly [K in keyof A]-?: A[K] extends () => infer F ? FieldValue<F> : never;
82
82
  };
83
- /** The relations as a row reads them; exported, as a schema's emitted declaration names it. */
83
+ /** The relations as a row reads them; exported, as a defined entity's emitted declaration names it. */
84
84
  export type RelationRow<R> = {
85
85
  -readonly [K in keyof R]?: RelationValue<R[K]>;
86
86
  };
@@ -101,32 +101,32 @@ type VersionKeyOf<F> = FlagKeys<F, Column<{
101
101
  readonly version: true;
102
102
  }>>;
103
103
  type FilledKeyOf<F> = Exclude<FlagKeys<F, Column<FilledOptions>>, IdKeyOf<F>>;
104
- /** The relation constructors a schema's `relations` receives, typed by the columns of the entity declaring them. */
104
+ /** The relation constructors a defined entity's `relations` receives, typed by the columns of the entity declaring them. */
105
105
  export type RelationBuilder<O> = {
106
- oneToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>> | RelationInverseOptions<T, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, '11'>;
107
- manyToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, 'm1'>;
106
+ oneToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & DefinedShape<K, Columns>, opts: RelationOwnerOptions<T, O, DefinedJoins<T, O, K, Columns>> | RelationInverseOptions<T, DefinedJoins<T, O, K, Columns>>): DefinedRelation<T, '11'>;
107
+ manyToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & DefinedShape<K, Columns>, opts: RelationOwnerOptions<T, O, DefinedJoins<T, O, K, Columns>>): DefinedRelation<T, 'm1'>;
108
108
  /** With no options, it is mapped by the one many-to-one of its target pointing back. */
109
- oneToMany<T extends object, Columns = T>(target: Type<T> & SchemaShape<unknown, Columns>, opts?: RelationInverseOptions<T, SchemaJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, SchemaJoins<T, O, unknown, Columns>>): SchemaRelation<T, '1m', Columns>;
110
- manyToMany<T extends object, Columns = T>(target: Type<T> & SchemaShape<unknown, Columns>, opts: RelationInverseOptions<T, SchemaJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, SchemaJoins<T, O, unknown, Columns>>): SchemaRelation<T, 'mm', Columns>;
109
+ oneToMany<T extends object, Columns = T>(target: Type<T> & DefinedShape<unknown, Columns>, opts?: RelationInverseOptions<T, DefinedJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, DefinedJoins<T, O, unknown, Columns>>): DefinedRelation<T, '1m', Columns>;
110
+ manyToMany<T extends object, Columns = T>(target: Type<T> & DefinedShape<unknown, Columns>, opts: RelationInverseOptions<T, DefinedJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, DefinedJoins<T, O, unknown, Columns>>): DefinedRelation<T, 'mm', Columns>;
111
111
  };
112
112
  /**
113
- * A schema's joins: a foreign key and paired columns checked by type, off the target's carried key and columns;
113
+ * A defined entity's joins: a foreign key and paired columns checked by type, off the target's carried key and columns;
114
114
  * `mappedBy` by key alone, its kind checked on first read.
115
115
  */
116
- type SchemaJoins<T, O, K = unknown, Columns = T> = {
116
+ type DefinedJoins<T, O, K = unknown, Columns = T> = {
117
117
  readonly key: KeyHolding<O, K>;
118
- readonly pairs: readonly SchemaJoinPair<O, Columns>[];
118
+ readonly pairs: readonly DefinedJoinPair<O, Columns>[];
119
119
  readonly mappedBy: keyof T;
120
120
  };
121
121
  /** One pair of join columns, the local one holding what the target's column does. */
122
- type SchemaJoinPair<O, Columns> = {
122
+ type DefinedJoinPair<O, Columns> = {
123
123
  readonly [F in keyof Columns]-?: {
124
124
  readonly local: KeyHolding<O, NonNullable<Columns[F]>>;
125
125
  readonly foreign: F;
126
126
  };
127
127
  }[keyof Columns];
128
- /** What the first call of a schema states: the class, its table and its columns. */
129
- export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown, BC = unknown> = {
128
+ /** What the first call of `defineEntity` states: the class, its table and its columns. */
129
+ export type DefineEntityOptions<F extends DefinedFields, B = object, BK = unknown, BC = unknown> = {
130
130
  /** The class's name, which a naming strategy derives the table's from, as it does a decorated class's. */
131
131
  readonly name: string;
132
132
  /** The table, exactly as the database names it, where it is not derived from `name`. */
@@ -136,56 +136,56 @@ export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown
136
136
  /** A base that is never a table: the entities extending it take what it declares. */
137
137
  readonly abstract?: true;
138
138
  /** The entity it inherits from, which the declared class extends, so its methods and `super` work. */
139
- readonly extends?: SchemaClass<B, BK, BC, boolean>;
139
+ readonly extends?: DefinedClass<B, BK, BC, boolean>;
140
140
  readonly fields: F;
141
141
  };
142
- /** A hook a schema runs on a row; a promise it returns is awaited. */
143
- type SchemaHook<Row> = (row: Row, ctx: HookContext) => unknown;
142
+ /** A hook a defined entity runs on a row; a promise it returns is awaited. */
143
+ type DefinedHook<Row> = (row: Row, ctx: HookContext) => unknown;
144
144
  /**
145
- * What a schema declares after its columns, each section typed by the columns now fixed, so none is inferred
145
+ * What a defined entity declares after its columns, each section typed by the columns now fixed, so none is inferred
146
146
  * again. `relations` comes last but for `filters`, which reads the row they complete.
147
147
  */
148
- type SchemaSections<Row, Key, Columns, B, Abstract> = {
148
+ type DefinedSections<Row, Key, Columns, B, Abstract> = {
149
149
  /** Columns the database computes off the stored ones, `(post) => ({ slug: f.string().as(sql`...`) })`. */
150
- computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row & ReadRow<C>, Key, Columns & ReadRow<C>, B, Abstract>;
151
- indexes(indexes: IndexSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
152
- checks(checks: CheckSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
153
- triggers(triggers: TriggerSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
154
- filters(filters: FilterSection<Row>): SchemaEntity<Row, Key, Columns, B, Abstract>;
150
+ computed<const C extends DefinedComputed>(computed: (refs: RefMap<Columns>) => C): DefinedEntity<Row & ReadRow<C>, Key, Columns & ReadRow<C>, B, Abstract>;
151
+ indexes(indexes: IndexSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
152
+ checks(checks: CheckSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
153
+ triggers(triggers: TriggerSection<Columns>): DefinedEntity<Row, Key, Columns, B, Abstract>;
154
+ filters(filters: FilterSection<Row>): DefinedEntity<Row, Key, Columns, B, Abstract>;
155
155
  /** Functions each lifecycle event runs on the row, in order, given the querier writing it. */
156
156
  hooks(hooks: {
157
- readonly [E in HookEvent]?: readonly SchemaHook<Row>[];
158
- }): SchemaEntity<Row, Key, Columns, B, Abstract>;
157
+ readonly [E in HookEvent]?: readonly DefinedHook<Row>[];
158
+ }): DefinedEntity<Row, Key, Columns, B, Abstract>;
159
159
  /**
160
160
  * The relations, each read lazily so entities pointing at each other declare in either order, and the values
161
161
  * read over the to-many ones, its base's too: `(author) => ({ postCount: () => author.posts.count() })`.
162
162
  */
163
163
  relations<const R, const A extends DerivedFields = {}>(relations: (rel: RelationBuilder<Columns>) => R, derived?: (refs: RefMap<Columns> & AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & DerivedRow<A>, Key, Columns, Abstract>;
164
164
  };
165
- /** A schema entity's class once its relations are in: its filters may follow, and read through them. */
166
- export type RelatedEntity<Row, Key, Columns, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & {
167
- filters(filters: FilterSection<Row>): SchemaClass<Row, Key, Columns, Abstract>;
165
+ /** A defined entity's class once its relations are in: its filters may follow, and read through them. */
166
+ export type RelatedEntity<Row, Key, Columns, Abstract = false> = DefinedClass<Row, Key, Columns, Abstract> & {
167
+ filters(filters: FilterSection<Row>): DefinedClass<Row, Key, Columns, Abstract>;
168
168
  };
169
- /** A schema entity's class while its sections may still be declared. */
170
- export type SchemaEntity<Row, Key, Columns, B, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & SchemaSections<Row, Key, Columns, B, Abstract>;
171
- /** The class a schema declares, to use as it is or to extend with behaviour; abstract for a base never a table. */
172
- export type SchemaClass<Row, Key = unknown, Columns = unknown, Abstract = false> = (Abstract extends true ? abstract new () => Row : new () => Row) & SchemaShape<Key, Columns>;
173
- declare const schemaShape: unique symbol;
169
+ /** A defined entity's class while its sections may still be declared. */
170
+ export type DefinedEntity<Row, Key, Columns, B, Abstract = false> = DefinedClass<Row, Key, Columns, Abstract> & DefinedSections<Row, Key, Columns, B, Abstract>;
171
+ /** The class `defineEntity` declares, to use as it is or to extend with behaviour; abstract for a base never a table. */
172
+ export type DefinedClass<Row, Key = unknown, Columns = unknown, Abstract = false> = (Abstract extends true ? abstract new () => Row : new () => Row) & DefinedShape<Key, Columns>;
173
+ declare const definedShape: unique symbol;
174
174
  /**
175
- * What a relation or an aggregate pointing at a schema reads of it, its key's type and its columns, carried beside
175
+ * What a relation or an aggregate pointing at a defined entity reads of it, its key's type and its columns, carried beside
176
176
  * its class rather than read off its row: the columns alone settle both while the row is still being inferred.
177
177
  */
178
- type SchemaShape<Key, Columns = unknown> = {
179
- readonly [schemaShape]?: {
178
+ type DefinedShape<Key, Columns = unknown> = {
179
+ readonly [definedShape]?: {
180
180
  readonly key: Key;
181
181
  readonly columns: Columns;
182
182
  };
183
183
  };
184
184
  /**
185
185
  * The key's type: its own column's, else the base's it inherits, `never` for a composite, which no one column can
186
- * reference, and anything for a schema built from data, whose columns are known only at run time.
186
+ * reference, and anything for an entity defined from data, whose columns are known only at run time.
187
187
  */
188
- export type SchemaKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
188
+ export type DefinedKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
189
189
  readonly isId: true;
190
190
  }>> extends infer K extends keyof F ? [K] extends [never] ? Inherited : true extends IsUnion<K> ? never : ColumnValueOf<F[K]> : never;
191
191
  export {};
@@ -354,7 +354,7 @@ export type OnFieldCallback<V = unknown> = V | QuerySql | (() => V | QuerySql);
354
354
  export type DdlDefault<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonDdlDefault : [TsTypeOf<FieldType>] extends [T] ? JsonDdlDefault | T : T;
355
355
  /** What a JSON column, and the field-less `FieldOptions`, may default to: a document, a list included, or its text. */
356
356
  type JsonDdlDefault = Scalar | Record<string, unknown> | readonly unknown[];
357
- /** The TypeScript type a declared `type` implies: a decorator checks the property against it, a schema derives it. */
357
+ /** The TypeScript type a declared `type` implies: a decorator checks the property against it, a defined entity derives it. */
358
358
  export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType | TimeColumnType | DecimalColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? JsonBrand | readonly JsonBrand[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
359
359
  /** The entity a relation points at: `Company` for `company?: Company` and `companies?: Company[]` alike. */
360
360
  export type RelationTarget<V> = Extract<Unpacked<V>, object>;
@@ -428,7 +428,7 @@ export type RelationRegistration = Merge<RelationOptions<object>, {
428
428
  /**
429
429
  * What a relation's join callbacks answer, `E` its target and `O` the entity declaring it: one foreign key, pairs of
430
430
  * columns, or the target's member mapping it. Each form states its own: a decorated class checks each member's
431
- * kind, a schema reads keys alone, since its target's types are still being inferred.
431
+ * kind, a defined entity reads keys alone, since its target's types are still being inferred.
432
432
  */
433
433
  export type RelationJoins = {
434
434
  readonly key: unknown;
@@ -548,7 +548,7 @@ export type RelationManyToOneOptions<E, O = unknown> = RelationOwnerSide & Parti
548
548
  export type RelationManyToManyOptions<E, O = unknown> = RelationJoinOptions<E, O, DecoratedJoins<E, O>> | RelationInverseOptions<E, DecoratedJoins<E, O>>;
549
549
  /** The lifecycle events. An upsert has its own pair: which branch a row takes is the database's to decide. */
550
550
  export type HookEvent = 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeUpsert' | 'afterUpsert' | 'beforeDelete' | 'afterDelete' | 'afterLoad';
551
- /** A hook as declared: the entity's method a decorator names, or the function a schema runs on the row. */
551
+ /** A hook as declared: the entity's method a decorator names, or the function a defined entity runs on the row. */
552
552
  export type HookDeclaration = {
553
553
  readonly methodName: string;
554
554
  } | {
@@ -567,7 +567,7 @@ export type HookContext = {
567
567
  readonly querier: Querier;
568
568
  readonly onCommit: Querier['onCommit'];
569
569
  };
570
- /** A schema entity's hook, bivariant in its row, so one typed by its row registers. */
570
+ /** A defined entity's hook, bivariant in its row, so one typed by its row registers. */
571
571
  export type HookFunction = {
572
572
  run(row: object, ctx: HookContext): unknown;
573
573
  }['run'];
@@ -755,7 +755,7 @@ export type EntityMeta<E> = {
755
755
  } & {
756
756
  [key: string]: RelationMeta | undefined;
757
757
  };
758
- /** The indexes `@Entity({ indexes })` or a schema's `indexes` declare. */
758
+ /** The indexes `@Entity({ indexes })` or `defineEntity`'s `.indexes()` declare. */
759
759
  indexes?: EntityIndexMeta<E>[];
760
760
  /** `CHECK` constraints, compiled when the schema is built. */
761
761
  checks?: EntityCheckMeta<E>[];
@@ -764,8 +764,8 @@ export type EntityMeta<E> = {
764
764
  /** Triggers the database runs, compiled when the schema is built. */
765
765
  triggers?: EntityTriggerMeta<E>[];
766
766
  /**
767
- * How far the registry finalized it: `'declared'` while a schema takes sections and is not registered, unset
768
- * once registered, `'settled'` once its schemas' relations, its bases' included, are in, and `'resolved'`
767
+ * How far the registry finalized it: `'declared'` while a defined entity takes sections and is not registered, unset
768
+ * once registered, `'settled'` once its `defineEntity` relations, its bases' included, are in, and `'resolved'`
769
769
  * once `getMeta` joined them too, which makes each step idempotent and re-entrant.
770
770
  */
771
771
  stage?: 'declared' | 'settled' | 'resolved';
@@ -11,7 +11,7 @@ export * from './query.js';
11
11
  export * from './queryAggregate.js';
12
12
  export * from './queryLock.js';
13
13
  export * from './querySql.js';
14
- export * from './schemaEntity.js';
14
+ export * from './definedEntity.js';
15
15
  export * from './queryWhere.js';
16
16
  export * from './universalQuerier.js';
17
17
  export * from './standardSchema.js';
@@ -11,7 +11,7 @@ export * from './query.js';
11
11
  export * from './queryAggregate.js';
12
12
  export * from './queryLock.js';
13
13
  export * from './querySql.js';
14
- export * from './schemaEntity.js';
14
+ export * from './definedEntity.js';
15
15
  export * from './queryWhere.js';
16
16
  export * from './universalQuerier.js';
17
17
  export * from './standardSchema.js';
@@ -100,7 +100,7 @@ export type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined)
100
100
  */
101
101
  export type FilterOnMissing = 'skip' | 'throw';
102
102
  /**
103
- * Authoring shape for `@Entity({ filters })` and a schema's `filters`.
103
+ * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.
104
104
  */
105
105
  export type FilterOptions<E = unknown> = {
106
106
  readonly where: FilterWhere<E>;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.107.0",
6
+ "version": "0.107.2",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -123,8 +123,8 @@
123
123
  }
124
124
  },
125
125
  "devDependencies": {
126
- "@electric-sql/pglite": "0.5.12",
127
- "@electric-sql/pglite-pgvector": "0.0.13",
126
+ "@electric-sql/pglite": "0.5.13",
127
+ "@electric-sql/pglite-pgvector": "0.0.14",
128
128
  "@libsql/client": "^0.18.0",
129
129
  "@neondatabase/serverless": "^1.2.0",
130
130
  "@nestjs/common": "^12.3.2",
@@ -10,7 +10,7 @@ description: >
10
10
 
11
11
  # UQL
12
12
 
13
- An entity is a decorated class, or a schema its row type is derived from. A query is a JSON object checked key by key against the entity, and it runs the same on every supported database. There is no schema file, no generated client and no query builder.
13
+ An entity is a decorated class, or declared as data with `defineEntity`, its row type derived. A query is a JSON object checked key by key against the entity, and it runs the same on every supported database. There is no schema file, no generated client and no query builder.
14
14
 
15
15
  Full docs are Markdown: the index at https://uql-orm.dev/llms.txt, and each page at its URL plus `.md`. Read the page for the task before guessing an option.
16
16
 
@@ -22,7 +22,7 @@ npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/
22
22
 
23
23
  ESM only. Needs Node 22.18+, Bun or an edge runtime, and TypeScript 5.7+.
24
24
 
25
- Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`. A project on legacy decorators (NestJS, Angular) keeps its config and defines entities with `defineEntity`: https://uql-orm.dev/entities/imperative.md
25
+ Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`. A project on legacy decorators (NestJS, Angular) keeps its config and defines entities with `defineEntity`: https://uql-orm.dev/entities/define-entity.md
26
26
 
27
27
  Node runs no decorators natively yet, so add `tsx` there (`npm i -D tsx`); `uql-migrate` loads `uql.config.ts` through it. A bundler that minifies class names needs `@Entity({ name: 'todo' })`, since the table name defaults to the class name.
28
28
 
@@ -83,7 +83,7 @@ export class Post {
83
83
  - Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable columns, `.eager(false)` fields, and relations. A computed field is present on a default read, so it is not optional. uql fills a single-column key and a version.
84
84
  - A NOT NULL field a default fills (`.default()`, `.onInsert()`) is `!` and listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
85
85
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included.
86
- - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... }) abstract class`, or a schema's `abstract: true`. A query or write on one does not compile: query the entities extending it.
86
+ - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... }) abstract class`, or `abstract: true` in `defineEntity`. A query or write on one does not compile: query the entities extending it.
87
87
  - `Date` is an instant, stored in UTC to the millisecond on every engine. `f.decimal()` is exact text (`price?: string | null`). `f.number().precision(10).scale(2)` opts into a rounding JS number.
88
88
  - Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`. Either may be left out where only one member fits: a decorated many-to-one's one foreign key to its target, a one-to-many's one many-to-one pointing back.
89
89
  - `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows in the same transaction; an update replaces a to-many's rows.
@@ -111,8 +111,8 @@ Both forms are supported, mix them per entity, and produce the same queries and
111
111
  - Without `@Entity({ name })`, the table name comes from the class name, which a minifier can change.
112
112
  - Higher type-check cost on the benchmark model (9,297 vs 5,110 instantiations).
113
113
  - Cannot be declared at run time.
114
- - `uql-codemod` cannot convert it into a schema.
115
- - Schema
114
+ - `uql-codemod` cannot convert it into `defineEntity`.
115
+ - `defineEntity`
116
116
  - Pros
117
117
  - The row type is derived from the builders, with nothing written twice.
118
118
  - Shorter: 19 to 30% fewer lines in the two apps this was measured on.
@@ -123,11 +123,11 @@ Both forms are supported, mix them per entity, and produce the same queries and
123
123
  - Cons
124
124
  - Relations are thunks declared after the columns, and `.relations()` comes last (only `.filters()` may follow it).
125
125
  - No column-level foreign keys: a shared key is a relation helper, and an eager read across two entities can create an inference cycle (TS7022).
126
- - Each entity needs a `type X = InstanceType<typeof X>` alias for its name.
127
- - No class to annotate or extend: inheritance uses `extends` on a base schema.
126
+ - Naming its row type as `X`, as a class does, takes a `type X = InstanceType<typeof X>` alias beside it.
127
+ - No class to annotate or extend: inheritance uses `extends` naming the base.
128
128
  - Newer and less used.
129
129
 
130
- ### Schema entities
130
+ ### defineEntity
131
131
 
132
132
  The same entities declared as data, the row type derived:
133
133
 
@@ -181,7 +181,7 @@ export const Book = defineEntity({
181
181
 
182
182
  - Each field is a column builder, as in the decorated form. The row follows from them: a key, a version and a NOT NULL column are always present, a `.nullable()` one reads `| null`; a default (`.default()`, `.onInsert()`, `.autoIncrement()`) makes it optional on insert; `f.enum()` gives the literal union. No `!`, `?` or brands to write.
183
183
  - The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `relations` comes last, but for a `filters` that reads through them: `.relations(...).filters({ byActiveAuthor: { where: { author: { active: true } } } })`. `defineEntity` itself takes `name` (the class name, which a naming strategy derives the table from), `table`, `schema`, `extends`, `abstract` and `fields`.
184
- - Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. A schema's foreign key is a relation: `manyToOne` names its `references` column, whose type is checked against the target's key; the column itself stays a plain field. `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
184
+ - Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. In `defineEntity`, a foreign key is a relation: `manyToOne` names its `references` column, whose type is checked against the target's key; the column itself stays a plain field. `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
185
185
  - `relations`' second callback declares the derived fields: each value is a thunk, read lazily, of an aggregate over a to-many (`() => author.books.count()`) or a column expression. The callback's refs are the entity's own columns and its relations, so one expression can combine them.
186
186
  - A hook is a function of the row and `{ querier, onCommit }`.
187
187
  - A JSON column's payload is a Standard Schema, `f.json(schema)`, typed by its output: any library's schema (Zod, Valibot, ArkType), or a hand-written `StandardSchemaV1`. Without one, any path reads. The schema types the column; uql never runs it, so a write is not validated.
File without changes