uql-orm 0.102.1 → 0.102.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +2 -2
- package/dist/cockroachdb/cockroachDialect.d.ts +1 -1
- package/dist/cockroachdb/cockroachDialect.js +1 -1
- package/dist/dialect/abstractSqlDialect.d.ts +14 -13
- package/dist/dialect/abstractSqlDialect.js +33 -32
- package/dist/dialect/aliases.d.ts +5 -3
- package/dist/dialect/aliases.js +7 -3
- package/dist/dialect/jsonSql.d.ts +4 -0
- package/dist/dialect/jsonSql.js +9 -0
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -1
- package/dist/dialect/mysqlLikeSqlDialect.js +8 -3
- package/dist/dialect/pgLikeSqlDialect.d.ts +4 -3
- package/dist/dialect/pgLikeSqlDialect.js +10 -7
- package/dist/dialect/queryJoins.d.ts +1 -1
- package/dist/mariadb/mariaDialect.d.ts +2 -2
- package/dist/mariadb/mariaDialect.js +2 -2
- package/dist/mongodb/mongoDialect.d.ts +26 -20
- package/dist/mongodb/mongoDialect.js +178 -126
- package/dist/mssql/mssqlDialect.d.ts +8 -6
- package/dist/mssql/mssqlDialect.js +32 -20
- package/dist/sqlite/sqliteDialect.d.ts +1 -1
- package/dist/sqlite/sqliteDialect.js +3 -3
- package/dist/turso/tursoLocalDialect.d.ts +2 -2
- package/dist/turso/tursoLocalDialect.js +7 -5
- package/dist/type/entity.d.ts +25 -11
- package/dist/type/queryAggregate.d.ts +3 -6
- package/dist/type/utility.d.ts +2 -0
- package/dist/util/dialect.util.d.ts +13 -13
- package/dist/util/dialect.util.js +47 -13
- package/dist/util/object.util.d.ts +3 -3
- package/dist/util/object.util.js +1 -1
- package/package.json +3 -3
- package/skills/uql-orm/SKILL.md +1 -1
|
@@ -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
|
|
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 X=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};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=9074411D6DC000BB64756E2164756E21
|
|
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\n/**
|
|
8
|
+
"import type { EntityMeta, JsonScalar } from '../type/index.js';\n\n/** Whether `value` is a {@link JsonScalar}, which `$addToSet` and an `=` on a JSON path compare by equality. */\nexport function isJsonScalar(value: unknown): value is JsonScalar {\n return typeof value === 'string' || typeof value === 'boolean' || Number.isFinite(value);\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n if (!(size >= 1)) {\n throw new RangeError(`a chunk holds at least one item, not ${size}`);\n }\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\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",
|
|
@@ -14,6 +14,6 @@
|
|
|
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.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AAC,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": "
|
|
17
|
+
"debugId": "9074411D6DC000BB64756E2164756E21",
|
|
18
18
|
"names": []
|
|
19
19
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
|
|
2
2
|
import type { IndexType } from '../schema/types.js';
|
|
3
3
|
import type { QueryContext, SqlDialectFeatures, Type } from '../type/index.js';
|
|
4
|
-
/** CockroachDB: the Postgres wire and SQL,
|
|
4
|
+
/** CockroachDB: the Postgres wire and SQL, with native vectors. */
|
|
5
5
|
export declare class CockroachDialect extends PgLikeSqlDialect {
|
|
6
6
|
readonly dialectName = "cockroachdb";
|
|
7
7
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AGGREGATE_VALUE_ALIAS } from '../dialect/aliases.js';
|
|
2
2
|
import { PG_FEATURES, PG_VECTOR_METRICS, PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
|
|
3
3
|
import { getMeta } from '../entity/index.js';
|
|
4
|
-
/** CockroachDB: the Postgres wire and SQL,
|
|
4
|
+
/** CockroachDB: the Postgres wire and SQL, with native vectors. */
|
|
5
5
|
export class CockroachDialect extends PgLikeSqlDialect {
|
|
6
6
|
dialectName = 'cockroachdb';
|
|
7
7
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type JsonUpdateOp, type Query, type QueryAggMap, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryExclude, type QueryGroupMap, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type Type, type UpdatePayload } from '../type/index.js';
|
|
1
|
+
import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type JsonArrayUpdateOp, type JsonUpdateOp, type Query, type 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
4
|
import { type JsonAccessMode, type JsonContainer, type JsonKeyWrite, type JsonSlot } from './jsonSql.js';
|
|
@@ -608,11 +608,10 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
608
608
|
* `"col" = <expr>` for a JSON update, folded to one write per path, on an empty document in place of a NULL
|
|
609
609
|
* column where one writes a key. Each write reads `current`, the column as stored.
|
|
610
610
|
*/
|
|
611
|
-
protected formatJsonUpdate(ctx: QueryContext, escapedCol: string, value: JsonUpdateOp, field?: FieldOptions, current?: string): void;
|
|
611
|
+
protected formatJsonUpdate(ctx: QueryContext, escapedCol: string, value: JsonUpdateOp | JsonArrayUpdateOp, field?: FieldOptions, current?: string): void;
|
|
612
612
|
/**
|
|
613
|
-
* The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its
|
|
614
|
-
* append
|
|
615
|
-
* without it where the stored one holds its item; each branch is built in the order it binds.
|
|
613
|
+
* The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its pulls, then each
|
|
614
|
+
* append onto `[]` in place of a missing or null array, a `unique` one only where the stored array lacks its item.
|
|
616
615
|
*/
|
|
617
616
|
private jsonArrayWrite;
|
|
618
617
|
/**
|
|
@@ -624,18 +623,20 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
624
623
|
}): string;
|
|
625
624
|
/** `value`, or the one stored at `slot` where it is NULL. */
|
|
626
625
|
protected jsonOrStored(slot: JsonSlot, value: string): string;
|
|
627
|
-
/** The
|
|
628
|
-
protected
|
|
629
|
-
/** The
|
|
630
|
-
protected
|
|
626
|
+
/** The elements of `slot` no pulled item equals, as one array, or NULL where none is left. */
|
|
627
|
+
protected jsonKept(ctx: QueryContext, slot: JsonSlot, items: readonly unknown[]): string;
|
|
628
|
+
/** The one row per element of `slot` a pull reads, each as {@link JSON_PULL_ALIAS}. */
|
|
629
|
+
protected jsonKeptFrom(slot: JsonSlot): string;
|
|
630
|
+
/** The row {@link jsonKept} returns: the elements that survive, aggregated into one array. */
|
|
631
|
+
protected jsonKeptAggregate(slot: JsonSlot): string;
|
|
632
|
+
/** Whether the element a pull reads equals none of `items`, each compared as {@link jsonElemEquals} compares one. */
|
|
633
|
+
protected jsonEqualsNone(ctx: QueryContext, slot: JsonSlot, items: readonly unknown[]): string;
|
|
631
634
|
/** The elements a `$pull` keeps, aggregated into one array. */
|
|
632
635
|
protected jsonArrayOf(elem: string): string;
|
|
633
|
-
/** Whether an element is not the pulled value, both read as JSON. */
|
|
634
|
-
protected jsonDiffers(elem: string, operand: string): string;
|
|
635
636
|
/** Each key or dotted path assigned, its parents already there, through `JSON_SET`. */
|
|
636
637
|
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;
|
|
638
|
+
/** The JSON `array` with `value` appended, unless the condition `unless` holds. */
|
|
639
|
+
protected abstract jsonAppended(ctx: QueryContext, array: string, value: unknown, unless?: string): string;
|
|
639
640
|
/** A JSON object with no keys, as a key write takes it. */
|
|
640
641
|
protected readonly jsonEmptyObject: string;
|
|
641
642
|
/** A JSON array with no elements, as a key write takes it. */
|
|
@@ -2,12 +2,12 @@ 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
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,
|
|
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, foldJson, 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
6
|
import { isJsonScalar } from '../util/object.util.js';
|
|
7
7
|
import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
|
|
8
8
|
import { kindOf, UqlUsageError } from '../util/uqlError.js';
|
|
9
9
|
import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
|
|
10
|
-
import { holdsOperator, chainedCall, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, } from './jsonSql.js';
|
|
10
|
+
import { holdsOperator, chainedCall, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, unlessThen, } from './jsonSql.js';
|
|
11
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';
|
|
12
12
|
import { SqlQueryContext } from './queryContext.js';
|
|
13
13
|
import { groupPathField, NO_JOINS, aggregateColumnField, resolveGroupJoins, resolveQueryJoins, relationSortTerms, resolveSortableJoin, } from './queryJoins.js';
|
|
@@ -1695,7 +1695,13 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1695
1695
|
* column where one writes a key. Each write reads `current`, the column as stored.
|
|
1696
1696
|
*/
|
|
1697
1697
|
formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
|
|
1698
|
-
const
|
|
1698
|
+
const update = foldJson(value);
|
|
1699
|
+
if ('array' in update) {
|
|
1700
|
+
const slot = { base: current, path: '' };
|
|
1701
|
+
ctx.append(`${escapedCol} = ${this.jsonOrStored(slot, this.jsonArrayWrite(ctx, slot, update.array))}`);
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
const writes = update.object;
|
|
1699
1705
|
const arrays = Object.entries(writes.arrays);
|
|
1700
1706
|
const keyWrites = (appending) => arrays
|
|
1701
1707
|
.filter(([, write]) => write.appends.length > 0 === appending)
|
|
@@ -1713,27 +1719,20 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1713
1719
|
ctx.append(`${escapedCol} = ${expr}`);
|
|
1714
1720
|
}
|
|
1715
1721
|
/**
|
|
1716
|
-
* The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its
|
|
1717
|
-
* append
|
|
1718
|
-
* without it where the stored one holds its item; each branch is built in the order it binds.
|
|
1722
|
+
* The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its pulls, then each
|
|
1723
|
+
* append onto `[]` in place of a missing or null array, a `unique` one only where the stored array lacks its item.
|
|
1719
1724
|
*/
|
|
1720
|
-
jsonArrayWrite(ctx, slot, {
|
|
1725
|
+
jsonArrayWrite(ctx, slot, { pulls, appends }) {
|
|
1721
1726
|
const isArray = this.jsonIs(slot, 'array');
|
|
1722
|
-
const kept =
|
|
1727
|
+
const kept = pulls.length > 0
|
|
1728
|
+
? `COALESCE((${this.jsonKept(ctx, slot, pulls)}), ${this.jsonEmptyArray})`
|
|
1729
|
+
: this.jsonValue(slot);
|
|
1723
1730
|
if (appends.length === 0) {
|
|
1724
|
-
return `CASE WHEN ${isArray} THEN ${kept
|
|
1731
|
+
return `CASE WHEN ${isArray} THEN ${kept} END`;
|
|
1725
1732
|
}
|
|
1726
1733
|
const isNull = this.jsonIsNull(slot);
|
|
1727
|
-
const appended =
|
|
1728
|
-
|
|
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`;
|
|
1734
|
+
const appended = appends.reduce((array, { item, unique }) => this.jsonAppended(ctx, array, item, unique ? this.jsonContains(ctx, slot, [item]) : undefined), `CASE WHEN ${isNull} THEN ${this.jsonEmptyArray} ELSE ${kept} END`);
|
|
1735
|
+
return `CASE WHEN ${isNull} OR ${isArray} THEN ${appended} END`;
|
|
1737
1736
|
}
|
|
1738
1737
|
/**
|
|
1739
1738
|
* `expr` with each key written, through as few `JSON_SET` calls, or `JSON_REPLACE` where a missing key stays
|
|
@@ -1747,24 +1746,26 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1747
1746
|
jsonOrStored(slot, value) {
|
|
1748
1747
|
return `COALESCE(${value}, ${this.jsonValue(slot)})`;
|
|
1749
1748
|
}
|
|
1750
|
-
/** The
|
|
1751
|
-
|
|
1752
|
-
return `
|
|
1749
|
+
/** The elements of `slot` no pulled item equals, as one array, or NULL where none is left. */
|
|
1750
|
+
jsonKept(ctx, slot, items) {
|
|
1751
|
+
return `SELECT ${this.jsonKeptAggregate(slot)} FROM ${this.jsonKeptFrom(slot)} WHERE ${this.jsonEqualsNone(ctx, slot, items)}`;
|
|
1753
1752
|
}
|
|
1754
|
-
/** The
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1753
|
+
/** The one row per element of `slot` a pull reads, each as {@link JSON_PULL_ALIAS}. */
|
|
1754
|
+
jsonKeptFrom(slot) {
|
|
1755
|
+
return this.jsonElemFrom(slot, JSON_PULL_ALIAS);
|
|
1756
|
+
}
|
|
1757
|
+
/** The row {@link jsonKept} returns: the elements that survive, aggregated into one array. */
|
|
1758
|
+
jsonKeptAggregate(slot) {
|
|
1759
|
+
return this.jsonArrayOf(this.jsonElemValue(slot, JSON_PULL_ALIAS, 'json'));
|
|
1760
|
+
}
|
|
1761
|
+
/** Whether the element a pull reads equals none of `items`, each compared as {@link jsonElemEquals} compares one. */
|
|
1762
|
+
jsonEqualsNone(ctx, slot, items) {
|
|
1763
|
+
return chain(items.map((item) => `NOT (${this.jsonElemEquals(ctx, slot, JSON_PULL_ALIAS, item)})`), 'AND');
|
|
1759
1764
|
}
|
|
1760
1765
|
/** The elements a `$pull` keeps, aggregated into one array. */
|
|
1761
1766
|
jsonArrayOf(elem) {
|
|
1762
1767
|
return `JSON_ARRAYAGG(${elem})`;
|
|
1763
1768
|
}
|
|
1764
|
-
/** Whether an element is not the pulled value, both read as JSON. */
|
|
1765
|
-
jsonDiffers(elem, operand) {
|
|
1766
|
-
return `${elem} <> ${operand}`;
|
|
1767
|
-
}
|
|
1768
1769
|
/** Each key or dotted path assigned, its parents already there, through `JSON_SET`. */
|
|
1769
1770
|
jsonSet(ctx, expr, set) {
|
|
1770
1771
|
return jsonSetCall((value) => this.jsonScalarParam(ctx, value), expr, set, this.maxFunctionArgs);
|
|
@@ -1781,7 +1782,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1781
1782
|
const parents = new Set(paths.flatMap(ancestorPaths));
|
|
1782
1783
|
return [...parents].map((path) => {
|
|
1783
1784
|
const slot = { base: current, path };
|
|
1784
|
-
return [slot,
|
|
1785
|
+
return [slot, unlessThen(this.jsonIs(slot, 'object'), 'NULL', this.jsonEmptyObject)];
|
|
1785
1786
|
});
|
|
1786
1787
|
}
|
|
1787
1788
|
/** Remove object keys, through `JSON_REMOVE`. */
|
|
@@ -27,7 +27,7 @@ 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
|
|
30
|
+
/** The key a JSON write aims at where it writes nothing, there being none by that name, nor any key in an array. */
|
|
31
31
|
export declare const JSON_SKIP_KEY = "_uql_skip";
|
|
32
32
|
/** What a savepoint the querier names is called, its depth appended. */
|
|
33
33
|
export declare const SAVEPOINT_PREFIX = "_uql_sp";
|
|
@@ -43,8 +43,10 @@ export declare const TEXT_SCORE_ALIAS = "_uql_text_score";
|
|
|
43
43
|
* A dot becomes `_o` and an underscore `__`, so two paths such as `a.b` and `a_b` never share a flag.
|
|
44
44
|
*/
|
|
45
45
|
export declare function nullsSortField(path: string): string;
|
|
46
|
-
/**
|
|
47
|
-
export declare
|
|
46
|
+
/** The field a MongoDB lookup parks its result on, named by what it reads so two lookups alive at once cannot share one. */
|
|
47
|
+
export declare function relTempField(kind: 'cond' | 'field' | 'sort' | 'count' | 'rel', name: string | number): string;
|
|
48
|
+
/** Prefix for the field a MongoDB lookup puts a relation's rows on where a stored field has the relation's name. */
|
|
49
|
+
export declare const REL_FIELD_PREFIX = "_uql_joined_";
|
|
48
50
|
/** The field a ManyToMany lookup nests its target match under, inside the junction's own pipeline. */
|
|
49
51
|
export declare const REL_NESTED_KEY = "_uql_target";
|
|
50
52
|
/**
|
package/dist/dialect/aliases.js
CHANGED
|
@@ -28,7 +28,7 @@ export const RELATION_ROW_ALIAS = `${OWNED_PREFIX}_row`;
|
|
|
28
28
|
export const JSON_ELEM_ALIAS = `${OWNED_PREFIX}_elem`;
|
|
29
29
|
/** The alias a `$pull` reads its surviving elements through, kept distinct from {@link JSON_ELEM_ALIAS}. */
|
|
30
30
|
export const JSON_PULL_ALIAS = `${OWNED_PREFIX}_pull`;
|
|
31
|
-
/** The key a
|
|
31
|
+
/** The key a JSON write aims at where it writes nothing, there being none by that name, nor any key in an array. */
|
|
32
32
|
export const JSON_SKIP_KEY = `${OWNED_PREFIX}_skip`;
|
|
33
33
|
/** What a savepoint the querier names is called, its depth appended. */
|
|
34
34
|
export const SAVEPOINT_PREFIX = `${OWNED_PREFIX}_sp`;
|
|
@@ -46,8 +46,12 @@ export const TEXT_SCORE_ALIAS = `${OWNED_PREFIX}_text_score`;
|
|
|
46
46
|
export function nullsSortField(path) {
|
|
47
47
|
return `${OWNED_PREFIX}_nulls_${path.replace(/[._]/g, (char) => (char === '.' ? '_o' : '__'))}`;
|
|
48
48
|
}
|
|
49
|
-
/**
|
|
50
|
-
export
|
|
49
|
+
/** The field a MongoDB lookup parks its result on, named by what it reads so two lookups alive at once cannot share one. */
|
|
50
|
+
export function relTempField(kind, name) {
|
|
51
|
+
return `${OWNED_PREFIX}_rel_${kind}_${name}`;
|
|
52
|
+
}
|
|
53
|
+
/** Prefix for the field a MongoDB lookup puts a relation's rows on where a stored field has the relation's name. */
|
|
54
|
+
export const REL_FIELD_PREFIX = `${OWNED_PREFIX}_joined_`;
|
|
51
55
|
/** The field a ManyToMany lookup nests its target match under, inside the junction's own pipeline. */
|
|
52
56
|
export const REL_NESTED_KEY = `${OWNED_PREFIX}_target`;
|
|
53
57
|
/**
|
|
@@ -4,6 +4,10 @@ import type { FieldOptions, FieldType } from '../type/index.js';
|
|
|
4
4
|
* accessor such as `[#]` or `[*]`.
|
|
5
5
|
*/
|
|
6
6
|
export declare function jsonPath(path: string, suffix?: string): string;
|
|
7
|
+
/** `then`, or `skip` where the condition `unless` holds. */
|
|
8
|
+
export declare function unlessThen(unless: string | undefined, skip: string, then: string): string;
|
|
9
|
+
/** `path`, or a key no document has, which a write leaves alone, where the condition `unless` holds. */
|
|
10
|
+
export declare function skippablePath(path: string, unless: string | undefined): string;
|
|
7
11
|
/** A key a JSON update writes, and the value it writes there, NULL where the stored one stays. */
|
|
8
12
|
export type JsonKeyWrite = readonly [slot: JsonSlot, value: string];
|
|
9
13
|
/** The JSON values a path can be asked to hold, beside a scalar. */
|
package/dist/dialect/jsonSql.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isOperatorMap } from '../util/dialect.util.js';
|
|
2
2
|
import { columnFamily, jsonPathKeys } from '../util/field.util.js';
|
|
3
3
|
import { isOperatorKey, someKey } from '../util/object.util.js';
|
|
4
|
+
import { JSON_SKIP_KEY } from './aliases.js';
|
|
4
5
|
/**
|
|
5
6
|
* A `'$.a.b'` JSON path literal, and `'$'` for an empty path, the document itself. `suffix` appends an
|
|
6
7
|
* accessor such as `[#]` or `[*]`.
|
|
@@ -9,6 +10,14 @@ export function jsonPath(path, suffix = '') {
|
|
|
9
10
|
const segments = path && `.${jsonPathKeys(path).join('.')}`;
|
|
10
11
|
return `'$${segments}${suffix}'`;
|
|
11
12
|
}
|
|
13
|
+
/** `then`, or `skip` where the condition `unless` holds. */
|
|
14
|
+
export function unlessThen(unless, skip, then) {
|
|
15
|
+
return unless === undefined ? then : `CASE WHEN ${unless} THEN ${skip} ELSE ${then} END`;
|
|
16
|
+
}
|
|
17
|
+
/** `path`, or a key no document has, which a write leaves alone, where the condition `unless` holds. */
|
|
18
|
+
export function skippablePath(path, unless) {
|
|
19
|
+
return unlessThen(unless, jsonPath(JSON_SKIP_KEY), path);
|
|
20
|
+
}
|
|
12
21
|
/** `base, '$.a.b'`, how `JSON_EACH`, `OPENJSON` and the like take the value at `slot`: no path for the whole document. */
|
|
13
22
|
export function jsonSlotArgs({ base, path }) {
|
|
14
23
|
return path ? `${base}, ${jsonPath(path)}` : base;
|
|
@@ -95,7 +95,8 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
95
95
|
/** `DOUBLE`, never a bare `DECIMAL`, which is `DECIMAL(10,0)` and rounds `1.4` to `1`. */
|
|
96
96
|
protected numericCast(expr: string): string;
|
|
97
97
|
neExpr(field: string, ph: string): string;
|
|
98
|
-
|
|
98
|
+
/** A guarded one merges an array of it or of nothing, since MariaDB answers `JSON_ARRAY_APPEND` at a skipping path with NULL. */
|
|
99
|
+
protected jsonAppended(ctx: QueryContext, array: string, value: unknown, unless?: string): string;
|
|
99
100
|
/**
|
|
100
101
|
* `->` for the value and `->>` for its text, each taking the whole path (`'$.a.b'`): a bare key, as
|
|
101
102
|
* Postgres chains them, is "Invalid JSON path expression" here.
|
|
@@ -4,7 +4,7 @@ import { escapeMysqlSqlLiteral } from '../util/sqlLiteral.js';
|
|
|
4
4
|
import { ANSI_SQL_VALUES, AbstractSqlDialect, isolationSetBefore, } from './abstractSqlDialect.js';
|
|
5
5
|
import { AGGREGATE_VALUE_ALIAS } from './aliases.js';
|
|
6
6
|
import { BYTES_PREFIX } from './hydrateColumn.js';
|
|
7
|
-
import { jsonPath } from './jsonSql.js';
|
|
7
|
+
import { jsonPath, unlessThen } from './jsonSql.js';
|
|
8
8
|
import { aggregatesRelations } from './queryJoins.js';
|
|
9
9
|
/**
|
|
10
10
|
* The largest `BIGINT UNSIGNED`: the row count MySQL's manual gives for "all rows from the offset on",
|
|
@@ -219,8 +219,13 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
219
219
|
// MySQL/MariaDB null-safe inequality: true when values differ or one side is NULL.
|
|
220
220
|
return `NOT (${field} <=> ${ph})`;
|
|
221
221
|
}
|
|
222
|
-
|
|
223
|
-
|
|
222
|
+
/** A guarded one merges an array of it or of nothing, since MariaDB answers `JSON_ARRAY_APPEND` at a skipping path with NULL. */
|
|
223
|
+
jsonAppended(ctx, array, value, unless) {
|
|
224
|
+
if (unless === undefined) {
|
|
225
|
+
return `JSON_ARRAY_APPEND(${array}, '$', ${this.jsonScalarParam(ctx, value)})`;
|
|
226
|
+
}
|
|
227
|
+
const added = unlessThen(unless, this.jsonEmptyArray, `JSON_ARRAY(${this.jsonScalarParam(ctx, value)})`);
|
|
228
|
+
return `JSON_MERGE_PRESERVE(${array}, ${added})`;
|
|
224
229
|
}
|
|
225
230
|
/**
|
|
226
231
|
* `->` for the value and `->>` for its text, each taking the whole path (`'$.a.b'`): a bare key, as
|
|
@@ -122,8 +122,9 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
122
122
|
* `[1,0,2]` every other type takes is rejected as "invalid input syntax for type sparsevec".
|
|
123
123
|
*/
|
|
124
124
|
protected appendVectorValue(ctx: QueryContext, value: readonly unknown[], field?: FieldOptions): void;
|
|
125
|
-
/** `WITH ORDINALITY`
|
|
126
|
-
protected
|
|
125
|
+
/** `WITH ORDINALITY` numbers each element, which the aggregate orders by to keep the survivors in their order. */
|
|
126
|
+
protected jsonKeptFrom(slot: JsonSlot): string;
|
|
127
|
+
protected jsonKeptAggregate(): string;
|
|
127
128
|
/** Each key or dotted path set as `jsonb`, which `JSONB_SET` takes and nothing else. */
|
|
128
129
|
protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>): string;
|
|
129
130
|
/**
|
|
@@ -132,7 +133,7 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
132
133
|
*/
|
|
133
134
|
private jsonbOf;
|
|
134
135
|
/** `JSONB_BUILD_ARRAY` takes any type, and a NULL as JSON's null. */
|
|
135
|
-
protected jsonAppended(ctx: QueryContext, array: string, value: unknown): string;
|
|
136
|
+
protected jsonAppended(ctx: QueryContext, array: string, value: unknown, unless?: string): string;
|
|
136
137
|
protected readonly jsonEmptyObject = "'{}'::jsonb";
|
|
137
138
|
protected readonly jsonEmptyArray = "'[]'::jsonb";
|
|
138
139
|
/** `JSONB_SET` takes one path, so each key wraps the last. */
|
|
@@ -6,7 +6,7 @@ import { escapePgSqlLiteral, PG_UTC } from '../util/sqlLiteral.js';
|
|
|
6
6
|
import { ANSI_SQL_VALUES, AbstractSqlDialect, } from './abstractSqlDialect.js';
|
|
7
7
|
import { JSON_PULL_ALIAS, RELATION_ROW_ALIAS } from './aliases.js';
|
|
8
8
|
import { BYTES_PREFIX } from './hydrateColumn.js';
|
|
9
|
-
import {} from './jsonSql.js';
|
|
9
|
+
import { unlessThen } from './jsonSql.js';
|
|
10
10
|
import { resolveVectorCast, toSparsevecLiteral } from './vectorCast.js';
|
|
11
11
|
/** Each metric's pgvector distance operator, and the infix of the operator class its index is built with. */
|
|
12
12
|
export const PG_VECTOR_METRICS = new Map([
|
|
@@ -278,9 +278,12 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
278
278
|
ctx.addValue(vectorType === 'sparsevec' ? toSparsevecLiteral(value) : `[${value.join(',')}]`);
|
|
279
279
|
ctx.append(`::${vectorType}`);
|
|
280
280
|
}
|
|
281
|
-
/** `WITH ORDINALITY`
|
|
282
|
-
|
|
283
|
-
return `
|
|
281
|
+
/** `WITH ORDINALITY` numbers each element, which the aggregate orders by to keep the survivors in their order. */
|
|
282
|
+
jsonKeptFrom(slot) {
|
|
283
|
+
return `JSONB_ARRAY_ELEMENTS(${this.jsonValue(slot)}) WITH ORDINALITY AS ${JSON_PULL_ALIAS}(${JSON_PULL_ALIAS}, ord)`;
|
|
284
|
+
}
|
|
285
|
+
jsonKeptAggregate() {
|
|
286
|
+
return `JSONB_AGG(${JSON_PULL_ALIAS} ORDER BY ${JSON_PULL_ALIAS}.ord)`;
|
|
284
287
|
}
|
|
285
288
|
/** Each key or dotted path set as `jsonb`, which `JSONB_SET` takes and nothing else. */
|
|
286
289
|
jsonSet(ctx, expr, set) {
|
|
@@ -297,8 +300,8 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
297
300
|
return value === null ? `'null'::jsonb` : this.jsonVal(ctx, value);
|
|
298
301
|
}
|
|
299
302
|
/** `JSONB_BUILD_ARRAY` takes any type, and a NULL as JSON's null. */
|
|
300
|
-
jsonAppended(ctx, array, value) {
|
|
301
|
-
return `${array} || JSONB_BUILD_ARRAY(${this.jsonVal(ctx, value)})`;
|
|
303
|
+
jsonAppended(ctx, array, value, unless) {
|
|
304
|
+
return `${array} || ${unlessThen(unless, this.jsonEmptyArray, `JSONB_BUILD_ARRAY(${this.jsonVal(ctx, value)})`)}`;
|
|
302
305
|
}
|
|
303
306
|
jsonEmptyObject = `'{}'::jsonb`;
|
|
304
307
|
jsonEmptyArray = `'[]'::jsonb`;
|
|
@@ -316,7 +319,7 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
|
|
|
316
319
|
}
|
|
317
320
|
/** Postgres binds JSON with a numbered placeholder and an explicit cast, per driver capability. */
|
|
318
321
|
jsonScalarParam(ctx, value) {
|
|
319
|
-
return this.
|
|
322
|
+
return this.jsonbOf(ctx, value);
|
|
320
323
|
}
|
|
321
324
|
/**
|
|
322
325
|
* Helper to add a JSON value to context with appropriate stringification and cast.
|
|
@@ -6,7 +6,7 @@ import { type ParsedGroupEntry } from '../util/index.js';
|
|
|
6
6
|
* `$sort` needs - which joins the same way, filters included, but adds nothing to the result.
|
|
7
7
|
*/
|
|
8
8
|
export type QueryJoin = {
|
|
9
|
-
/** The relation key on its parent
|
|
9
|
+
/** The relation key on its parent. */
|
|
10
10
|
readonly key: string;
|
|
11
11
|
/** Dotted path from the queried entity, which is what a joined row's columns answer under. */
|
|
12
12
|
readonly path: string;
|