uql-orm 0.105.1 → 0.106.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/uql-browser.min.js.map +1 -1
- package/dist/entity/columnOptionsBuilder.d.ts +3 -3
- package/dist/entity/columnOptionsBuilder.js +3 -5
- package/dist/entity/decorator/members.d.ts +1 -1
- package/dist/entity/metadata/definition.d.ts +5 -3
- package/dist/entity/metadata/definition.js +67 -84
- package/dist/entity/metadata/schemaFixture/animal.d.ts +17 -5
- package/dist/entity/metadata/schemaFixture/author.d.ts +10 -10
- package/dist/entity/metadata/schemaFixture/author.js +3 -3
- package/dist/entity/metadata/schemaFixture/book.d.ts +20 -20
- package/dist/migrate/builder/types.d.ts +5 -7
- package/dist/migrate/cli.js +13 -13
- package/dist/migrate/generator/definitionToNode.d.ts +1 -1
- package/dist/migrate/generator/definitionToNode.js +4 -8
- package/dist/mongodb/mongoIntrospector.d.ts +1 -1
- package/dist/mongodb/mongoSchemaGenerator.js +4 -7
- package/dist/pglite/pgliteQuerierPool.d.ts +2 -2
- package/dist/schema/schemaASTBuilder.js +6 -12
- package/dist/sqlite/localSqliteQuerierPool.d.ts +3 -2
- package/dist/type/column.d.ts +21 -20
- package/dist/type/entity.d.ts +51 -64
- package/dist/type/index.d.ts +1 -0
- package/dist/type/index.js +1 -0
- package/dist/type/query.d.ts +1 -1
- package/dist/type/schemaEntity.d.ts +42 -45
- package/dist/type/standardSchema.d.ts +28 -0
- package/dist/type/standardSchema.js +1 -0
- package/dist/type/utility.d.ts +21 -32
- package/dist/type/vector.d.ts +4 -4
- package/dist/util/ddlExpression.util.d.ts +6 -6
- package/dist/util/ddlExpression.util.js +11 -5
- package/dist/util/fieldOption.util.js +1 -1
- package/dist/util/sql.d.ts +1 -3
- package/dist/util/sql.js +0 -4
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +25 -10
|
@@ -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 ? Omit<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 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",
|
|
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,5 +1,5 @@
|
|
|
1
1
|
import type { ForeignKeyAction } from '../schema/types.js';
|
|
2
|
-
import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type
|
|
2
|
+
import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance } from '../type/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
|
|
5
5
|
* `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
|
|
@@ -44,8 +44,8 @@ export declare const columns: {
|
|
|
44
44
|
decimal: (precision?: number, scale?: number) => ColumnOptionsBuilder;
|
|
45
45
|
boolean: () => ColumnOptionsBuilder;
|
|
46
46
|
date: () => ColumnOptionsBuilder;
|
|
47
|
-
json: (
|
|
48
|
-
jsonb: (
|
|
47
|
+
json: (schema?: StandardSchemaV1) => ColumnOptionsBuilder;
|
|
48
|
+
jsonb: (schema?: StandardSchemaV1) => ColumnOptionsBuilder;
|
|
49
49
|
vector: (dimensions: number) => ColumnOptionsBuilder;
|
|
50
50
|
enum: (members: readonly string[] | readonly number[]) => ColumnOptionsBuilder;
|
|
51
51
|
version: (type?: NumberConstructor | BigIntConstructor) => ColumnOptionsBuilder;
|
|
@@ -85,9 +85,7 @@ export class ColumnOptionsBuilder {
|
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
const column = (options) => new ColumnOptionsBuilder(options);
|
|
88
|
-
|
|
89
|
-
return column({ type, ...(shape && { shape }) });
|
|
90
|
-
}
|
|
88
|
+
const jsonColumn = (type) => (schema) => column({ type, ...(schema && { schema }) });
|
|
91
89
|
/** The column constructors at run time, which `f` types and the migration builder names. */
|
|
92
90
|
export const columns = {
|
|
93
91
|
string: () => column({ type: String }),
|
|
@@ -98,8 +96,8 @@ export const columns = {
|
|
|
98
96
|
decimal: (precision, scale) => column({ type: 'decimal', ...(precision !== undefined && { precision }), ...(scale !== undefined && { scale }) }),
|
|
99
97
|
boolean: () => column({ type: Boolean }),
|
|
100
98
|
date: () => column({ type: Date }),
|
|
101
|
-
json: (
|
|
102
|
-
jsonb: (
|
|
99
|
+
json: jsonColumn('json'),
|
|
100
|
+
jsonb: jsonColumn('jsonb'),
|
|
103
101
|
vector: (dimensions) => column({ type: 'vector', dimensions }),
|
|
104
102
|
enum: (members) => column({ type: typeof members[0] === 'number' ? Number : String, enum: members }),
|
|
105
103
|
version: (type = Number) => column({ type, version: true }),
|
|
@@ -41,7 +41,7 @@ type ComputedColumn = Column<{
|
|
|
41
41
|
type ComputedValue<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O, infer V> ? V | NullOf<O> : never;
|
|
42
42
|
/** What the property has to admit: all of an aggregate's value, which is exact, and a column's `null`. */
|
|
43
43
|
type ComputedAdmits<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O> ? NullOf<O> : never;
|
|
44
|
-
/** A JSON column with no
|
|
44
|
+
/** A JSON column with no schema holds any document, which the property narrows: `Json<Settings>`. */
|
|
45
45
|
type Narrowable<V> = IsEqual<V, Json> extends true ? JsonBrand | readonly JsonBrand[] : V;
|
|
46
46
|
/** Whether the column is a key, which the class has to name. */
|
|
47
47
|
type IsKey<O> = O extends {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EntityGetter, type EntityMeta, type EntityOptions, type FieldMeta, type IdKey, type KeyMap, type RelationKey, type RelationMeta, type RelationOptions, type RelationRegistration, type SchemaEntityOptions, type Brands, 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 SchemaEntityOptions, type Brands, type EntityBrand, type ColumnRow, type SchemaFields, type SchemaKey, type Type, type AbstractType, type WrittenId, type SchemaEntity } 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,6 +11,7 @@ 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
15
|
/**
|
|
15
16
|
* Declares an entity by its schema and returns its class, whose row type the schema derives, so nothing is
|
|
16
17
|
* written twice: its columns now, then each section, `.indexes()` and so on, `.relations()` last but for
|
|
@@ -18,8 +19,8 @@ export declare function keyOf<E, K extends keyof E>(pick: (keys: KeyMap<E>) => K
|
|
|
18
19
|
*/
|
|
19
20
|
export declare function defineEntity<const F extends SchemaFields, B = object, BK = unknown, BC = unknown>(schema: SchemaEntityOptions<F, B, BK, BC> & {
|
|
20
21
|
readonly abstract: true;
|
|
21
|
-
}): SchemaEntity<
|
|
22
|
-
export declare function defineEntity<const F extends SchemaFields, B = object, BK = unknown, BC = unknown>(schema: SchemaEntityOptions<F, B, BK, BC>): SchemaEntity<
|
|
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>;
|
|
23
24
|
/**
|
|
24
25
|
* The registration both forms share, a schema's `members` given as the decorators would register them. Built
|
|
25
26
|
* apart and stored once it passes, so a rejected definition leaves the registry as it was.
|
|
@@ -71,3 +72,4 @@ export declare function getMeta<E>(entity: AbstractType<E>): EntityMeta<E>;
|
|
|
71
72
|
* schema build constrains and a junction joins by, settling the relations holding them first.
|
|
72
73
|
*/
|
|
73
74
|
export declare function foreignKeysOf<E>(meta: EntityMeta<E>): RelationMeta[];
|
|
75
|
+
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { COLUMN_OPTIONS, REF_KEY, RelationAggregate, SECTION_ENTRY, SOFT_DELETE_FILTER, } from '../../type/index.js';
|
|
2
2
|
import { aggregateField, defaultReadKeys, fieldKeys, isInlinedExpression } from '../../util/field.util.js';
|
|
3
|
-
import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs,
|
|
3
|
+
import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, isRecord, whereWith, } from '../../util/index.js';
|
|
4
4
|
import { UqlUsageError } from '../../util/uqlError.js';
|
|
5
5
|
import { ownRegistrations } from '../decorator/bag.js';
|
|
6
6
|
/**
|
|
@@ -36,7 +36,11 @@ function addField(meta, key, opts) {
|
|
|
36
36
|
// Flagged when the author gave `references` but no `type`, so schema generation knows to resolve the
|
|
37
37
|
// column from the referenced primary key (picking up its `columnType`, length and chained keys)
|
|
38
38
|
// instead of treating whatever ends up in `type` as deliberate.
|
|
39
|
-
|
|
39
|
+
fieldStore(meta)[key] = { name: key, ...opts, ...(!opts.type && { typeFromReference: true }) };
|
|
40
|
+
}
|
|
41
|
+
/** `meta`'s fields as a store a key is written into: a generic entity's fields are read-only by type. */
|
|
42
|
+
function fieldStore(meta) {
|
|
43
|
+
return meta.fields;
|
|
40
44
|
}
|
|
41
45
|
/**
|
|
42
46
|
* `opts` as the registry takes them: `mappedBy` and `references` read off their key maps down to the
|
|
@@ -163,27 +167,21 @@ export function defineEntity(schema) {
|
|
|
163
167
|
}[schema.name];
|
|
164
168
|
metas.set(entity, { ...emptyMeta(entity), stage: 'declared' });
|
|
165
169
|
declaredSchemas.set(entity, { schema, sections: {} });
|
|
166
|
-
for (const section of
|
|
170
|
+
for (const section of SECTIONS) {
|
|
167
171
|
Object.defineProperty(entity, section, {
|
|
168
|
-
value(
|
|
172
|
+
value(declared, derived) {
|
|
169
173
|
declareSection(this, section, declared);
|
|
174
|
+
if (section === 'relations' && derived) {
|
|
175
|
+
declareSection(this, 'derived', derived);
|
|
176
|
+
}
|
|
170
177
|
return this;
|
|
171
178
|
},
|
|
172
179
|
});
|
|
173
180
|
}
|
|
174
181
|
return entity;
|
|
175
182
|
}
|
|
176
|
-
/** The sections a schema declares as methods. `
|
|
177
|
-
const SECTIONS =
|
|
178
|
-
computed: true,
|
|
179
|
-
indexes: true,
|
|
180
|
-
checks: true,
|
|
181
|
-
triggers: true,
|
|
182
|
-
filters: true,
|
|
183
|
-
hooks: true,
|
|
184
|
-
references: true,
|
|
185
|
-
relations: true,
|
|
186
|
-
};
|
|
183
|
+
/** The sections a schema declares as methods. `derived` is no method: `relations` takes it as its second argument. */
|
|
184
|
+
const SECTIONS = ['computed', 'indexes', 'checks', 'triggers', 'filters', 'hooks', 'relations'];
|
|
187
185
|
/** Records one section of a pending schema, refusing a second of it and one declared after the entity was read. */
|
|
188
186
|
function declareSection(entity, section, declared) {
|
|
189
187
|
const pending = pendingSchema(entity);
|
|
@@ -193,8 +191,7 @@ function declareSection(entity, section, declared) {
|
|
|
193
191
|
if (section in pending.sections) {
|
|
194
192
|
throw new UqlUsageError(`'${entity.name}' declares its ${section} twice: declare them in one call`);
|
|
195
193
|
}
|
|
196
|
-
|
|
197
|
-
Object.assign(pending.sections, { [section]: first }, section === 'relations' && aggregates && { aggregates });
|
|
194
|
+
Object.assign(pending.sections, { [section]: declared });
|
|
198
195
|
}
|
|
199
196
|
/** What `entity` declared as a schema, while it is not registered yet. */
|
|
200
197
|
function pendingSchema(entity) {
|
|
@@ -207,11 +204,12 @@ function settleSchema(entity) {
|
|
|
207
204
|
return;
|
|
208
205
|
}
|
|
209
206
|
const { schema, sections } = pending;
|
|
210
|
-
const fields =
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
207
|
+
const fields = fieldsOf(schema.name, schema.fields);
|
|
208
|
+
const refs = memberRefs();
|
|
209
|
+
for (const added of [
|
|
210
|
+
fieldsOf(schema.name, sections.computed?.(refs) ?? {}),
|
|
211
|
+
fieldsOf(schema.name, readDerived(sections.derived, refs)),
|
|
212
|
+
]) {
|
|
215
213
|
const taken = Object.keys(added).find((key) => key in fields);
|
|
216
214
|
if (taken) {
|
|
217
215
|
throw new UqlUsageError(`'${schema.name}.${taken}' is declared twice: name each member once`);
|
|
@@ -231,24 +229,6 @@ function settleSchema(entity) {
|
|
|
231
229
|
hooks: Object.fromEntries(definedEntries(sections.hooks ?? {}).map(([event, runs]) => [event, runs.map((run) => ({ run }))])),
|
|
232
230
|
});
|
|
233
231
|
}
|
|
234
|
-
/** Each foreign key `.references()` names, written onto its column as `@Field`'s `references()` would. */
|
|
235
|
-
function referencedFields(name, fields, references) {
|
|
236
|
-
return Object.fromEntries(Object.entries(references ?? {}).map(([key, target]) => {
|
|
237
|
-
const column = fields[key]?.[COLUMN_OPTIONS];
|
|
238
|
-
if (!column) {
|
|
239
|
-
throw new UqlUsageError(`'.references()' names '${name}.${key}', which is no column of its 'fields'`);
|
|
240
|
-
}
|
|
241
|
-
const { entity, ...action } = typeof target === 'function' ? { entity: target } : target;
|
|
242
|
-
return [key, { ...column, ...action, references: () => entityOf(entity(), key) }];
|
|
243
|
-
}));
|
|
244
|
-
}
|
|
245
|
-
/** The entity a getter returned, refused where it returned anything else. */
|
|
246
|
-
function entityOf(target, key) {
|
|
247
|
-
if (!metas.has(target) || !isTable(target)) {
|
|
248
|
-
throw new UqlUsageError(`'.references()' points '${key}' at something that is not an entity`);
|
|
249
|
-
}
|
|
250
|
-
return target;
|
|
251
|
-
}
|
|
252
232
|
/** An index as a section's `index(columns, options)` writes it, a bare string its name. */
|
|
253
233
|
function indexEntry(columns, options) {
|
|
254
234
|
const stated = typeof options === 'string' ? { name: options } : options;
|
|
@@ -260,25 +240,26 @@ function checkEntry(where, name) {
|
|
|
260
240
|
function triggerEntry(trigger) {
|
|
261
241
|
return { ...trigger, [SECTION_ENTRY]: 'trigger' };
|
|
262
242
|
}
|
|
263
|
-
/** The options
|
|
264
|
-
function
|
|
265
|
-
return Object.fromEntries(Object.entries(
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
return columnOptions(computed?.(memberRefs()) ?? {});
|
|
270
|
-
}
|
|
271
|
-
/** A schema's aggregates as the computed fields they read as, through the refs a decorated `@Computed` reads. */
|
|
272
|
-
function aggregateFields(name, aggregates) {
|
|
273
|
-
return Object.fromEntries(Object.entries(aggregates?.(relationRefs()) ?? {}).map(([key, read]) => {
|
|
274
|
-
const aggregate = typeof read === 'function' ? read() : undefined;
|
|
243
|
+
/** The fields a section's values define: a column's options, or an aggregate, which reads as a computed column. */
|
|
244
|
+
function fieldsOf(name, values) {
|
|
245
|
+
return Object.fromEntries(Object.entries(values).map(([key, field]) => {
|
|
246
|
+
if (field instanceof RelationAggregate) {
|
|
247
|
+
return [key, aggregateField(field)];
|
|
248
|
+
}
|
|
275
249
|
// The types refuse anything else; an untyped caller still reaches here.
|
|
276
|
-
if (!(
|
|
277
|
-
throw new UqlUsageError(`'${name}.${key}'
|
|
250
|
+
if (!isColumn(field)) {
|
|
251
|
+
throw new UqlUsageError(`'${name}.${key}' is neither a column nor an aggregate: declare it as one`);
|
|
278
252
|
}
|
|
279
|
-
return [key,
|
|
253
|
+
return [key, field[COLUMN_OPTIONS]];
|
|
280
254
|
}));
|
|
281
255
|
}
|
|
256
|
+
function isColumn(field) {
|
|
257
|
+
return isRecord(field) && COLUMN_OPTIONS in field;
|
|
258
|
+
}
|
|
259
|
+
/** A relation's derived fields, each a thunk read lazily; a value that is no thunk is passed on to be refused. */
|
|
260
|
+
function readDerived(derived, refs) {
|
|
261
|
+
return Object.fromEntries(Object.entries(derived?.(refs) ?? {}).map(([key, read]) => [key, typeof read === 'function' ? read() : read]));
|
|
262
|
+
}
|
|
282
263
|
const RELATION_BUILDER = {
|
|
283
264
|
oneToOne: (target, options) => ({ target, cardinality: '11', options }),
|
|
284
265
|
manyToOne: (target, options) => ({ target, cardinality: 'm1', options }),
|
|
@@ -649,34 +630,33 @@ function fillInverseSide(at, meta, relOpts, mappedBy) {
|
|
|
649
630
|
return relOpts.references;
|
|
650
631
|
}
|
|
651
632
|
/**
|
|
652
|
-
* Refuses a join on a column either entity does not store,
|
|
653
|
-
*
|
|
633
|
+
* Refuses a join on a column either entity does not store, a one-column join whose foreign key, on whichever
|
|
634
|
+
* side holds it, points at another entity, and a join whose column holds another kind of value than its key.
|
|
654
635
|
*/
|
|
655
636
|
function assertJoins(at, meta, relOpts, pairs) {
|
|
656
637
|
const target = registeredMeta(relOpts.entity());
|
|
657
638
|
// Only the owning side of a to-one holds its foreign key; an inverse side and a to-many join on the target's.
|
|
658
639
|
const holdsLocally = holdsForeignKey(relOpts);
|
|
659
|
-
const
|
|
660
|
-
|
|
661
|
-
{ meta
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
const column = `'${side.meta.entity.name}.${key}'`;
|
|
666
|
-
const field = side.meta.fields[key];
|
|
667
|
-
if (!field || isInlinedExpression(field)) {
|
|
668
|
-
throw new UqlUsageError(`${at} joins ${column}, which is not a column: declare it with '@Field'.`);
|
|
669
|
-
}
|
|
670
|
-
const referenced = side.holds && pairs.length === 1 ? field.references?.() : undefined;
|
|
671
|
-
if (referenced && !isA(side.joins, referenced)) {
|
|
672
|
-
throw new UqlUsageError(`${at} joins ${column}, a foreign key to '${referenced.name}', not to '${side.joins.name}'.`);
|
|
673
|
-
}
|
|
640
|
+
const single = pairs.length === 1;
|
|
641
|
+
for (const { local, foreign } of pairs) {
|
|
642
|
+
assertJoinColumn(at, { meta, key: local, joins: target.entity, holds: holdsLocally && single });
|
|
643
|
+
assertJoinColumn(at, { meta: target, key: foreign, joins: meta.entity, holds: !holdsLocally && single });
|
|
644
|
+
if (holdsLocally) {
|
|
645
|
+
assertKindsJoin(at, fieldOf(meta, local), valueFieldOf(fieldOf(target, foreign)), target.entity.name);
|
|
674
646
|
}
|
|
675
647
|
}
|
|
676
648
|
}
|
|
677
|
-
/**
|
|
678
|
-
function
|
|
679
|
-
|
|
649
|
+
/** Refuses a join column that is no column, or a foreign key to another entity than the one it joins. */
|
|
650
|
+
function assertJoinColumn(at, side) {
|
|
651
|
+
const column = `'${side.meta.entity.name}.${side.key}'`;
|
|
652
|
+
const field = side.meta.fields[side.key];
|
|
653
|
+
if (!field || isInlinedExpression(field)) {
|
|
654
|
+
throw new UqlUsageError(`${at} joins ${column}, which is not a column: declare it with '@Field'.`);
|
|
655
|
+
}
|
|
656
|
+
const referenced = side.holds ? field.references?.() : undefined;
|
|
657
|
+
if (referenced && !isA(side.joins, referenced)) {
|
|
658
|
+
throw new UqlUsageError(`${at} joins ${column}, a foreign key to '${referenced.name}', not to '${side.joins.name}'.`);
|
|
659
|
+
}
|
|
680
660
|
}
|
|
681
661
|
/** Whether `entity` is `base` or extends it, as an entity inheriting a relation does. */
|
|
682
662
|
function isA(entity, base) {
|
|
@@ -699,9 +679,12 @@ export function foreignKeysOf(meta) {
|
|
|
699
679
|
if (!field.references)
|
|
700
680
|
return [];
|
|
701
681
|
const target = knownMeta(field.references());
|
|
702
|
-
|
|
682
|
+
// A joined column's kinds were checked when its relation settled.
|
|
703
683
|
if (joined.has(key) || !target.ids.length)
|
|
704
684
|
return [];
|
|
685
|
+
if (!field.typeFromReference && target.ids.length === 1) {
|
|
686
|
+
assertKindsJoin(`'${meta.entity.name}.${key}'`, field, valueFieldOf(fieldOf(target, target.ids[0])), target.entity.name);
|
|
687
|
+
}
|
|
705
688
|
if (target.ids.length > 1) {
|
|
706
689
|
throw new UqlUsageError(`'${meta.entity.name}.${key}' cannot reference '${target.entity.name}', whose primary key is composite ` +
|
|
707
690
|
`(${target.ids.join(', ')}): a column points at one. Declare a column per key and pair each with it ` +
|
|
@@ -711,19 +694,19 @@ export function foreignKeysOf(meta) {
|
|
|
711
694
|
});
|
|
712
695
|
return [...owning, ...columns];
|
|
713
696
|
}
|
|
714
|
-
/** The kinds a column of `type` holds as a join compares them, as `
|
|
697
|
+
/** The kinds a column of `type` holds as a join compares them, as `JoinKind` does: a bigint is a number, which BIGINT widens. */
|
|
715
698
|
function joinedKinds(type) {
|
|
716
699
|
const types = valueTypesOf(type);
|
|
717
700
|
return types && [...new Set(types.map((kind) => (kind === 'bigint' ? 'number' : kind)))];
|
|
718
701
|
}
|
|
719
|
-
/** Refuses a
|
|
720
|
-
function
|
|
721
|
-
|
|
702
|
+
/** Refuses a join whose column holds another kind of value than the key it joins to, which no join matches. */
|
|
703
|
+
function assertKindsJoin(at, held, key, target) {
|
|
704
|
+
const heldKinds = joinedKinds(held.type);
|
|
705
|
+
if (!heldKinds)
|
|
722
706
|
return;
|
|
723
|
-
const
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
throw new UqlUsageError(`${at} holds a ${held.join(' or ')}, but the key of '${target.entity.name}' it references is a ${needed.join(' or ')}`);
|
|
707
|
+
const neededKinds = joinedKinds(key.type);
|
|
708
|
+
if (neededKinds && !neededKinds.every((kind) => heldKinds.includes(kind))) {
|
|
709
|
+
throw new UqlUsageError(`${at} holds a ${heldKinds.join(' or ')}, but the key of '${target}' it references is a ${neededKinds.join(' or ')}`);
|
|
727
710
|
}
|
|
728
711
|
}
|
|
729
712
|
/** Each key of `side`, paired with the one column of `junction` referencing it: a rename of either follows. */
|
|
@@ -10,11 +10,11 @@ export declare const Animal: import("../../../index.js").SchemaEntity<object & {
|
|
|
10
10
|
readonly name: import("../../../index.js").StringColumn<{
|
|
11
11
|
readonly type: StringConstructor;
|
|
12
12
|
}, string>;
|
|
13
|
-
}>, number, {
|
|
13
|
+
}, object>, number, {
|
|
14
14
|
id: number;
|
|
15
15
|
name: string;
|
|
16
16
|
} & {}, object>;
|
|
17
|
-
export declare const Dog: import("../../../index.js").SchemaEntity<object & {
|
|
17
|
+
export declare const Dog: import("../../../index.js").SchemaEntity<import("../../../index.js").Except<object & {
|
|
18
18
|
id: number;
|
|
19
19
|
name: string;
|
|
20
20
|
} & {} & import("../../../index.js").Brands<{
|
|
@@ -26,7 +26,7 @@ export declare const Dog: import("../../../index.js").SchemaEntity<object & {
|
|
|
26
26
|
readonly name: import("../../../index.js").StringColumn<{
|
|
27
27
|
readonly type: StringConstructor;
|
|
28
28
|
}, string>;
|
|
29
|
-
}> & {} & {
|
|
29
|
+
}, object>, typeof import("../../../index.js").idKey | typeof import("../../../index.js").versionKey | typeof import("../../../index.js").filledKey> & {} & {
|
|
30
30
|
tricks?: number | null | undefined;
|
|
31
31
|
} & import("../../../index.js").Brands<{
|
|
32
32
|
readonly tricks: import("../../../index.js").NumericColumn<{
|
|
@@ -34,7 +34,19 @@ export declare const Dog: import("../../../index.js").SchemaEntity<object & {
|
|
|
34
34
|
} & {
|
|
35
35
|
readonly nullable: true;
|
|
36
36
|
}, number>;
|
|
37
|
-
}
|
|
37
|
+
}, object & {
|
|
38
|
+
id: number;
|
|
39
|
+
name: string;
|
|
40
|
+
} & {} & import("../../../index.js").Brands<{
|
|
41
|
+
readonly id: import("../../../index.js").NumericColumn<{
|
|
42
|
+
readonly type: NumberConstructor;
|
|
43
|
+
} & {
|
|
44
|
+
readonly isId: true;
|
|
45
|
+
}, number>;
|
|
46
|
+
readonly name: import("../../../index.js").StringColumn<{
|
|
47
|
+
readonly type: StringConstructor;
|
|
48
|
+
}, string>;
|
|
49
|
+
}, object>>, number, {
|
|
38
50
|
id: number;
|
|
39
51
|
name: string;
|
|
40
52
|
} & {} & {} & {
|
|
@@ -51,4 +63,4 @@ export declare const Dog: import("../../../index.js").SchemaEntity<object & {
|
|
|
51
63
|
readonly name: import("../../../index.js").StringColumn<{
|
|
52
64
|
readonly type: StringConstructor;
|
|
53
65
|
}, string>;
|
|
54
|
-
}>>;
|
|
66
|
+
}, object>>;
|
|
@@ -23,7 +23,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
|
|
|
23
23
|
} & {
|
|
24
24
|
readonly defaultValue: unknown;
|
|
25
25
|
}, Date>;
|
|
26
|
-
}> & import("../../../index.js").RelationRow<{
|
|
26
|
+
}, object> & import("../../../index.js").RelationRow<{
|
|
27
27
|
readonly books: () => import("../../../index.js").SchemaRelation<object & {
|
|
28
28
|
id: number;
|
|
29
29
|
title: string;
|
|
@@ -56,9 +56,9 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
|
|
|
56
56
|
readonly authorId: import("../../../index.js").NumericColumn<{
|
|
57
57
|
readonly type: NumberConstructor;
|
|
58
58
|
}, number>;
|
|
59
|
-
}> & {
|
|
60
|
-
readonly shout
|
|
61
|
-
} & import("../../../index.js").RelationRow<{
|
|
59
|
+
}, object> & {
|
|
60
|
+
readonly shout: string | null;
|
|
61
|
+
} & {} & import("../../../index.js").RelationRow<{
|
|
62
62
|
readonly author: () => import("../../../index.js").SchemaRelation<object & {
|
|
63
63
|
id: number;
|
|
64
64
|
name: string;
|
|
@@ -84,7 +84,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
|
|
|
84
84
|
} & {
|
|
85
85
|
readonly defaultValue: unknown;
|
|
86
86
|
}, Date>;
|
|
87
|
-
}> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").
|
|
87
|
+
}, object> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").DerivedRow<{
|
|
88
88
|
readonly bookCount: () => import("../../../index.js").RelationAggregate<number>;
|
|
89
89
|
readonly topStock: () => import("../../../index.js").RelationAggregate<number | null>;
|
|
90
90
|
}>, "m1", object & {
|
|
@@ -112,11 +112,11 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
|
|
|
112
112
|
} & {
|
|
113
113
|
readonly defaultValue: unknown;
|
|
114
114
|
}, Date>;
|
|
115
|
-
}> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").
|
|
115
|
+
}, object> & import("../../../index.js").RelationRow</*elided*/ any> & import("../../../index.js").DerivedRow<{
|
|
116
116
|
readonly bookCount: () => import("../../../index.js").RelationAggregate<number>;
|
|
117
117
|
readonly topStock: () => import("../../../index.js").RelationAggregate<number | null>;
|
|
118
118
|
}>>;
|
|
119
|
-
}> & import("../../../index.js").
|
|
119
|
+
}> & import("../../../index.js").DerivedRow<{}>, "1m", {
|
|
120
120
|
id: number;
|
|
121
121
|
title: string;
|
|
122
122
|
stock: number;
|
|
@@ -124,9 +124,9 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
|
|
|
124
124
|
version: number;
|
|
125
125
|
authorId: number;
|
|
126
126
|
} & {} & {
|
|
127
|
-
readonly shout
|
|
128
|
-
}>;
|
|
129
|
-
}> & import("../../../index.js").
|
|
127
|
+
readonly shout: string | null;
|
|
128
|
+
} & {}>;
|
|
129
|
+
}> & import("../../../index.js").DerivedRow<{
|
|
130
130
|
readonly bookCount: () => import("../../../index.js").RelationAggregate<number>;
|
|
131
131
|
readonly topStock: () => import("../../../index.js").RelationAggregate<number | null>;
|
|
132
132
|
}>, number, {
|