uql-orm 0.102.0 → 0.102.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/browser/uql-browser.min.js +2 -2
  2. package/dist/browser/uql-browser.min.js.map +3 -3
  3. package/dist/dialect/abstractDialect.js +2 -1
  4. package/dist/dialect/abstractSqlDialect.d.ts +42 -21
  5. package/dist/dialect/abstractSqlDialect.js +79 -39
  6. package/dist/dialect/aliases.d.ts +8 -0
  7. package/dist/dialect/aliases.js +24 -16
  8. package/dist/dialect/jsonSql.d.ts +10 -7
  9. package/dist/dialect/jsonSql.js +7 -10
  10. package/dist/dialect/mysqlLikeSqlDialect.d.ts +4 -8
  11. package/dist/dialect/mysqlLikeSqlDialect.js +8 -11
  12. package/dist/dialect/pgLikeSqlDialect.d.ts +20 -13
  13. package/dist/dialect/pgLikeSqlDialect.js +37 -29
  14. package/dist/mongodb/mongoDialect.d.ts +4 -12
  15. package/dist/mongodb/mongoDialect.js +69 -70
  16. package/dist/mssql/mssqlDialect.d.ts +20 -10
  17. package/dist/mssql/mssqlDialect.js +35 -28
  18. package/dist/mysql/mysqlDialect.js +1 -1
  19. package/dist/querier/abstractQuerier.js +1 -2
  20. package/dist/querier/cursorStream.js +1 -2
  21. package/dist/sqlite/localSqliteQuerierPool.js +8 -2
  22. package/dist/sqlite/sqliteDialect.d.ts +4 -4
  23. package/dist/sqlite/sqliteDialect.js +10 -8
  24. package/dist/turso/tursoLocalDialect.d.ts +3 -1
  25. package/dist/turso/tursoLocalDialect.js +7 -0
  26. package/dist/type/entity.d.ts +18 -10
  27. package/dist/util/dialect.util.d.ts +27 -0
  28. package/dist/util/dialect.util.js +120 -4
  29. package/dist/util/field.util.d.ts +2 -0
  30. package/dist/util/field.util.js +5 -0
  31. package/dist/util/object.util.d.ts +2 -0
  32. package/dist/util/object.util.js +4 -0
  33. package/package.json +7 -7
  34. package/skills/uql-orm/SKILL.md +3 -3
