uql-orm 0.103.2 → 0.104.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.
@@ -1,4 +1,4 @@
1
- var c=new Set;function l(e){for(let r of c)r(e)}function U(e){return c.add(e),()=>{c.delete(e)}}var f={$select:{value:"object",scope:"relation"},$populate:{value:"object",scope:"relation"},$exclude:{value:"object",scope:"relation"},$where:{value:"object",scope:"relation"},$sort:{value:"object",scope:"relation"},$skip:{value:"number",scope:"relation"},$limit:{value:"number",scope:"relation"},$distinct:{value:"boolean",scope:"relation"},$count:{value:"object",scope:"statement"},$candidates:{value:"number",scope:"statement"},$lock:{value:"object",scope:"statement"},$after:{value:"string",scope:"statement"},$before:{value:"string",scope:"statement"}};var R=Symbol("sqlFn"),F=Symbol("rawAlias"),A=Symbol("sqlText"),L=Symbol("sqlValueType");function d(e){return e?Object.keys(e):[]}function q(e){if(typeof e!=="object"||e===null)return!0;if(Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null}class b extends Error{}class i extends b{name="UqlUsageError";kind="usage";status=400}var k=["hardDelete","count"];var H=new Map([...d(f).map((e)=>[e,f[e].value]),...k.map((e)=>[e,"boolean"])]);function u(e){if(!e)return"";let r=new URLSearchParams;for(let n of d(e)){let s=e[n];if(s===void 0)continue;r.append(n,typeof s==="object"&&s!==null?a(s):String(s))}let t=r.toString();return t?`?${t}`:""}function a(e){return JSON.stringify(e,(r,t)=>{if(typeof t!=="object"||t===null)return t;if(R in t)throw new i("raw SQL cannot travel over HTTP: what leaves the browser is JSON");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))throw new i("binary cannot travel over HTTP: what leaves the browser is JSON");return t})}class P extends Error{status;constructor(e,r){super(e);this.status=r;this.name="RequestError"}}function h(e,r){return y(e,{method:"GET"},r)}function E(e,r,t){return y(e,{method:"POST",body:a(r)},t)}function x(e,r,t){return y(e,{method:"PATCH",body:a(r)},t)}function S(e,r,t){return y(e,{method:"PUT",body:a(r)},t)}function g(e,r){return y(e,{method:"DELETE"},r)}function T(e,r,t){return y(e,{method:"QUERY",body:a(r)},t)}function y(e,r,t){if(l({phase:"start",opts:t}),r.headers={accept:"application/json","content-type":"application/json",...t?.headers},t?.signal)r.signal=t.signal;return fetch(e,r).then((n)=>n.json().then((s)=>{if(n.status>=200&&n.status<300)return l({phase:"success",opts:t}),s;let m=s,p={message:m?.error?.message??n.statusText,code:m?.error?.code??n.status};throw l({phase:"error",error:p,opts:t}),new P(p.message,p.code)})).finally(()=>{l({phase:"complete",opts:t})})}function O(e){let r=e.charAt(0).toLowerCase();for(let t=1;t<e.length;++t)r+=e[t]===e[t].toUpperCase()?"-"+e[t].toLowerCase():e[t];return r}var o={findMany:{method:"GET",path:""},findManyPage:{method:"GET",path:"/page"},findOne:{method:"GET",path:"/one"},count:{method:"GET",path:"/count"},findOneById:{method:"GET",path:"/:id"},insertOne:{method:"POST",path:""},insertMany:{method:"POST",path:"/many"},saveOne:{method:"PUT",path:""},saveMany:{method:"PUT",path:"/many"},updateMany:{method:"PATCH",path:""},updateOneById:{method:"PATCH",path:"/:id"},deleteOneById:{method:"DELETE",path:"/:id"},deleteMany:{method:"DELETE",path:""}},w=d(o),ne=new Map(w.filter((e)=>o[e].method==="GET"&&o[e].path!=="/:id").map((e)=>[o[e].path,e]));function C(e){return O(e.name)}function Q(e,r){if(!q(r))throw new i(`'${e.name}' was addressed by an id object, which the HTTP route cannot carry.`);return String(r)}class K{basePath;defaults;constructor(e,r={}){this.basePath=e;this.defaults=r}findOneById=async(e,r,t,n)=>h(`${this.getBasePath(e)}/${Q(e,r)}${u(t)}`,this.buildOptions(n));findOne=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findOne.path}`,r,t);findMany=(e,r,t)=>this.read(this.getBasePath(e),t?.count?{...r,count:!0}:r,t);findManyAndCount=async(e,r,t)=>{let n=await this.findMany(e,r,{...t,count:!0});if(typeof n.count!=="number")throw TypeError("findManyAndCount response has an invalid count");return{...n,count:n.count}};findManyPage=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findManyPage.path}`,r,t);count=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.count.path}`,r,t);exists=async(e,r,t)=>{let n=await this.count(e,{...r,$limit:1},t);return{...n,data:n.data>0}};insertOne=(e,r,t)=>E(this.getBasePath(e),r,this.buildOptions(t));insertMany=(e,r,t)=>E(`${this.getBasePath(e)}${o.insertMany.path}`,r,this.buildOptions(t));updateOneById=async(e,r,t,n)=>x(`${this.getBasePath(e)}/${Q(e,r)}`,t,this.buildOptions(n));updateMany=(e,r,t,n)=>x(`${this.getBasePath(e)}${u(r)}`,t,this.buildOptions(n));saveOne=(e,r,t)=>S(this.getBasePath(e),r,this.buildOptions(t));saveMany=(e,r,t)=>S(`${this.getBasePath(e)}${o.saveMany.path}`,r,this.buildOptions(t));deleteOneById=async(e,r,t={})=>{let n=t.hardDelete?u({hardDelete:t.hardDelete}):"";return g(`${this.getBasePath(e)}/${Q(e,r)}${n}`,this.buildOptions(t))};deleteMany=(e,r,t={})=>g(`${this.getBasePath(e)}${u(t.hardDelete?{...r,hardDelete:t.hardDelete}:r)}`,this.buildOptions(t));getBasePath(e){return`${this.basePath}/${(this.defaults.entityPath??C)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return T(e,r??{},this.buildOptions(t));return h(`${e}${u(r)}`,this.buildOptions(t))}buildOptions(e){if(!this.defaults.headers&&!e?.headers)return e;return{...e,headers:{...this.defaults.headers,...e?.headers}}}}export{K as HttpQuerier,P as RequestError,h as get,l as notify,U as on,x as patch,E as post,S as put,T as query,g as remove};
1
+ var c=new Set;function l(e){for(let r of c)r(e)}function U(e){return c.add(e),()=>{c.delete(e)}}var f={$select:{value:"object",scope:"relation"},$populate:{value:"object",scope:"relation"},$exclude:{value:"object",scope:"relation"},$where:{value:"object",scope:"relation"},$sort:{value:"object",scope:"relation"},$skip:{value:"number",scope:"relation"},$limit:{value:"number",scope:"relation"},$distinct:{value:"boolean",scope:"relation"},$count:{value:"object",scope:"statement"},$candidates:{value:"number",scope:"statement"},$lock:{value:"object",scope:"statement"},$after:{value:"string",scope:"statement"},$before:{value:"string",scope:"statement"}};var R=Symbol("sqlFn"),j=Symbol("rawAlias"),A=Symbol("sqlText"),L=Symbol("sqlValueType");function d(e){return e?Object.keys(e):[]}function k(e){if(typeof e!=="object"||e===null)return!0;if(Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null}class b extends Error{}class i extends b{name="UqlUsageError";kind="usage";status=400}var P=["hardDelete","count"];var H=new Map([...d(f).map((e)=>[e,f[e].value]),...P.map((e)=>[e,"boolean"])]);function a(e){if(!e)return"";let r=new URLSearchParams;for(let n of d(e)){let s=e[n];if(s===void 0)continue;r.append(n,typeof s==="object"&&s!==null?u(s):String(s))}let t=r.toString();return t?`?${t}`:""}function u(e){return JSON.stringify(e,(r,t)=>{if(typeof t!=="object"||t===null)return t;if(R in t)throw new i("raw SQL cannot travel over HTTP: what leaves the browser is JSON");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))throw new i("binary cannot travel over HTTP: what leaves the browser is JSON");return t})}class T extends Error{status;constructor(e,r){super(e);this.status=r;this.name="RequestError"}}function E(e,r){return y(e,{method:"GET"},r)}function h(e,r,t){return y(e,{method:"POST",body:u(r)},t)}function x(e,r,t){return y(e,{method:"PATCH",body:u(r)},t)}function Q(e,r,t){return y(e,{method:"PUT",body:u(r)},t)}function g(e,r){return y(e,{method:"DELETE"},r)}function w(e,r,t){return y(e,{method:"QUERY",body:u(r)},t)}function y(e,r,t){if(l({phase:"start",opts:t}),r.headers={accept:"application/json","content-type":"application/json",...t?.headers},t?.signal)r.signal=t.signal;return fetch(e,r).then((n)=>n.json().then((s)=>{if(n.status>=200&&n.status<300)return l({phase:"success",opts:t}),s;let m=s,p={message:m?.error?.message??n.statusText,code:m?.error?.code??n.status};throw l({phase:"error",error:p,opts:t}),new T(p.message,p.code)})).finally(()=>{l({phase:"complete",opts:t})})}function O(e){let r=e.charAt(0).toLowerCase();for(let t=1;t<e.length;++t)r+=e[t]===e[t].toUpperCase()?"-"+e[t].toLowerCase():e[t];return r}var o={findMany:{method:"GET",path:""},findManyPage:{method:"GET",path:"/page"},findOne:{method:"GET",path:"/one"},count:{method:"GET",path:"/count"},findOneById:{method:"GET",path:"/:id"},insertOne:{method:"POST",path:""},insertMany:{method:"POST",path:"/many"},saveOne:{method:"PUT",path:""},saveMany:{method:"PUT",path:"/many"},updateMany:{method:"PATCH",path:""},updateOneById:{method:"PATCH",path:"/:id"},deleteOneById:{method:"DELETE",path:"/:id"},deleteMany:{method:"DELETE",path:""}},M=d(o),ne=new Map(M.filter((e)=>o[e].method==="GET"&&o[e].path!=="/:id").map((e)=>[o[e].path,e]));function q(e){return O(e.name)}function S(e,r){if(!k(r))throw new i(`'${e.name}' was addressed by an id object, which the HTTP route cannot carry.`);return String(r)}class K{basePath;defaults;constructor(e,r={}){this.basePath=e;this.defaults=r}findOneById=async(e,r,t,n)=>E(`${this.getBasePath(e)}/${S(e,r)}${a(t)}`,this.buildOptions(n));findOne=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findOne.path}`,r,t);findMany=(e,r,t)=>this.read(this.getBasePath(e),t?.count?{...r,count:!0}:r,t);findManyAndCount=async(e,r,t)=>{let n=await this.findMany(e,r,{...t,count:!0});if(typeof n.count!=="number")throw TypeError("findManyAndCount response has an invalid count");return{...n,count:n.count}};findManyPage=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findManyPage.path}`,r,t);count=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.count.path}`,r,t);exists=async(e,r,t)=>{let n=await this.count(e,{...r,$limit:1},t);return{...n,data:n.data>0}};insertOne=(e,r,t)=>h(this.getBasePath(e),r,this.buildOptions(t));insertMany=(e,r,t)=>h(`${this.getBasePath(e)}${o.insertMany.path}`,r,this.buildOptions(t));updateOneById=async(e,r,t,n)=>x(`${this.getBasePath(e)}/${S(e,r)}`,t,this.buildOptions(n));updateMany=(e,r,t,n)=>x(`${this.getBasePath(e)}${a(r)}`,t,this.buildOptions(n));saveOne=(e,r,t)=>Q(this.getBasePath(e),r,this.buildOptions(t));saveMany=(e,r,t)=>Q(`${this.getBasePath(e)}${o.saveMany.path}`,r,this.buildOptions(t));deleteOneById=async(e,r,t={})=>{let n=t.hardDelete?a({hardDelete:t.hardDelete}):"";return g(`${this.getBasePath(e)}/${S(e,r)}${n}`,this.buildOptions(t))};deleteMany=(e,r,t={})=>g(`${this.getBasePath(e)}${a(t.hardDelete?{...r,hardDelete:t.hardDelete}:r)}`,this.buildOptions(t));getBasePath(e){return`${this.basePath}/${(this.defaults.entityPath??q)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return w(e,r??{},this.buildOptions(t));return E(`${e}${a(r)}`,this.buildOptions(t))}buildOptions(e){if(!this.defaults.headers&&!e?.headers)return e;return{...e,headers:{...this.defaults.headers,...e?.headers}}}}export{K as HttpQuerier,T as RequestError,E as get,l as notify,U as on,x as patch,h as post,Q as put,w as query,g as remove};
2
2
 