@@ -1,4 +1,4 @@
1
- var c=new Set;function l(e){for(let r of c)r(e)}function V(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 P extends Error{}class i extends P{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 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 b 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:u(r)},t)}function x(e,r,t){return y(e,{method:"PATCH",body:u(r)},t)}function S(e,r,t){return y(e,{method:"PUT",body:u(r)},t)}function Q(e,r){return y(e,{method:"DELETE"},r)}function T(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 b(p.message,p.code)})).finally(()=>{l({phase:"complete",opts:t})})}function C(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 O(e){return C(e.name)}function g(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)}/${g(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)=>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)}/${g(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)=>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?a({hardDelete:t.hardDelete}):"";return Q(`${this.getBasePath(e)}/${g(e,r)}${n}`,this.buildOptions(t))};deleteMany=(e,r,t={})=>Q(`${this.getBasePath(e)}${a(t.hardDelete?{...r,hardDelete:t.hardDelete}:r)}`,this.buildOptions(t));getBasePath(e){return`${this.basePath}/${(this.defaults.entityPath??O)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return T(e,r??{},this.buildOptions(t));return h(`${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,b as RequestError,h as get,l as notify,V as on,x as patch,E as post,S as put,T as query,Q as remove};
1
+ var c=new Set;function l(e){for(let r of c)r(e)}function V(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 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 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:u(r)},t)}function x(e,r,t){return y(e,{method:"PATCH",body:u(r)},t)}function S(e,r,t){return y(e,{method:"PUT",body:u(r)},t)}function g(e,r){return y(e,{method:"DELETE"},r)}function T(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 P(p.message,p.code)})).finally(()=>{l({phase:"complete",opts:t})})}function C(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 O(e){return C(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)}${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)=>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)}${a(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?a({hardDelete:t.hardDelete}):"";return g(`${this.getBasePath(e)}/${Q(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??O)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return T(e,r??{},this.buildOptions(t));return h(`${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,P as RequestError,h as get,l as notify,V as on,x as patch,E as post,S as put,T as query,g as remove};
2
2
 
3
- //# debugId=BD03E80C0F2470E364756E2164756E21
3
+ //# debugId=AF1D60416A95C3D364756E2164756E21
4
4
  //# sourceMappingURL=uql-browser.min.js.map
@@ -5,7 +5,7 @@
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
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.\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, C> & 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<\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> = [S | X] extends [never]\n ? E\n : IsUniform<V> extends true\n ? [PopulatedToMany<E, P>] extends [never]\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 : // A populated to-many is always a list, empty where the parent has no children, so it maps\n // and counts without a guard. Only that promotion needs a second member, and only a query\n // that populates one pays for it; every other key keeps the modifier the entity declared,\n // a to-one relation included, since a join that finds no row leaves it absent.\n Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E> & {\n [K in PopulatedToMany<E, P>]-?: NonNullable<E[K]>;\n }\n : E;\n\n/** The to-many relations a query populated, which come back as lists rather than as optional ones. */\ntype PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;\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",
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
- "import type { EntityMeta } from '../type/index.js';\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\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",
8
+ "import type { EntityMeta } from '../type/index.js';\n\n/** A value a JSON document holds whole, and `$addToSet` and an `=` on a JSON path compare by equality. */\nexport function isJsonScalar(value: unknown): value is string | number | boolean {\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\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",
10
10
  "import type { QueryKeyset, QueryOptions, WireQuery } from '../type/index.js';\n// the clause table itself, not the barrel: this module is in the browser bundle's graph\nimport { QUERY_CLAUSES, type QueryClause } from '../type/query.js';\n// the brand alone, not the class: importing `QuerySql` for an `instanceof` kept it, and `ColumnRef`\n// with it, in the browser bundle, which is on a size budget\nimport { SQL_FN } from '../type/querySql.js';\n// the specific util module, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys, isRecord, isWhereMap } from '../util/object.util.js';\n// the error class alone, from its own leaf module: `queryError.ts` carries every driver's code map\nimport { UqlUsageError } from '../util/uqlError.js';\n\n/** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */\nconst WIRE_FLAGS = ['hardDelete', 'count'] as const satisfies (keyof Pick<QueryOptions, 'hardDelete'> | 'count')[];\n\n/** {@link WIRE_FLAGS} as the booleans {@link parseQueryParams} decodes them to, where a hook may also set them. */\nexport type WireFlags = { readonly [K in (typeof WIRE_FLAGS)[number]]?: boolean };\n\n/** The cursors a page request carries; only `findManyPage` reads them. */\nexport type WireCursors = Pick<QueryKeyset<unknown>, '$after' | '$before'>;\n\n/**\n * Keys that mean something locally but that this transport can never honor, so they are rejected\n * rather than dropped like the rest. Each request runs on its own auto-committing connection, so a\n * row lock taken here is released before the response is written: honoring `$lock` is impossible,\n * and ignoring it would hand the caller a read they believe is serialized and is not.\n */\nconst REJECTED_QUERY_KEYS = new Set<string>(['$lock'] satisfies (keyof WireQuery<unknown>)[]);\n\n/**\n * The keys accepted from the wire, mapped to how each value is decoded: every query clause ({@link QUERY_CLAUSES})\n * plus the {@link WIRE_FLAGS}. Anything else (e.g. `filters`, `context`, `$entity`) is dropped, so a remote\n * client can't bypass a security filter or inject ambient context.\n */\nconst WIRE_VALUES: ReadonlyMap<string, QueryClause['value']> = new Map([\n ...getKeys(QUERY_CLAUSES).map((key) => [key, QUERY_CLAUSES[key].value] as const),\n ...WIRE_FLAGS.map((flag) => [flag, 'boolean'] as const),\n]);\n\n/**\n * Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query\n * object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.\n */\nexport function parseQueryParams<E = unknown>(params: unknown = {}): WireQuery<E> & WireFlags & WireCursors {\n if (!isRecord(params)) {\n throw new UqlUsageError('the query must be a JSON object');\n }\n const query: Record<string, unknown> = {};\n for (const key of getKeys(params)) {\n if (REJECTED_QUERY_KEYS.has(key)) {\n throw new UqlUsageError(`'${key}' is not supported over HTTP`);\n }\n const shape = WIRE_VALUES.get(key);\n if (shape && params[key] !== undefined) {\n query[key] = decodeWireValue(key, shape, params[key]);\n }\n }\n query['$where'] ??= {};\n if (!isWhereMap(query['$where'])) {\n throw new UqlUsageError(\"'$where' must be a JSON object\");\n }\n return query;\n}\n\n/**\n * Decodes a value to the type its clause declares. A query string carries every value as text, so a boolean\n * must be decoded: `'false'` is a non-empty string, and taken as is, `$distinct=false` would turn it on.\n */\nfunction decodeWireValue(key: string, shape: QueryClause['value'], value: unknown): unknown {\n switch (shape) {\n case 'object':\n return typeof value === 'string' ? parseJson(key, value) : value;\n case 'number':\n return Number(value);\n case 'boolean':\n return value === true || value === 'true';\n case 'string':\n // A cursor arrives as the exact text a page handed out, never as JSON, so any other value is not a cursor.\n if (typeof value !== 'string') {\n throw new UqlUsageError(`'${key}' must be a cursor a page handed out`);\n }\n return value;\n }\n}\n\nfunction parseJson(key: string, text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new UqlUsageError(`invalid JSON in '${key}'`);\n }\n}\n\n/**\n * Serialize a UQL query object into a percent-encoded query string where object values\n * are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.\n */\nexport function stringifyQuery(query?: Record<string, unknown>): string {\n if (!query) {\n return '';\n }\n const params = new URLSearchParams();\n for (const key of getKeys(query)) {\n const value = query[key];\n if (value === undefined) {\n continue;\n }\n params.append(key, typeof value === 'object' && value !== null ? wireJson(value) : String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\n/**\n * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server\n * build a statement around the remains. A `sql` fragment renders SQL against a dialect the client does not\n * have and arrives as `{}`; binary arrives as an object keyed by index. A `Date` is not among them - it\n * serializes to ISO 8601, which is what a date column reads. This is what a cast, or a JavaScript caller,\n * hits where the client's types already refuse a fragment.\n */\nexport function wireJson(value: unknown): string {\n return JSON.stringify(value, (_key: string, held: unknown) => {\n if (typeof held !== 'object' || held === null) {\n return held;\n }\n if (SQL_FN in held) {\n throw new UqlUsageError('raw SQL cannot travel over HTTP: what leaves the browser is JSON');\n }\n // A blob is a field value, so no type parameter reaches it: this is the only place it is caught.\n if (held instanceof ArrayBuffer || ArrayBuffer.isView(held)) {\n throw new UqlUsageError('binary cannot travel over HTTP: what leaves the browser is JSON');\n }\n return held;\n });\n}\n",
11
11
  "import type { RequestErrorResponse } from '../../http/contract.js';\nimport { wireJson } from '../../http/query.js';\nimport type { RequestSuccessResponse } from '../../type/index.js';\nimport type { RequestOptions } from '../type/index.js';\nimport { notify } from './bus.js';\n\n/**\n * Error thrown for non-2xx responses. Carries the HTTP status so callers can key\n * behavior on it (401 redirects, 402 payment flows, error-boundary routing).\n */\nexport class RequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n this.name = 'RequestError';\n }\n}\n\n// Methods are upper-case because `fetch` normalizes only the classic verbs: a lowercase `patch` or `query`\n// is sent as written, and servers refuse it.\nexport function get<T>(url: string, opts?: RequestOptions) {\n return request<T>(url, { method: 'GET' }, opts);\n}\n\nexport function post<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'POST', body: wireJson(payload) }, opts);\n}\n\nexport function patch<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'PATCH', body: wireJson(payload) }, opts);\n}\n\nexport function put<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'PUT', body: wireJson(payload) }, opts);\n}\n\nexport function remove<T>(url: string, opts?: RequestOptions) {\n return request<T>(url, { method: 'DELETE' }, opts);\n}\n\n/**\n * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the\n * request body, avoiding URL-length limits.\n */\nexport function query<T>(url: string, payload: unknown, opts?: RequestOptions) {\n return request<T>(url, { method: 'QUERY', body: wireJson(payload) }, opts);\n}\n\nfunction request<T>(url: string, init: RequestInit, opts?: RequestOptions) {\n notify({ phase: 'start', opts });\n\n init.headers = {\n accept: 'application/json',\n 'content-type': 'application/json',\n ...opts?.headers,\n };\n if (opts?.signal) {\n init.signal = opts.signal;\n }\n\n return fetch(url, init)\n .then((rawResp) =>\n rawResp.json().then((resp: unknown) => {\n const isSuccess = rawResp.status >= 200 && rawResp.status < 300;\n if (isSuccess) {\n notify({ phase: 'success', opts });\n return resp as RequestSuccessResponse<T>;\n }\n const errorResp = resp as Partial<RequestErrorResponse> | undefined;\n const error = {\n message: errorResp?.error?.message ?? rawResp.statusText,\n code: errorResp?.error?.code ?? rawResp.status,\n };\n notify({ phase: 'error', error, opts });\n throw new RequestError(error.message, error.code);\n }),\n )\n .finally(() => {\n notify({ phase: 'complete', opts });\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
- "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5D,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": "AF1D60416A95C3D364756E2164756E21",
18
18
  "names": []
19
19
  }
@@ -6,6 +6,7 @@ import { aggregateOf, definedEntries, entityName, someKey } from '../util/index.
6
6
  import { assertNoUndefined, assertWhere } from '../util/query.util.js';
7
7
  import { qualifyName } from '../util/sql.util.js';
8
8
  import { UqlUsageError } from '../util/uqlError.js';
9
+ import { OWNED_PREFIX } from './aliases.js';
9
10
  import { groupClauses, isGroupOp } from './operators.js';
10
11
  /**
11
12
  * The dialect's share of a pool's {@link ExtraOptions}: what changes the SQL rather than the
@@ -98,7 +99,7 @@ export class AbstractDialect {
98
99
  if (!PLAIN_NAME.test(alias)) {
99
100
  throw new UqlUsageError(`$project '${alias}' is no plain name: letters, digits and '_', not led by a digit`);
100
101
  }
101
- if (alias === '_id' || alias.startsWith('_uql')) {
102
+ if (alias === '_id' || alias.startsWith(OWNED_PREFIX)) {
102
103
  throw new UqlUsageError(`$project '${alias}' is a name MongoDB or UQL reserves`);
103
104
  }
104
105
  if (definedEntries(meta.fields).some(([key, field]) => key === alias || this.resolveColumnName(key, field) === alias)) {
@@ -1,7 +1,7 @@
1
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 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';
2
2
  import { type SortDirection } from '../util/index.js';
3
3
  import type { HydrateKind } from './hydrateColumn.js';
4
- import { type JsonAccessMode, type JsonSlot } from './jsonSql.js';
4
+ import { type JsonAccessMode, type JsonContainer, type JsonKeyWrite, type JsonSlot } from './jsonSql.js';
5
5
  import { type QueryJoins, type QuerySortOptions } from './queryJoins.js';
6
6
  import { VectorSqlDialect } from './vectorSqlDialect.js';
7
7
  /** How a column's values are bound: see {@link AbstractSqlDialect.persistKind}. */
@@ -336,8 +336,13 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
336
336
  protected jsonAny(ctx: QueryContext, slot: JsonSlot, values: readonly unknown[]): string;
337
337
  /** How many elements the JSON array at `slot` has, which `$size` compares. */
338
338
  protected abstract jsonLength(slot: JsonSlot): string;
339
- /** Whether the value at `slot` is a JSON array: the array operators match, and `$pull` changes, no other. */
340
- protected abstract jsonIsArray(slot: JsonSlot): string;
339
+ /**
340
+ * Whether the value at `slot` is a JSON array, which the array operators match and `$pull` changes, or an
341
+ * object, which a dotted `$set` writes into.
342
+ */
343
+ protected abstract jsonIs(slot: JsonSlot, kind: JsonContainer): string;
344
+ /** Whether `slot` holds nothing: no value, or a JSON null. */
345
+ protected abstract jsonIsNull(slot: JsonSlot): string;
341
346
  /** The JSON array at `slot` as one row per element under `alias`, the `FROM` of an `EXISTS`. */
342
347
  protected abstract jsonElemFrom(slot: JsonSlot, alias: string): string;
343
348
  /** An exploded element as a JSON document, which its fields are paths into. */
@@ -600,30 +605,46 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
600
605
  */
601
606
  protected jsonCast(operand: string): string;
602
607
  /**
603
- * `"col" = <expr>` for a JSON update, each operator wrapping the last: `$pull`, `$set`, `$push`, `$unset`.
604
- * `$pull` reads the column and every later one its expression once, so no value binds twice.
608
+ * `"col" = <expr>` for a JSON update, folded to one write per path, on an empty document in place of a NULL
609
+ * column where one writes a key. Each write reads `current`, the column as stored.
605
610
  */
606
611
  protected formatJsonUpdate(ctx: QueryContext, escapedCol: string, value: JsonUpdateOp, field?: FieldOptions, current?: string): void;
607
612
  /**
608
- * Remove every element equal to the given value, per array key. Each key wraps the expression
609
- * built so far, so dialects only supply {@link jsonPullKey} - and because every key reads
610
- * `escapedCol` rather than the accumulated expression, values bind once, in key order.
611
- */
612
- protected jsonPull(ctx: QueryContext, expr: string, escapedCol: string, pull: Record<string, unknown>): string;
613
- /**
614
- * Wrap `expr` so the array at `key` no longer contains `value`: the array rebuilt from the elements that
615
- * differ from it, and any other value put back as it is. `JSON_REPLACE` leaves an absent key, and a NULL
616
- * column, untouched.
617
- */
618
- protected jsonPullKey(ctx: QueryContext, expr: string, escapedCol: string, key: string, value: unknown): string;
619
- /** The elements a `$pull` keeps, back in one array, and an empty one where it keeps none. */
613
+ * The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its pull, then each
614
+ * append, onto `[]` in place of a missing or null array. With a `unique` append, a second branch writes the array
615
+ * without it where the stored one holds its item; each branch is built in the order it binds.
616
+ */
617
+ private jsonArrayWrite;
618
+ /**
619
+ * `expr` with each key written, through as few `JSON_SET` calls, or `JSON_REPLACE` where a missing key stays
620
+ * missing, as `maxFunctionArgs` allows: every value reads the column as stored, so none needs another's result.
621
+ */
622
+ protected jsonWriteKeys(expr: string, writes: readonly JsonKeyWrite[], { create }: {
623
+ create: boolean;
624
+ }): string;
625
+ /** `value`, or the one stored at `slot` where it is NULL. */
626
+ protected jsonOrStored(slot: JsonSlot, value: string): string;
627
+ /** The array at `slot` without the elements equal to `item`, an empty one where it keeps none. */
628
+ protected jsonPulled(ctx: QueryContext, slot: JsonSlot, item: unknown): string;
629
+ /** The surviving elements of `slot` as one array, or NULL where there are none: `jsonPulled` supplies the empty one. */
630
+ protected jsonKept(ctx: QueryContext, slot: JsonSlot, item: unknown): string;
631
+ /** The elements a `$pull` keeps, aggregated into one array. */
620
632
  protected jsonArrayOf(elem: string): string;
621
633
  /** Whether an element is not the pulled value, both read as JSON. */
622
634
  protected jsonDiffers(elem: string, operand: string): string;
623
- /** Shallow assignment of top-level keys, matching PostgreSQL's `jsonb || jsonb`, through `JSON_SET`. */
624
- protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>, field?: FieldOptions): string;
625
- /** Append one value per array key, creating the array when the key is absent. */
626
- protected abstract jsonPush(ctx: QueryContext, expr: string, push: Record<string, unknown>): string;
635
+ /** Each key or dotted path assigned, its parents already there, through `JSON_SET`. */
636
+ protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>): string;
637
+ /** The JSON `array` with `value` appended. */
638
+ protected abstract jsonAppended(ctx: QueryContext, array: string, value: unknown): string;
639
+ /** A JSON object with no keys, as a key write takes it. */
640
+ protected readonly jsonEmptyObject: string;
641
+ /** A JSON array with no elements, as a key write takes it. */
642
+ protected readonly jsonEmptyArray: string;
643
+ /**
644
+ * A write at every parent of `paths`, outermost first, so a dotted `$set` has somewhere to write: an empty object
645
+ * in place of anything that is no object, a missing value included, and NULL, the stored one kept, where it is.
646
+ */
647
+ private jsonParents;
627
648
  /** Remove object keys, through `JSON_REMOVE`. */