3
- //# debugId=35D479D13BD5FEE064756E2164756E21
3
+ //# debugId=5C47B677F680BF8464756E2164756E21
4
4
  //# sourceMappingURL=uql-browser.min.js.map
@@ -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 { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey } 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. `F` is also how a projection passes its captured key set.\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 * Fields to exclude from the query result - `{ name: true }` blacklists fields.\n * Mutually exclusive with positive field selections in `$select`.\n */\nexport type QueryExclude<E> = QuerySelect<E>;\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 })` / `@Filter` / `defineFilter`.\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 row with the value a `$sort` projects under the name its `$project` gives - a vector's distance, or a\n * `$text` relevance - which is not inferred: `(await querier.findMany(Post, q)) as WithProjection<Post, 'score'>[]`.\n */\nexport type WithProjection<E, K extends string> = E & Record<K, number>;\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, or raw SQL projections\n * (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * Mutually exclusive with `$exclude`.\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 * field exclusion - `{ name: true }` blacklists fields. Mutually exclusive with positive `$select`.\n * Keys a relation is assembled from (a joined row's primary key, a to-many's foreign key) are kept\n * regardless, since subtracting them would leave the relation unfilled.\n */\n $exclude?: QueryExclude<E>;\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 `sql` clause only in the statement itself.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\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 $exclude: { 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 // A populated relation's rows keep their declared type, so they have no `_count` for a `$count` to fill.\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 // Never decoded: HTTP refuses it, because a request cannot hold a lock past its response.\n $lock: { value: 'object', scope: 'statement' },\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' | '$exclude' | '$populate' | '$where'>;\n\n/**\n * The clauses that shape a row, captured as key sets rather than maps: a naked type parameter skips\n * excess-property checks, while a key set fails its own constraint on a typo.\n * @internal\n */\ntype QueryProjection<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E>,\n Sql = QuerySql,\n> = {\n $select?: QuerySelect<E, S, V> | readonly Sql[];\n $exclude?: QuerySelect<E, X, V>;\n $populate?: QueryPopulate<E, Sql, P>;\n // Narrowing the captured names to the to-many ones leaves a to-one relation no key here at all,\n // so counting one is an excess property rather than a value to check.\n $count?: QueryCount<E, Sql, C & ToManyRelationKey<E>>;\n};\n\n/**\n * A {@link Query} whose projection is captured, so {@link QueryFindResult} can shape the row.\n */\nexport type QueryProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n Sql = QuerySql,\n> = Query<E, Sql> & QueryProjection<E, S, V, X, P, C, Sql>;\n\n/**\n * A {@link QueryOne} whose projection is captured, so {@link QueryFindResult} can shape the row.\n */\nexport type QueryOneProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n Sql = QuerySql,\n> = QueryOne<E, Sql> & QueryProjection<E, S, V, X, P, C, Sql>;\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/** A {@link QueryKeyset} with its projection captured, so {@link QueryFindResult} can narrow the row. */\nexport type QueryKeysetProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n Sql = QuerySql,\n> = QueryKeyset<E, Sql> & QueryProjection<E, S, V, X, P, C, Sql>;\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 * The keys a query comes back with, as the runtime projects them: a positive `$select`'s, or every\n * field minus what `$select` or `$exclude` subtracts, plus the populated relations.\n * @internal\n */\ntype ProjectedKeys<E, S, V, X, P> =\n | ([V] extends [false | 0] ? Exclude<FieldKey<E>, S> : [S] extends [never] ? Exclude<FieldKey<E>, X> : S)\n | P;\n\n/**\n * Whether every entry of the captured map says the same thing: all selected, or all subtracted.\n * @internal\n */\ntype IsUniform<V> = [V] extends [true | 1] ? true : [V] extends [false | 0] ? true : false;\n\n/**\n * A find's row: the entity narrowed to what the query projected and populated, so reading anything\n * else does not compile. The entity itself where the projection is raw, absent or not uniform. Either\n * way, each populated to-many is a list.\n * @example `QueryFindResult<User, 'id' | 'name'>`\n */\nexport type QueryFindResult<\n E,\n S extends FieldKey<E> = never,\n // A whitelist by default, so the hand-written form reads `QueryFindResult<User, 'id' | 'name'>`.\n V = true,\n X extends FieldKey<E> = never,\n P extends RelationKey<E> = never,\n C extends RelationKey<E> = never,\n> = QueryProjectedRow<E, S, V, X, P> & PopulatedLists<E, P> & CountedRelations<C>;\n\n/**\n * The `_count` a query asked for, or an inert intersection member when it asked for none - so a read\n * without `$count` keeps exactly the row type it had.\n */\ntype CountedRelations<C extends PropertyKey> = [C] extends [never]\n ? unknown\n : { [K in typeof COUNT_RESULT_KEY]: { [R in C]: number } };\n\n/** @internal */\ntype QueryProjectedRow<E, S, V, X, P> = [S | X] extends [never]\n ? E\n : IsUniform<V> extends true\n ? // `Pick`, not a key remap: an entity keyed by an index signature - a content type defined at\n // runtime - has `string` for its keys, and a remap keeps no literal one, so every projection\n // over one came back as `{}`.\n Pick<E, ProjectedKeys<E, S, V, X, P> & keyof E>\n : E;\n\n/**\n * Each populated to-many as a list, empty where the parent has no children, so it maps without a guard.\n * Inert where the query populated nothing. A to-one keeps its modifier: a join finding no row leaves it absent.\n */\ntype PopulatedLists<E, P> = [P] extends [never]\n ? unknown\n : { [K in Extract<P, ToManyRelationKey<E>>]-?: NonNullable<E[K]> };\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>, V = true> = { readonly returning?: QuerySelect<E, S, V> };\n\n/** What a write resolves to: `Plain`, its ids or its count, where it names no `returning` field; else `Read`. */\nexport type ReturningResult<S, Plain, Read> = [S] extends [never] ? Plain : Read;\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 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 * Fields to exclude from the query result - `{ name: true }` blacklists fields.\n * Mutually exclusive with positive field selections in `$select`.\n */\nexport type QueryExclude<E> = QuerySelect<E>;\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 })` / `@Filter` / `defineFilter`.\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 row with the value a `$sort` projects under the name its `$project` gives - a vector's distance, or a\n * `$text` relevance - which is not inferred: `(await querier.findMany(Post, q)) as WithProjection<Post, 'score'>[]`.\n */\nexport type WithProjection<E, K extends string> = E & Record<K, number>;\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, or raw SQL projections\n * (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * Mutually exclusive with `$exclude`.\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 * field exclusion - `{ name: true }` blacklists fields. Mutually exclusive with positive `$select`.\n * Keys a relation is assembled from (a joined row's primary key, a to-many's foreign key) are kept\n * regardless, since subtracting them would leave the relation unfilled.\n */\n $exclude?: QueryExclude<E>;\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 `sql` clause only in the statement itself.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\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 $exclude: { 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 // Never decoded: HTTP refuses it, because a request cannot hold a lock past its response.\n $lock: { value: 'object', scope: 'statement' },\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' | '$exclude' | '$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. The entity itself where nothing narrows it. A key union names\n * a projection by hand. `K` is internal: `Q` whole, for a key union the test on `Q` distributes over.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}, K extends Q = Q> = Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : [K] extends [PropertyKey]\n ? Pick<E, K & keyof E>\n : E;\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery =\n | { readonly $select: object }\n | { readonly $exclude: object }\n | { readonly $populate: object }\n | { readonly $count: object };\n\n/**\n * A nested relation's row, 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`.\n */\ntype FindRow<E, Q> = Q extends ShapingQuery ? ShapedRow<E, Q> : E;\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 subtracts, as a truthy `$exclude` entry does. `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 : Q extends { readonly $exclude: infer M }\n ? (M[keyof M] extends true | 1\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, Exclude<FieldKey<E>, OnKeys<M> | MaybeKeys<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 } ? Omit<E, keyof M & keyof E> : 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, Type } 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?: Type<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\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 /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */\n render(opts: QuerySqlRenderOptions): void {\n const emitted = this[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/**\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\n constructor(\n readonly key: K,\n value: QuerySqlFn,\n ) {\n super(value);\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 `@Field({ version })` 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",
@@ -13,7 +13,7 @@
13
13
  "import { queryErrorKind } from '../querier/queryError.js';\nimport type { Type, UniversalQuerier } from '../type/index.js';\n// the specific util modules, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys } from '../util/object.util.js';\nimport { kebabCase } from '../util/string.util.js';\nimport type { QueryErrorKind } from '../util/uqlError.js';\n\ntype RouteShape = {\n readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly path: '' | `/${string}`;\n};\n\n/**\n * Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.\n * Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method\n * (or routing a non-existent one) is a compile error.\n */\nexport const CRUD_ROUTES = {\n findMany: { method: 'GET', path: '' },\n findManyPage: { method: 'GET', path: '/page' },\n findOne: { method: 'GET', path: '/one' },\n count: { method: 'GET', path: '/count' },\n findOneById: { method: 'GET', path: '/:id' },\n insertOne: { method: 'POST', path: '' },\n insertMany: { method: 'POST', path: '/many' },\n saveOne: { method: 'PUT', path: '' },\n saveMany: { method: 'PUT', path: '/many' },\n updateMany: { method: 'PATCH', path: '' },\n updateOneById: { method: 'PATCH', path: '/:id' },\n deleteOneById: { method: 'DELETE', path: '/:id' },\n deleteMany: { method: 'DELETE', path: '' },\n} as const satisfies Partial<Record<keyof UniversalQuerier, RouteShape>>;\n\nexport type CrudOperation = keyof typeof CRUD_ROUTES;\n\nexport type CrudRoute = (typeof CRUD_ROUTES)[CrudOperation];\n\n/**\n * `QUERY` (RFC 10008) is an alternate transport for the read operations: same semantics as the\n * GET routes, but the JSON query travels in the request body instead of the query string,\n * avoiding URL-length limits for large queries.\n */\nexport type HttpMethod = CrudRoute['method'] | 'QUERY';\n\nconst CRUD_OPS = getKeys(CRUD_ROUTES);\n\n// derived from CRUD_ROUTES (the literal-path GET routes) so the sub-paths live in exactly one place\nconst QUERY_READ_OPS: ReadonlyMap<string, CrudOperation> = new Map(\n CRUD_OPS.filter((op) => CRUD_ROUTES[op].method === 'GET' && CRUD_ROUTES[op].path !== '/:id').map((op) => [\n CRUD_ROUTES[op].path,\n op,\n ]),\n);\n\n/**\n * URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.\n */\nexport function entityPath<E>(entity: Type<E>): string {\n return kebabCase(entity.name);\n}\n\nexport type RouteMatch = {\n readonly op: CrudOperation;\n /**\n * the resolved transport method - differs from the op's canonical route method for QUERY.\n */\n readonly method: HttpMethod;\n readonly id?: string;\n};\n\n/**\n * Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.\n */\nexport function matchRoute(method: string, subPath: string | undefined): RouteMatch | undefined {\n const raw = method.toUpperCase();\n const literal = subPath === undefined ? '' : `/${subPath}`;\n if (raw === 'QUERY') {\n const op = QUERY_READ_OPS.get(literal);\n return op ? { op, method: 'QUERY' } : undefined;\n }\n // HEAD reads like GET per HTTP semantics; the server runtime omits the response body\n const verb = raw === 'HEAD' ? 'GET' : raw;\n let idOp: CrudOperation | undefined;\n for (const op of CRUD_OPS) {\n const route = CRUD_ROUTES[op];\n if (route.method !== verb) {\n continue;\n }\n if (route.path === literal) {\n return { op, method: route.method };\n }\n if (route.path === '/:id') {\n idOp = op;\n }\n }\n return idOp && subPath !== undefined ? { op: idOp, method: CRUD_ROUTES[idOp].method, id: subPath } : undefined;\n}\n\nexport type RequestErrorResponse = {\n readonly error: {\n readonly message: string;\n readonly code: number;\n };\n};\n\n/** Generic on purpose: a driver's constraint message names tables and constraints, and Postgres echoes the value. */\nconst CONSTRAINT_ERRORS: ReadonlyMap<QueryErrorKind | undefined, RequestErrorResponse['error']> = new Map([\n ['uniqueViolation', { message: 'Conflict', code: 409 }],\n ['foreignKeyViolation', { message: 'Conflict', code: 409 }],\n ['notNullViolation', { message: 'Bad Request', code: 400 }],\n ['checkViolation', { message: 'Bad Request', code: 400 }],\n]);\n\n/**\n * Map a thrown error to the wire error envelope. Honors a numeric `status` on the error\n * (e.g. hooks throwing 403), then a constraint violation (409/400), defaults to 500; `code` mirrors the HTTP status.\n */\nexport function toErrorResponse(err: unknown): { status: number; body: RequestErrorResponse } {\n const error =\n err instanceof Error && 'status' in err && typeof err.status === 'number'\n ? { message: err.message, code: err.status }\n : (CONSTRAINT_ERRORS.get(queryErrorKind(err)) ?? {\n message: err instanceof Error ? err.message : 'Internal Server Error',\n code: 500,\n });\n return { status: error.code, body: { error } };\n}\n",
14
14
  "import { CRUD_ROUTES, entityPath, type HttpMethod } from '../../http/contract.js';\nimport { stringifyQuery } from '../../http/query.js';\nimport type { EntityId, SharedQuerier, Type } from '../../type/index.js';\nimport { isScalarId } from '../../util/object.util.js';\nimport { UqlUsageError } from '../../util/uqlError.js';\nimport { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';\nimport type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';\n\nexport type HttpQuerierDefaults = {\n /**\n * headers sent with every request from this instance, merged under per-call headers.\n * Create one instance per request (e.g. during SSR) to scope auth headers safely.\n */\n readonly headers?: Record<string, string>;\n /**\n * transport for read queries (findOne, findMany, findManyPage, count). 'QUERY' (RFC 10008) sends the\n * JSON query in the request body, avoiding URL-length limits for large queries; requires\n * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.\n */\n readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;\n /**\n * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same\n * option the server handler takes, so one map serves both. State it where the default cannot: a\n * build that minifies class names renames every route.\n */\n readonly entityPath?: (entity: Type<unknown>) => string;\n};\n\n/** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */\nfunction idSegment<E>(entity: Type<E>, id: EntityId<E>): string {\n if (!isScalarId(id)) {\n throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);\n }\n return String(id);\n}\n\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n // Typed properties instead of methods, so each takes its signature from `ClientQuerier` rather than repeating it.\n readonly findOneById: ClientQuerier['findOneById'] = async (entity, id, q, opts) =>\n get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts));\n\n readonly findOne: ClientQuerier['findOne'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts);\n\n readonly findMany: SharedQuerier<'client', RequestFindOptions>['findMany'] = (entity, q, opts) =>\n this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts);\n\n readonly findManyAndCount: SharedQuerier<'client', RequestFindOptions>['findManyAndCount'] = async (\n entity,\n q,\n opts,\n ) => {\n const response = await this.findMany(entity, q, { ...opts, count: true });\n if (typeof response.count !== 'number') {\n throw new TypeError('findManyAndCount response has an invalid count');\n }\n return { ...response, count: response.count };\n };\n\n readonly findManyPage: ClientQuerier['findManyPage'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts);\n\n readonly count: ClientQuerier['count'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);\n\n /** The `count` route capped at one row, so existence needs no endpoint of its own. */\n readonly exists: ClientQuerier['exists'] = async (entity, q, opts) => {\n const res = await this.count(entity, { ...q, $limit: 1 }, opts);\n return { ...res, data: res.data > 0 };\n };\n\n readonly insertOne: ClientQuerier['insertOne'] = (entity, payload, opts) =>\n post(this.getBasePath(entity), payload, this.buildOptions(opts));\n\n readonly insertMany: ClientQuerier['insertMany'] = (entity, payload, opts) =>\n post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts));\n\n readonly updateOneById: ClientQuerier['updateOneById'] = async (entity, id, payload, opts) =>\n patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));\n\n readonly updateMany: ClientQuerier['updateMany'] = (entity, q, payload, opts) =>\n patch(`${this.getBasePath(entity)}${stringifyQuery(q)}`, payload, this.buildOptions(opts));\n\n readonly saveOne: ClientQuerier['saveOne'] = (entity, payload, opts) =>\n put(this.getBasePath(entity), payload, this.buildOptions(opts));\n\n readonly saveMany: ClientQuerier['saveMany'] = (entity, payload, opts) =>\n put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts));\n\n readonly deleteOneById: ClientQuerier['deleteOneById'] = async (entity, id, opts = {}) => {\n const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';\n return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));\n };\n\n readonly deleteMany: ClientQuerier['deleteMany'] = (entity, q, opts = {}) =>\n remove(\n `${this.getBasePath(entity)}${stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q)}`,\n this.buildOptions(opts),\n );\n\n getBasePath<E>(entity: Type<E>) {\n return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;\n }\n\n protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions) {\n if (this.defaults.readMethod === 'QUERY') {\n return httpQuery<T>(path, q ?? {}, this.buildOptions(opts));\n }\n return get<T>(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));\n }\n\n protected buildOptions(opts?: RequestOptions): RequestOptions | undefined {\n if (!this.defaults.headers && !opts?.headers) {\n return opts;\n }\n return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };\n }\n}\n"
15
15
  ],
16
- "mappings": "AAEA,IAAM,EAAe,IAAI,IAElB,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAElD,OADA,EAAa,IAAI,CAAE,EACZ,IAAY,CACjB,EAAa,OAAO,CAAE,GC+UnB,IAAM,EAAgB,CAC3B,QAAS,CAAE,MAAO,SAAU,MAAO,UAAW,EAC9C,UAAW,CAAE,MAAO,SAAU,MAAO,UAAW,EAChD,SAAU,CAAE,MAAO,SAAU,MAAO,UAAW,EAC/C,OAAQ,CAAE,MAAO,SAAU,MAAO,UAAW,EAC7C,MAAO,CAAE,MAAO,SAAU,MAAO,UAAW,EAC5C,MAAO,CAAE,MAAO,SAAU,MAAO,UAAW,EAC5C,OAAQ,CAAE,MAAO,SAAU,MAAO,UAAW,EAC7C,UAAW,CAAE,MAAO,UAAW,MAAO,UAAW,EAEjD,OAAQ,CAAE,MAAO,SAAU,MAAO,WAAY,EAE9C,YAAa,CAAE,MAAO,SAAU,MAAO,WAAY,EAEnD,MAAO,CAAE,MAAO,SAAU,MAAO,WAAY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,EAAK,UAAW,CAAC,EAAI,GAC/E,OAAO,EAAO,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAI,IAAM,KAAK,aAAa,CAAI,CAAC,GAG3F,WAA0C,CAAC,EAAQ,EAAG,EAAO,CAAC,IACrE,EACE,GAAG,KAAK,YAAY,CAAM,IAAI,EAAe,EAAK,WAAa,IAAK,EAAG,WAAY,EAAK,UAAW,EAAI,CAAC,IACxG,KAAK,aAAa,CAAI,CACxB,EAEF,WAAc,CAAC,EAAiB,CAC9B,MAAO,GAAG,KAAK,aAAa,KAAK,SAAS,YAAc,GAAY,CAAM,IAGlE,IAAO,CAAC,EAAc,EAAwC,EAAuB,CAC7F,GAAI,KAAK,SAAS,aAAe,QAC/B,OAAO,EAAa,EAAM,GAAK,CAAC,EAAG,KAAK,aAAa,CAAI,CAAC,EAE5D,OAAO,EAAO,GAAG,IAAO,EAAe,CAAC,IAAK,KAAK,aAAa,CAAI,CAAC,EAG5D,YAAY,CAAC,EAAmD,CACxE,GAAI,CAAC,KAAK,SAAS,SAAW,CAAC,GAAM,QACnC,OAAO,EAET,MAAO,IAAK,EAAM,QAAS,IAAK,KAAK,SAAS,WAAY,GAAM,OAAQ,CAAE,EAE9E",
17
+ "debugId": "5C47B677F680BF8464756E2164756E21",
18
18
  "names": []
19
19
  }