628
649
  protected jsonUnset(_ctx: QueryContext, expr: string, unset: readonly string[]): string;
629
650
  /**
@@ -1,12 +1,13 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
2
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, RAW_ALIAS, } from '../type/index.js';
3
3
  import { utcTimestamp } from '../util/date.js';
4
- import { isExactDecimal, isInlinedExpression, jsonKey, jsonPathKeys } from '../util/field.util.js';
5
- import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
4
+ import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
5
+ import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJsonUpdate, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
6
+ import { isJsonScalar } from '../util/object.util.js';
6
7
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
7
8
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
8
9
  import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
9
- import { holdsOperator, isJsonScalar, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, } from './jsonSql.js';
10
+ import { holdsOperator, chainedCall, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, } from './jsonSql.js';
10
11
  import { betweenBounds, COMPARE_OPS, EQUALITY_OPS, GROUP_OPS, groupClauses, inOperands, isGroupOp, isOrderedOp, isVectorQuery, LIKE_OPS, namesRows, ORDERED_OPS, VECTOR_QUERY_KEY_SET, whereOperators, } from './operators.js';
11
12
  import { SqlQueryContext } from './queryContext.js';
12
13
  import { groupPathField, NO_JOINS, aggregateColumnField, resolveGroupJoins, resolveQueryJoins, relationSortTerms, resolveSortableJoin, } from './queryJoins.js';
@@ -1690,59 +1691,98 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1690
1691
  return `CAST(${operand} AS JSON)`;
1691
1692
  }
1692
1693
  /**
1693
- * `"col" = <expr>` for a JSON update, each operator wrapping the last: `$pull`, `$set`, `$push`, `$unset`.
1694
- * `$pull` reads the column and every later one its expression once, so no value binds twice.
1694
+ * `"col" = <expr>` for a JSON update, folded to one write per path, on an empty document in place of a NULL
1695
+ * column where one writes a key. Each write reads `current`, the column as stored.
1695
1696
  */