@@ -1,4 +1,4 @@
1
- import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type JsonArrayUpdateOp, type JsonUpdateOp, type Query, type QueryAggMap, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryExclude, type QueryGroupMap, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type Type, type UpdatePayload } from '../type/index.js';
1
+ import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type JsonArrayUpdateOp, type JsonUpdateOp, type Query, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryExclude, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type Type, type UpdatePayload } from '../type/index.js';
2
2
  import { type SortDirection } from '../util/index.js';
3
3
  import type { HydrateKind } from './hydrateColumn.js';
4
4
  import { type JsonAccessMode, type JsonContainer, type JsonKeyWrite, type JsonSlot } from './jsonSql.js';
@@ -430,7 +430,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
430
430
  * caller reached for this to avoid, and only say so by taking a long time.
431
431
  */
432
432
  estimatedCount<E>(_ctx: QueryContext, _entity: Type<E>): void;
433
- aggregate<E, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(ctx: QueryContext, entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryRenderOptions): readonly SelectTerm[];
433
+ aggregate<E>(ctx: QueryContext, entity: Type<E>, q: QueryAggregate<E>, opts?: QueryRenderOptions): readonly SelectTerm[];
434
434
  /**
435
435
  * What one entry reads: a grouped field, through the join its path passes, or an aggregate's argument,
436
436
  * narrowed by its own `$where` to `CASE WHEN … THEN … END`. Bare where it is a column or `'*'`.
@@ -1,9 +1,9 @@
1
- import type { EntityIndexColumnInput, EntityIndexOptions, EntityOptions, FilterName, FilterOptions, RefMap, TriggerOptions, Type } from '../../type/index.js';
1
+ import type { BrandsNameFields, EntityIndexColumnInput, EntityIndexOptions, EntityOptions, FilterName, FilterOptions, RefMap, TriggerOptions, Type } from '../../type/index.js';
2
2
  /**
3
3
  * Marks a class as an entity and finalizes its metadata, draining `context.metadata`: the class gets
4
4
  * `Symbol.metadata` only after its decorators return.
5
5
  */
6
- export declare function Entity<E>(opts?: NoInfer<EntityOptions<E>>): (entity: Type<E>, context?: ClassDecoratorContext) => void;
6
+ export declare function Entity<E>(opts?: NoInfer<EntityOptions<E>>): (entity: Type<E> & BrandsNameFields<E>, context?: ClassDecoratorContext) => void;
7
7
  /**
8
8
  * Registers a named `$where` filter, applied to every query unless bypassed via `QueryOptions.filters`.
9
9
  *
@@ -1,4 +1,4 @@
1
- import type { EntityGetter, EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, KeyMap, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
1
+ import type { BrandsNameFields, EntityGetter, EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, KeyMap, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
2
2
  export declare function defineField<E>(entity: Type<E>, key: string, opts?: FieldOptions): EntityMeta<E>;
3
3
  export declare function defineId<E>(entity: Type<E>, key: string, opts: FieldOptions): EntityMeta<E>;
4
4
  /** `T` is the relation's target, independent of the owner `E`. */
@@ -35,7 +35,7 @@ export declare function applyMembers<E>(entity: Type<E>, specs: EntityMembers |
35
35
  * Registers a class as an entity from `opts` alone, the decorator-free counterpart of `@Entity()` with
36
36
  * `@Field`/`@ManyToOne`/...
37
37
  */
38
- export declare function defineEntity<E>(entity: Type<E>, opts?: EntityOptions<E>): EntityMeta<E>;
38
+ export declare function defineEntity<E>(entity: Type<E> & BrandsNameFields<E>, opts?: EntityOptions<E>): EntityMeta<E>;
39
39
  /**
40
40
  * Refuses an entity whose primary key is not one column, naming the path that cannot express it.
41
41
  *
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIn
5
5
  export * from './namingStrategy/index.js';
6
6
  export { type QueryError, queryErrorKind } from './querier/queryError.js';
7
7
  export type * from './type/index.js';
8
- export { idKey, isSqlQuerier, versionKey } from './type/index.js';
8
+ export { filledKey, idKey, isSqlQuerier, versionKey } from './type/index.js';
9
9
  export { withDeleted } from './util/filters.util.js';
10
10
  export { sortOf } from './util/query.util.js';
11
11
  export type { HookContext } from './util/hook.util.js';
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ export * from './entity/decorator/members.js';
4
4
  export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, keyOf, removeEntity, } from './entity/metadata/definition.js';
5
5
  export * from './namingStrategy/index.js';
6
6
  export { queryErrorKind } from './querier/queryError.js';
7
- export { idKey, isSqlQuerier, versionKey } from './type/index.js';
7
+ export { filledKey, idKey, isSqlQuerier, versionKey } from './type/index.js';
8
8
  export { withDeleted } from './util/filters.util.js';
9
9
  export { sortOf } from './util/query.util.js';
10
10
  export { DefaultLogger } from './util/logger.js';
@@ -1,6 +1,6 @@
1
1
  import { type Document, type Filter, type Sort } from 'mongodb';
2
2
  import { AbstractDialect } from '../dialect/abstractDialect.js';
3
- import type { DialectFeatures, EntityData, EntityMeta, Query, QueryAggMap, QueryAggregate, QueryExclude, QueryGroupMap, QueryOptions, QueryPager, QuerySelectValue, QuerySortMap, QueryVectorSearch, QueryWhere, Type } from '../type/index.js';
3
+ import type { DialectFeatures, EntityData, EntityMeta, Query, QueryAggregate, QueryExclude, QueryOptions, QueryPager, QuerySelectValue, QuerySortMap, QueryVectorSearch, QueryWhere, Type } from '../type/index.js';
4
4
  import { type CallbackKey } from '../util/index.js';
5
5
  /**
6
6
  * An ordering as the pipeline runs it: the `$sort`, the fields it needs on the document first - a
@@ -217,7 +217,7 @@ export declare class MongoDialect extends AbstractDialect {
217
217
  normalizeId<E extends Document>(meta: EntityMeta<E>, doc: Document): E;
218
218
  normalizeId<E extends Document>(meta: EntityMeta<E>, doc: Document | undefined): E | undefined;
219
219
  /** An aggregate's rows with each 64-bit integer decoded as a document's is: a `bigint` only where the column reads a `BigInt` field. */
220
- normalizeAggregateRows<E extends Document, const G extends QueryGroupMap<E>, const A extends QueryAggMap<E>, R extends Document>(entity: Type<E>, q: QueryAggregate<E, G, A>, rows: R[]): R[];
220
+ normalizeAggregateRows<E extends Document, R extends Document>(entity: Type<E>, q: QueryAggregate<E>, rows: R[]): R[];
221
221
  /**
222
222
  * A key as MongoDB stores it: a 24-hex string as an `ObjectId`, so a write matches the filter looking for
223
223
  * it, and anything else as given. Only 24-hex, not any 12-byte string. Arrays convert element-wise.
@@ -241,7 +241,7 @@ export declare class MongoDialect extends AbstractDialect {
241
241
  /**
242
242
  * Build MongoDB aggregation pipeline stages from a QueryAggregate.
243
243
  */
244
- buildAggregateStages<E extends Document, const G extends QueryGroupMap<E>, const A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): MongoAggregationPipelineEntry<Document>[];
244
+ buildAggregateStages<E extends Document>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): MongoAggregationPipelineEntry<Document>[];
245
245
  /**
246
246
  * Resolve parsed group entries into the `_id` keys and accumulators of a `$group` stage, and the
247
247
  * `columns` its `$project` reads each result from: a group key out of `_id`, a DISTINCT set by its
@@ -1,7 +1,7 @@
1
1
  import type { ClientSession, Document, MongoClient } from 'mongodb';
2
2
  import type { UpsertedId } from '../querier/abstractQuerier.js';
3
3
  import { AbstractQuerier } from '../querier/index.js';
4
- import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
4
+ import type { EntityData, ExtraOptions, Query, QueryAggregate, QueryConflictPaths, QueryPage, QueryOptions, QuerySearch, RawRow, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
5
5
  import type { MongoDialect } from './mongoDialect.js';
6
6
  import type { MongoQuerier } from './mongoQuerier.js';
7
7
  export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
@@ -35,7 +35,7 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
35
35
  * `$vectorSearch` is always the first stage; `$where` is merged into its `filter`.
36
36
  */