1696
1697
  formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
1697
- const { $pull, $set, $push, $unset } = value;
1698
- [...getKeys($pull), ...getKeys($set), ...getKeys($push), ...($unset ?? [])].forEach(jsonKey);
1699
- let expr = current;
1700
- if (hasKeys($pull)) {
1701
- expr = this.jsonPull(ctx, expr, current, $pull);
1702
- }
1703
- if (hasKeys($set)) {
1704
- expr = this.jsonSet(ctx, expr, $set, field);
1705
- }
1706
- if (hasKeys($push)) {
1707
- expr = this.jsonPush(ctx, expr, $push);
1708
- }
1709
- if ($unset?.length) {
1710
- expr = this.jsonUnset(ctx, expr, $unset);
1711
- }
1698
+ const writes = foldJsonUpdate(value);
1699
+ const arrays = Object.entries(writes.arrays);
1700
+ const keyWrites = (appending) => arrays
1701
+ .filter(([, write]) => write.appends.length > 0 === appending)
1702
+ .map(([key, write]) => {
1703
+ const slot = { base: current, path: key };
1704
+ return [slot, this.jsonArrayWrite(ctx, slot, write)];
1705
+ });
1706
+ // Pulls alone first, through a write creating no key: each built before the next, as positional values bind.
1707
+ const pulled = this.jsonWriteKeys(writesKeys(writes) ? jsonSetTarget(current, field, this.jsonEmptyObject) : current, keyWrites(false), { create: false });
1708
+ const withArrays = this.jsonWriteKeys(pulled, keyWrites(true), { create: true });
1709
+ const withSet = hasKeys(writes.set)
1710
+ ? this.jsonSet(ctx, this.jsonWriteKeys(withArrays, this.jsonParents(Object.keys(writes.set), current), { create: true }), writes.set)
1711
+ : withArrays;
1712
+ const expr = writes.unset.length > 0 ? this.jsonUnset(ctx, withSet, writes.unset) : withSet;
1712
1713
  ctx.append(`${escapedCol} = ${expr}`);