37
37
  private buildVectorPipeline;
38
- protected internalAggregate<E extends Document, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
38
+ protected internalAggregate<E extends Document>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
39
39
  /**
40
40
  * A `$required` relation drops parents that have no match, and `$distinct` collapses them, so both
41
41
  * totals have to be taken after the stage that does it - which only the read pipeline builds. Every
@@ -1,5 +1,5 @@
1
1
  import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
- import type { BooleanLike, CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, RelationKey, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, ReturningResult, WriteOptions, PrimaryKey, WrittenId } from '../type/index.js';
2
+ import type { BooleanLike, CursorPage, Captured, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, QueryPage, QuerySearch, SavepointCommand, TransactionOptions, Type, UpdatePayload, UpdateWrite, WriteResults, WriteOptions, PrimaryKey, WrittenId, RawRow } from '../type/index.js';
3
3
  import { LoggerWrapper } from '../util/index.js';
4
4
  import { type TransactionScope } from './transaction.js';
5
5
  /** What an upsert reports of a row: the value a driver answers for a lone key, or the key the read back names. */
@@ -34,17 +34,21 @@ export declare abstract class AbstractQuerier implements Querier {
34
34
  */
35
35
  private assertLockable;
36
36
  private validateProjectionQueryRecursive;
37
- findOneById<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, id: EntityId<E>, q?: QueryOneProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
37
+ findOneById<E extends object, const Q extends QueryOne<E> = {}>(entity: Type<E>, id: EntityId<E>, q?: Captured<QueryOne<E>, Q>, opts?: QueryOptions): Promise<QueryFindResult<E, Q> | undefined>;
38
38
  /** Find one record, the entity passed first or as the query's `$entity`. */
39
- findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryOneProjected<E, S, V, X, P, C> & {
39
+ findOne<E extends object, const Q extends QueryOne<E> & {
40
40
  $entity: Type<E>;
41
- }, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
42
- findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryOneProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
41
+ }>(q: Captured<QueryOne<E> & {
42
+ $entity: Type<E>;
43
+ }, Q>, opts?: QueryOptions): Promise<QueryFindResult<E, Q> | undefined>;
44
+ findOne<E extends object, const Q extends QueryOne<E>>(entity: Type<E>, q: Captured<QueryOne<E>, Q>, opts?: QueryOptions): Promise<QueryFindResult<E, Q> | undefined>;
43
45
  /** Find many records, the entity passed first or as the query's `$entity`. */
44
- findMany<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryProjected<E, S, V, X, P, C> & {
46
+ findMany<E extends object, const Q extends Query<E> & {
47
+ $entity: Type<E>;
48
+ }>(q: Captured<Query<E> & {
45
49
  $entity: Type<E>;
46
- }, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C>[]>;
47
- findMany<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C>[]>;
50
+ }, Q>, opts?: QueryOptions): Promise<QueryFindResult<E, Q>[]>;
51
+ findMany<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>, opts?: QueryOptions): Promise<QueryFindResult<E, Q>[]>;
48
52
  /**
49
53
  * The rows matching `q`, each populated relation and `$count` read with them in the same statement
50
54
  * or pipeline. [The design](../../../../architecture/relations-in-one-statement.md).
@@ -54,10 +58,12 @@ export declare abstract class AbstractQuerier implements Querier {
54
58
  * Stream records with the relations and counts `findMany` reads, the entity passed first or as `$entity`.
55
59
  * `afterLoad` runs on each row as it arrives, and the querier runs nothing else until the loop ends.
56
60
  */
57
- findManyStream<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryProjected<E, S, V, X, P, C> & {
61
+ findManyStream<E extends object, const Q extends Query<E> & {
62
+ $entity: Type<E>;
63
+ }>(q: Captured<Query<E> & {
58
64
  $entity: Type<E>;
59
- }, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, S, V, X, P, C>>;
60
- findManyStream<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, S, V, X, P, C>>;
65
+ }, Q>, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, Q>>;
66
+ findManyStream<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, Q>>;
61
67
  /**
62
68
  * `rows`, each through `loaded` (guarded, so an unhooked row costs no turn) before the loop sees it, holding the
63
69
  * querier from the first row asked for until the loop ends. Most drivers queue a statement behind an open read,
@@ -66,20 +72,24 @@ export declare abstract class AbstractQuerier implements Querier {
66
72
  private holdWhileReading;
67
73
  protected abstract internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncIterable<E>;
68
74
  /** Find many records and count every match, the entity passed first or as the query's `$entity`. */
69
- findManyAndCount<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryProjected<E, S, V, X, P, C> & {
75
+ findManyAndCount<E extends object, const Q extends Query<E> & {
70
76
  $entity: Type<E>;
71
- }, opts?: QueryOptions): Promise<[QueryFindResult<E, S, V, X, P, C>[], number]>;
72
- findManyAndCount<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<[QueryFindResult<E, S, V, X, P, C>[], number]>;
77
+ }>(q: Captured<Query<E> & {
78
+ $entity: Type<E>;
79
+ }, Q>, opts?: QueryOptions): Promise<[QueryFindResult<E, Q>[], number]>;
80
+ findManyAndCount<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>, opts?: QueryOptions): Promise<[QueryFindResult<E, Q>[], number]>;
73
81
  /**
74
82
  * The page and how many rows the filter matched beyond it. Two statements here, which is what a
75
83
  * backend with no way to answer both at once is left with; SQL overrides it to answer from one.
76
84
  */