1713
1714
  }
1714
1715
  /**
1715
- * Remove every element equal to the given value, per array key. Each key wraps the expression
1716
- * built so far, so dialects only supply {@link jsonPullKey} - and because every key reads
1717
- * `escapedCol` rather than the accumulated expression, values bind once, in key order.
1716
+ * The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its pull, then each
1717
+ * append, onto `[]` in place of a missing or null array. With a `unique` append, a second branch writes the array
1718
+ * without it where the stored one holds its item; each branch is built in the order it binds.
1718
1719
  */
1719
- jsonPull(ctx, expr, escapedCol, pull) {
1720
- return Object.entries(pull).reduce((acc, [key, value]) => this.jsonPullKey(ctx, acc, escapedCol, key, value), expr);
1720
+ jsonArrayWrite(ctx, slot, { pull, appends }) {
1721
+ const isArray = this.jsonIs(slot, 'array');
1722
+ const kept = () => (pull ? this.jsonPulled(ctx, slot, pull.item) : this.jsonValue(slot));
1723
+ if (appends.length === 0) {
1724
+ return `CASE WHEN ${isArray} THEN ${kept()} END`;
1725
+ }
1726
+ const isNull = this.jsonIsNull(slot);
1727
+ const appended = (included) => included.reduce((array, { item }) => this.jsonAppended(ctx, array, item), `CASE WHEN ${isNull} THEN ${this.jsonEmptyArray} ELSE ${kept()} END`);
1728
+ const unique = appends.find((append) => append.unique);
1729
+ if (!unique) {
1730
+ return `CASE WHEN ${isNull} OR ${isArray} THEN ${appended(appends)} END`;
1731
+ }
1732
+ const lacks = `${isNull} OR ${isArray} AND NOT ${this.jsonContains(ctx, slot, [unique.item])}`;
1733
+ const withUnique = `WHEN ${lacks} THEN ${appended(appends)}`;
1734
+ const others = appends.filter((append) => append !== unique);
1735
+ const without = pull || others.length > 0 ? ` WHEN ${isArray} THEN ${appended(others)}` : '';
1736
+ return `CASE ${withUnique}${without} END`;
1721
1737
  }
1722
1738
  /**
1723
- * Wrap `expr` so the array at `key` no longer contains `value`: the array rebuilt from the elements that
1724
- * differ from it, and any other value put back as it is. `JSON_REPLACE` leaves an absent key, and a NULL
1725
- * column, untouched.
1739
+ * `expr` with each key written, through as few `JSON_SET` calls, or `JSON_REPLACE` where a missing key stays
1740
+ * missing, as `maxFunctionArgs` allows: every value reads the column as stored, so none needs another's result.
1726
1741
  */
1727
- jsonPullKey(ctx, expr, escapedCol, key, value) {
1728
- const slot = { base: escapedCol, path: key };
1742
+ jsonWriteKeys(expr, writes, { create }) {
1743
+ const pairs = writes.map(([slot, value]) => `${jsonPath(slot.path)}, ${this.jsonOrStored(slot, value)}`);
1744
+ return chainedCall(create ? 'JSON_SET' : 'JSON_REPLACE', expr, pairs, 2, this.maxFunctionArgs);
1745
+ }
1746
+ /** `value`, or the one stored at `slot` where it is NULL. */
1747
+ jsonOrStored(slot, value) {
1748
+ return `COALESCE(${value}, ${this.jsonValue(slot)})`;
1749
+ }
1750
+ /** The array at `slot` without the elements equal to `item`, an empty one where it keeps none. */
1751
+ jsonPulled(ctx, slot, item) {
1752
+ return `COALESCE((${this.jsonKept(ctx, slot, item)}), ${this.jsonEmptyArray})`;
1753
+ }
1754
+ /** The surviving elements of `slot` as one array, or NULL where there are none: `jsonPulled` supplies the empty one. */
1755
+ jsonKept(ctx, slot, item) {
1729
1756
  const elem = this.jsonElemValue(slot, JSON_PULL_ALIAS, 'json');
1730
- const differs = this.jsonDiffers(elem, this.jsonScalarParam(ctx, value));
1731
- const kept = `SELECT ${this.jsonArrayOf(elem)} FROM ${this.jsonElemFrom(slot, JSON_PULL_ALIAS)} WHERE ${differs}`;
1732
- const pulled = `CASE WHEN ${this.jsonIsArray(slot)} THEN (${kept}) ELSE ${this.jsonValue(slot)} END`;
1733
- return `JSON_REPLACE(${expr}, ${jsonPath(key)}, ${pulled})`;
1757
+ const differs = this.jsonDiffers(elem, this.jsonScalarParam(ctx, item));
1758
+ return `SELECT ${this.jsonArrayOf(elem)} FROM ${this.jsonElemFrom(slot, JSON_PULL_ALIAS)} WHERE ${differs}`;
1734
1759
  }
1735
- /** The elements a `$pull` keeps, back in one array, and an empty one where it keeps none. */
1760
+ /** The elements a `$pull` keeps, aggregated into one array. */
1736
1761
  jsonArrayOf(elem) {
1737
- return `COALESCE(JSON_ARRAYAGG(${elem}), JSON_ARRAY())`;
1762
+ return `JSON_ARRAYAGG(${elem})`;
1738
1763
  }
1739
1764
  /** Whether an element is not the pulled value, both read as JSON. */
1740
1765
  jsonDiffers(elem, operand) {
1741
1766
  return `${elem} <> ${operand}`;
1742
1767
  }
1743
- /** Shallow assignment of top-level keys, matching PostgreSQL's `jsonb || jsonb`, through `JSON_SET`. */
1744
- jsonSet(ctx, expr, set, field) {
1745
- return jsonSetCall((value) => this.jsonScalarParam(ctx, value), jsonSetTarget(expr, field, `'{}'`), set, this.maxFunctionArgs);
1768
+ /** Each key or dotted path assigned, its parents already there, through `JSON_SET`. */
1769
+ jsonSet(ctx, expr, set) {
1770
+ return jsonSetCall((value) => this.jsonScalarParam(ctx, value), expr, set, this.maxFunctionArgs);
1771
+ }
1772
+ /** A JSON object with no keys, as a key write takes it. */
1773
+ jsonEmptyObject = 'JSON_OBJECT()';
1774
+ /** A JSON array with no elements, as a key write takes it. */
1775
+ jsonEmptyArray = 'JSON_ARRAY()';
1776
+ /**
1777
+ * A write at every parent of `paths`, outermost first, so a dotted `$set` has somewhere to write: an empty object
1778
+ * in place of anything that is no object, a missing value included, and NULL, the stored one kept, where it is.
1779
+ */
1780
+ jsonParents(paths, current) {
1781
+ const parents = new Set(paths.flatMap(ancestorPaths));
1782
+ return [...parents].map((path) => {
1783
+ const slot = { base: current, path };
1784
+ return [slot, `CASE WHEN ${this.jsonIs(slot, 'object')} THEN NULL ELSE ${this.jsonEmptyObject} END`];
1785
+ });
1746
1786
  }
1747
1787
  /** Remove object keys, through `JSON_REMOVE`. */
1748
1788
  jsonUnset(_ctx, expr, unset) {
@@ -27,6 +27,14 @@ export declare const RELATION_ROW_ALIAS = "_uql_row";
27
27
  export declare const JSON_ELEM_ALIAS = "_uql_elem";
28
28
  /** The alias a `$pull` reads its surviving elements through, kept distinct from {@link JSON_ELEM_ALIAS}. */
29
29
  export declare const JSON_PULL_ALIAS = "_uql_pull";
30
+ /** The key a SQL Server JSON write aims at where it writes nothing, there being none by that name. */
31
+ export declare const JSON_SKIP_KEY = "_uql_skip";
32
+ /** What a savepoint the querier names is called, its depth appended. */
33
+ export declare const SAVEPOINT_PREFIX = "_uql_sp";
34
+ /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
35
+ export declare const CURSOR_ALIAS = "_uql_cursor";
36
+ /** The SQL Server table variable an `OUTPUT` fills. */
37
+ export declare const OUTPUT_TABLE = "@_uql_output";
30
38
  /** The field a MongoDB `$sort` by `$text` reads `textScore` from where it projects none, taken back out after. */
31
39
  export declare const TEXT_SCORE_ALIAS = "_uql_text_score";
32
40
  /**