77
85
  protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
78
86
  /** Read a page of records from a cursor, the entity passed first or as the query's `$entity`. */
79
- findManyPage<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryKeysetProjected<E, S, V, X, P, C> & {
87
+ findManyPage<E extends object, const Q extends QueryKeyset<E> & {
88
+ $entity: Type<E>;
89
+ }>(q: Captured<QueryKeyset<E> & {
80
90
  $entity: Type<E>;
81
- }, opts?: QueryOptions): Promise<CursorPage<QueryFindResult<E, S, V, X, P, C>>>;
82
- findManyPage<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryKeysetProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<CursorPage<QueryFindResult<E, S, V, X, P, C>>>;
91
+ }, Q>, opts?: QueryOptions): Promise<CursorPage<QueryFindResult<E, Q>>>;
92
+ findManyPage<E extends object, const Q extends QueryKeyset<E>>(entity: Type<E>, q: Captured<QueryKeyset<E>, Q>, opts?: QueryOptions): Promise<CursorPage<QueryFindResult<E, Q>>>;
83
93
  /** Count records matching the query, the entity passed first or as the query's `$entity`. */
84
94
  count<E extends object>(q: QueryPage<E> & {
85
95
  $entity: Type<E>;
@@ -95,12 +105,12 @@ export declare abstract class AbstractQuerier implements Querier {
95
105
  /**
96
106
  * Run an aggregate query.
97
107
  */
98
- aggregate<E extends object, const G extends QueryGroupMap<E>, const A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
99
- protected abstract internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
108
+ aggregate<E extends object, const Q extends QueryAggregate<E>>(entity: Type<E>, q: Captured<QueryAggregate<E, Q>, Q>, opts?: QueryOptions): Promise<QueryAggregateResult<E, Q>[]>;
109
+ protected abstract internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
100
110
  /** Abstract outright: nothing is shared to do around it. See {@link UniversalQuerier.estimatedCount}. */
101
111
  abstract estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
102
- insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, WrittenId<E> | undefined, QueryFindResult<E, S, V>>>;
103
- insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, (WrittenId<E> | undefined)[], QueryFindResult<E, S, V>[]>>;
112
+ insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
113
+ insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted'][]>;
104
114
  /**
105
115
  * The ids of the rows inserted, in payload order. The `onInsert` values are filled before the write, so
106
116
  * the after hooks and the ids read the same rows the statement wrote.
@@ -126,8 +136,8 @@ export declare abstract class AbstractQuerier implements Querier {
126
136
  private insertRows;
127
137
  /** Writes `rows`, its columns only, and onto each one the key the database generated for it, where it can tell. */
128
138
  protected abstract internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
129
- updateOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
130
- updateMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V>[]>>;
139
+ updateOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affected']>;
140
+ updateMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affectedMany']>;
131
141
  /**
132
142
  * The number of rows the update changed, or the rows `returning` reads back: settled first and held, so the
133
143
  * update writes those rows and no other, whatever a payload or another writer does to what `$where` reads.
@@ -192,8 +202,8 @@ export declare abstract class AbstractQuerier implements Querier {
192
202
  * cleared stamp, or a row pointed at the relation just inserted for it.
193
203
  */
194
204
  private unversionedUpdate;
195
- upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, WrittenId<E> | undefined, QueryFindResult<E, S, V>>>;
196
- upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, (WrittenId<E> | undefined)[], QueryFindResult<E, S, V>[]>>;
205
+ upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
206
+ upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted'][]>;
197
207
  /**
198
208
  * An upsert as a read, then writes: the rows the conflict names are read through the filters, those found update
199
209
  * as `updateMany` does and the rest insert, so either branch writes its relations and a guarded row stays its
@@ -203,12 +213,12 @@ export declare abstract class AbstractQuerier implements Querier {
203
213
  private readThenUpsert;
204
214
  /** Upserts `payload`, answering each row's key in payload order, `undefined` for one the engine did not report. */
205
215
  protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[]>;
206
- deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V> | undefined>>;
216
+ deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affected']>;
207
217
  /** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
208
218
  deleteMany<E extends object>(q: QuerySearch<E> & {
209
219
  $entity: Type<E>;
210
220
  }, opts?: QueryOptions): Promise<number>;
211
- deleteMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<ReturningResult<S, number, QueryFindResult<E, S, V>[]>>;
221
+ deleteMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affectedMany']>;
212
222
  /** The number of rows deleted, or the rows `returning` reads as they were: held before the delete, which deletes those. */
213
223
  private deleteWhere;
214
224
  /** Whether an update is its one statement over `q`: no version to lock, relation to write or page to settle first. */
@@ -221,8 +231,8 @@ export declare abstract class AbstractQuerier implements Querier {
221
231
  private deleteRows;
222
232
  /** Runs one DELETE (or soft-delete stamp) over `q`, which names its rows by id wherever {@link deleteMany} settled them. */
223
233
  protected abstract internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
224
- saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, WrittenId<E> | undefined, QueryFindResult<E, S, V>>>;
225
- saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<ReturningResult<S, (WrittenId<E> | undefined)[], QueryFindResult<E, S, V>[]>>;
234
+ saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
235
+ saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted'][]>;
226
236
  /**
227
237
  * Whether a row names its key decides its statement, never whether the row exists: a named row
228
238
  * upserts on that key, so a stale id is written rather than silently missed, and an unnamed one
@@ -339,9 +339,6 @@ export class AbstractQuerier {
339
339
  const [entity, q, opts] = entityArgs(args);
340
340
  return (await this.internalCount(entity, { $where: q.$where, $limit: 1 }, opts)) > 0;
341
341
  }
342
- /**
343
- * Run an aggregate query.
344
- */
345
342
  aggregate(entity, q, opts) {
346
343
  return this.internalAggregate(entity, q, opts);
347
344
  }
@@ -510,7 +507,8 @@ export class AbstractQuerier {
510
507
  */
511
508
  async throwStaleVersion(entity, key, q, expected, opts) {
512
509
  const meta = getMeta(entity);
513
- const row = await this.findOne(entity, { $select: keySet([key]), $where: whereIds(meta, idOf(meta, { ...q.$where })) }, opts);
510
+ const read = { $select: keySet([key]), $where: whereIds(meta, idOf(meta, { ...q.$where })) };
511
+ const row = await this.findOne(entity, read, opts);
514
512
  const actual = row?.[key];
515
513
  const message = actual === undefined
516
514
  ? `no row of '${entityName(meta)}' has that id any more: it is gone`
@@ -1,5 +1,5 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
2
+ import type { EntityData, ExtraOptions, Query, QueryAggregate, QueryConflictPaths, QueryPage, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
3
3
  import type { SqlExecution } from '../util/sql.util.js';
4
4
  import { AbstractQuerier, type UpsertedId, type WritesReturning } from './abstractQuerier.js';
5
5
  /** A statement as it is sent: its SQL and the values it binds. */
@@ -95,7 +95,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
95
95
  private runCount;
96
96
  protected internalCount<E extends object>(entity: Type<E>, q: QueryPage<E>, opts?: QueryOptions): Promise<number>;
97
97
  estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
98
- protected internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
98
+ protected internalAggregate<E extends object>(entity: Type<E>, q: QueryAggregate<E>, opts?: QueryOptions): Promise<RawRow[]>;
99
99
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
100
100
  internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
101
101
  /** `UPDATE` and `DELETE` with a `RETURNING` read as a read's rows are, where the engine has it. */