uql-orm 0.108.0 → 0.109.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +5 -5
- package/dist/dialect/abstractSqlDialect.d.ts +9 -14
- package/dist/dialect/abstractSqlDialect.js +17 -23
- package/dist/dialect/mergeSqlDialect.d.ts +2 -2
- package/dist/dialect/mergeSqlDialect.js +2 -2
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/mongodb/mongodbQuerier.d.ts +1 -1
- package/dist/mongodb/mongodbQuerier.js +8 -8
- package/dist/mssql/mssqlDialect.d.ts +2 -2
- package/dist/mssql/mssqlDialect.js +2 -2
- package/dist/querier/abstractQuerier.d.ts +32 -15
- package/dist/querier/abstractQuerier.js +48 -30
- package/dist/querier/abstractSqlQuerier.d.ts +1 -1
- package/dist/querier/abstractSqlQuerier.js +12 -12
- package/dist/type/dialect.d.ts +2 -3
- package/dist/type/querier.d.ts +28 -15
- package/dist/type/query.d.ts +18 -13
- package/dist/type/querySql.d.ts +4 -2
- package/dist/type/querySql.js +6 -2
- package/dist/type/universalQuerier.d.ts +12 -12
- package/dist/util/dialect.util.d.ts +3 -3
- package/dist/util/dialect.util.js +4 -3
- package/dist/util/index.d.ts +1 -1
- package/dist/util/object.util.d.ts +2 -0
- package/dist/util/object.util.js +4 -0
- package/dist/util/sql.d.ts +12 -4
- package/dist/util/sql.js +71 -23
- package/dist/util/triggerWrite.d.ts +10 -5
- package/dist/util/triggerWrite.js +5 -5
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +24 -18
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
npm install uql-orm pg
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
That is the whole install, `pg` swapped for your database's driver: `mysql2`, `mariadb`, `better-sqlite3`, `mongodb`, `@tursodatabase/serverless` or `@libsql/client` ([setup](https://uql-orm.dev/getting-started)). No compiler flags and no `reflect-metadata
|
|
36
|
+
That is the whole install, `pg` swapped for your database's driver: `mysql2`, `mariadb`, `better-sqlite3`, `mongodb`, `@tursodatabase/serverless` or `@libsql/client` ([setup](https://uql-orm.dev/getting-started)). No compiler flags and no `reflect-metadata`.
|
|
37
37
|
|
|
38
38
|
<a href="https://uql-orm.dev">
|
|
39
39
|
<picture>
|
|
@@ -149,6 +149,7 @@ The same queries run from the browser too: [serve them over HTTP](https://uql-or
|
|
|
149
149
|
|
|
150
150
|
- **One API, everywhere it runs.** PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, MSSQL, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun's native SQL, and even MongoDB. The same code on Node 22.18+, Bun, [Cloudflare Workers](https://uql-orm.dev/cloudflare-d1), [AWS Lambda and Vercel](https://uql-orm.dev/serverless), and [the browser](https://uql-orm.dev/browser), with no native binaries on the `fetch`-based drivers.
|
|
151
151
|
- **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
|
|
152
|
+
- **Decorators or plain data, your call.** An entity is a class with [standard TC39 decorators](https://uql-orm.dev/entities/basic), or plain data via [`defineEntity`](https://uql-orm.dev/entities/define-entity), its row type derived. Both are typed the same, mix in one project, and need no compiler flags or `reflect-metadata`.
|
|
152
153
|
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 27 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
|
|
153
154
|
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [multi-tenant filters you cannot bypass by accident](https://uql-orm.dev/multi-tenancy), [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming), and [drift checks](https://uql-orm.dev/migrations) that catch a database that no longer matches.
|
|
154
155
|
- **SQL when you need it.** [`sql()`](https://uql-orm.dev/querying/raw-sql) fits anywhere a value or a field goes, [computed fields](https://uql-orm.dev/entities/computed-fields) are SQL you can filter and sort on, and a migration can be plain SQL.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var f=new Set;function l(e){for(let r of f)r(e)}function A(e){return f.add(e),()=>{f.delete(e)}}var p={$select:{value:"object",scope:"relation"},$populate:{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",wire:!1},$after:{value:"string",scope:"statement"},$before:{value:"string",scope:"statement"}};var R=Symbol("sqlFn"),F=Symbol("rawAlias"),N=Symbol("sqlText"),
|
|
1
|
+
var f=new Set;function l(e){for(let r of f)r(e)}function A(e){return f.add(e),()=>{f.delete(e)}}var p={$select:{value:"object",scope:"relation"},$populate:{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",wire:!1},$after:{value:"string",scope:"statement"},$before:{value:"string",scope:"statement"}};var R=Symbol("sqlFn"),F=Symbol("rawAlias"),N=Symbol("sqlText"),W=Symbol("sqlValueType"),L=Symbol("refKey"),v=Symbol("refEntity"),_=Symbol("jsonPath"),D=Symbol("jsonValue");function d(e){return e?Object.keys(e):[]}function b(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 k extends Error{}class i extends k{name="UqlUsageError";kind="usage";status=400}var O=["hardDelete","count"],ee=new Map([...d(p).filter((e)=>M(p[e])).map((e)=>[e,p[e].value]),...O.map((e)=>[e,"boolean"])]);function M(e){return e.wire!==!1}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 w 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 g(e,r,t){return y(e,{method:"PUT",body:u(r)},t)}function Q(e,r){return y(e,{method:"DELETE"},r)}function q(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,c={message:m?.error?.message??n.statusText,code:m?.error?.code??n.status};throw l({phase:"error",error:c,opts:t}),new w(c.message,c.code)})).finally(()=>{l({phase:"complete",opts:t})})}function T(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:""}},C=d(o),ue=new Map(C.filter((e)=>o[e].method==="GET"&&o[e].path!=="/:id").map((e)=>[o[e].path,e]));function P(e){return T(e.name)}function S(e,r){if(!b(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)}/${S(e,r)}${a(t)}`,this.buildOptions(n));findOne=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findOne.path}`,r,t);findMany=(e,r,t)=>this.read(this.getBasePath(e),t?.count?{...r,count:!0}:r,t);findManyAndCount=async(e,r,t)=>{let n=await this.findMany(e,r,{...t,count:!0});if(typeof n.count!=="number")throw TypeError("findManyAndCount response has an invalid count");return{...n,count:n.count}};findManyPage=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.findManyPage.path}`,r,t);count=(e,r,t)=>this.read(`${this.getBasePath(e)}${o.count.path}`,r,t);exists=async(e,r,t)=>{let n=await this.count(e,{...r,$limit:1},t);return{...n,data:n.data>0}};insertOne=(e,r,t)=>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)}/${S(e,r)}`,t,this.buildOptions(n));updateMany=(e,r,t,n)=>x(`${this.getBasePath(e)}${a(r)}`,t,this.buildOptions(n));saveOne=(e,r,t)=>g(this.getBasePath(e),r,this.buildOptions(t));saveMany=(e,r,t)=>g(`${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)}/${S(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??P)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return q(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,w as RequestError,h as get,l as notify,A as on,x as patch,E as post,g as put,q as query,Q as remove};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=9E77C69A393BE19B64756E2164756E21
|
|
4
4
|
//# sourceMappingURL=uql-browser.min.js.map
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
"sources": ["../../src/browser/http/bus.ts", "../../src/type/query.ts", "../../src/type/querySql.ts", "../../src/util/object.util.ts", "../../src/util/uqlError.ts", "../../src/http/query.ts", "../../src/browser/http/http.ts", "../../src/util/string.util.ts", "../../src/http/contract.ts", "../../src/browser/querier/httpQuerier.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors = new Set<RequestCallback>();\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.add(cb);\n return (): void => {\n subscriptors.delete(cb);\n };\n}\n",
|
|
6
|
-
"import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/** The fields of a unique key an upsert finds a row by, `{ email: true }`, as `$select` names them. */\nexport type QueryConflictKeys<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * The rows an upsert writes: a row `$conflict`'s keys find, `{ email: true }`, takes the update where it matches\n * `$where`, as `updateMany` reads one, `{ status: ['done', 'failed'] }`, and stays as it is elsewhere; the rest insert.\n */\nexport type QueryUpsert<E, Sql = QuerySql> = QueryFilter<E, Sql> & { readonly $conflict: QueryConflictKeys<E> };\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * read in the same transaction after the write (before it, for a delete), so they hold what the database filled.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike> = {\n readonly returning?: QuerySelect<E, S, V>;\n};\n\n/** What each kind of write resolves to: its ids or its count where it names no `returning` field, else the rows it reads back. */\nexport type WriteResults<E, S, V> = [S] extends [never]\n ? {\n readonly inserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n }\n : {\n readonly inserted: ReturnedRow<E, S, V>;\n readonly affected: ReturnedRow<E, S, V> | undefined;\n readonly affectedMany: ReturnedRow<E, S, V>[];\n };\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
|
|
7
|
-
"import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, AbstractType } from './utility.js';\n\n/** What a `sql` callback receives. See {@link QuerySqlFn}. */\nexport type QuerySqlRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: AbstractType<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QuerySqlRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QuerySqlFnOptions = Partial<QuerySqlRenderOptions>;\n\n/**\n * A `sql` callback: write into `ctx`, or return a string or number to have it appended. Anything else\n * it returns is ignored, which is why the return type is `unknown` rather than `void | Scalar` - the\n * latter rejected `({ ctx }) => ctx.append(...)`, the form every computed field is written in, because\n * TypeScript's \"returning a value where void is expected\" allowance does not apply to a union.\n */\nexport type QuerySqlFn = (opts: QuerySqlRenderOptions) => unknown;\n\nexport const SQL_FN: unique symbol = Symbol('sqlFn');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const SQL_TEXT: unique symbol = Symbol('sqlText');\n/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */\nexport const SQL_VALUE_TYPE: unique symbol = Symbol('sqlValueType');\n/** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */\nexport const REF_KEY: unique symbol = Symbol('refKey');\n\n/** The entity a {@link ColumnRef} was read off, where it names one: a definition's refs name none. */\nexport const REF_ENTITY: unique symbol = Symbol('refEntity');\n/** The dotted path a {@link JsonPathRef} reads down its column's document. */\nexport const JSON_PATH: unique symbol = Symbol('jsonPath');\n/** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */\nexport const JSON_VALUE: unique symbol = Symbol('jsonValue');\n\n/**\n * What a `sql` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type SqlArg = Scalar | null | readonly (Scalar | null)[] | QuerySql;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `sql` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: SqlArg[]] | readonly [sql: QuerySql];\n\nexport class QuerySql {\n readonly [SQL_FN]: QuerySqlFn;\n readonly [RAW_ALIAS]?: string;\n /**\n * The SQL verbatim, set only where it is a constant: a template that interpolates nothing binds no\n * value and reads no column, so it needs no dialect to render. What a DDL clause with nowhere to\n * bind reads - see {@link constantSql}.\n */\n readonly [SQL_TEXT]?: string;\n\n constructor(value: QuerySqlFn, { alias, text }: { readonly alias?: string; readonly text?: string } = {}) {\n this[SQL_FN] = value;\n this[RAW_ALIAS] = alias;\n this[SQL_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QuerySql {\n return new QuerySql(this[SQL_FN], { alias, text: this[SQL_TEXT] });\n }\n}\n\n/** Writes `statement` into `opts.ctx`. The alias is the projection's to write, after the term. */\nexport function renderSql(statement: QuerySql, opts: QuerySqlRenderOptions): void {\n const emitted = statement[SQL_FN](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `sql`, it\n * renders as the field's column. Its key is how an index tells a column from an expression, and `V`,\n * the field's type, is what a value slot checks it against: see {@link SqlFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n readonly [REF_KEY]: K;\n readonly
|
|
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\n/** Orders two strings by code unit, or two numbers by value, the order every engine sorts text by, so names and JSON keys agree across them. */\nexport function byCodeUnit<T extends string | number>(a: T, b: T): number {\n return a < b ? -1 : 1;\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n if (!(size >= 1)) {\n throw new RangeError(`a chunk holds at least one item, not ${size}`);\n }\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** A shallow copy of `value` without `keys`. */\nexport function omitKeys<T extends object>(value: T, keys: Iterable<string>): T {\n const copy = { ...value };\n for (const key of keys) {\n Reflect.deleteProperty(copy, key);\n }\n return copy;\n}\n\n/** The value `cache` holds for `key`, computed and held the first time it is asked for. */\nexport function cachedIn<K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n compute: () => V,\n): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n\n/** What `text` spells as JSON, or nothing where it is no JSON at all. */\nexport function jsonDocument(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n",
|
|
6
|
+
"import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n UpdateWrite,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/** The fields of a unique key an upsert finds a row by, `{ email: true }`, as `$select` names them. */\nexport type QueryConflictKeys<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * The rows an upsert writes: a row `$conflict`'s keys find, `{ email: true }`, takes `$update` where it matches `$where`,\n * as `updateMany` reads one, `{ status: ['done', 'failed'] }`, and stays as it is elsewhere; the rest insert. Without\n * `$update` a found row takes the payload less its key and `$conflict`'s; `$update: {}` keeps it as it is.\n */\nexport type QueryUpsert<E, Sql = QuerySql, U = UpdateWrite<E, Sql>> = QueryFilter<E, Sql> & {\n readonly $conflict: QueryConflictKeys<E>;\n readonly $update?: U;\n};\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * or `true` for every field a read returns, read in the same transaction after the write (before it, for a delete), so\n * they hold what the database filled. `W` is `true` for `returning: true`, and `boolean` for a map.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike, W = boolean> = {\n readonly returning?: QuerySelect<E, S, V> | W;\n};\n\n/** What each kind of write resolves to: its ids or its count where it reads nothing back, else the rows it reads. */\nexport type WriteResults<E, S, V, W = false> = [W] extends [true]\n ? ReturnedRows<Pick<E, FieldKey<E>>>\n : [W] extends [false]\n ? WrittenIds<E>\n : [S] extends [never]\n ? WrittenIds<E>\n : ReturnedRows<ReturnedRow<E, S, V>>;\n\ntype WrittenIds<E> = {\n readonly inserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n};\n\ntype ReturnedRows<R> = { readonly inserted: R; readonly affected: R | undefined; readonly affectedMany: R[] };\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
|
|
7
|
+
"import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, AbstractType } from './utility.js';\n\n/** What a `sql` callback receives. See {@link QuerySqlFn}. */\nexport type QuerySqlRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: AbstractType<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QuerySqlRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QuerySqlFnOptions = Partial<QuerySqlRenderOptions>;\n\n/**\n * A `sql` callback: write into `ctx`, or return a string or number to have it appended. Anything else\n * it returns is ignored, which is why the return type is `unknown` rather than `void | Scalar` - the\n * latter rejected `({ ctx }) => ctx.append(...)`, the form every computed field is written in, because\n * TypeScript's \"returning a value where void is expected\" allowance does not apply to a union.\n */\nexport type QuerySqlFn = (opts: QuerySqlRenderOptions) => unknown;\n\nexport const SQL_FN: unique symbol = Symbol('sqlFn');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const SQL_TEXT: unique symbol = Symbol('sqlText');\n/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */\nexport const SQL_VALUE_TYPE: unique symbol = Symbol('sqlValueType');\n/** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */\nexport const REF_KEY: unique symbol = Symbol('refKey');\n\n/** The entity a {@link ColumnRef} was read off, where it names one: a definition's refs name none. */\nexport const REF_ENTITY: unique symbol = Symbol('refEntity');\n/** The dotted path a {@link JsonPathRef} reads down its column's document. */\nexport const JSON_PATH: unique symbol = Symbol('jsonPath');\n/** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */\nexport const JSON_VALUE: unique symbol = Symbol('jsonValue');\n\n/**\n * What a `sql` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type SqlArg = Scalar | null | readonly (Scalar | null)[] | QuerySql;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `sql` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: SqlArg[]] | readonly [sql: QuerySql];\n\nexport class QuerySql {\n readonly [SQL_FN]: QuerySqlFn;\n readonly [RAW_ALIAS]?: string;\n /**\n * The SQL verbatim, set only where it is a constant: a template that interpolates nothing binds no\n * value and reads no column, so it needs no dialect to render. What a DDL clause with nowhere to\n * bind reads - see {@link constantSql}.\n */\n readonly [SQL_TEXT]?: string;\n\n constructor(value: QuerySqlFn, { alias, text }: { readonly alias?: string; readonly text?: string } = {}) {\n this[SQL_FN] = value;\n this[RAW_ALIAS] = alias;\n this[SQL_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QuerySql {\n return new QuerySql(this[SQL_FN], { alias, text: this[SQL_TEXT] });\n }\n}\n\n/** Writes `statement` into `opts.ctx`. The alias is the projection's to write, after the term. */\nexport function renderSql(statement: QuerySql, opts: QuerySqlRenderOptions): void {\n const emitted = statement[SQL_FN](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `sql`, it\n * renders as the field's column. Its key is how an index tells a column from an expression, and `V`,\n * the field's type, is what a value slot checks it against: see {@link SqlFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n readonly [REF_KEY]: K;\n readonly #entity?: () => AbstractType<unknown>;\n\n /** `entity` is read when the ref is, so an entity declared after the ref resolves. */\n constructor(key: K, value: QuerySqlFn, entity?: () => AbstractType<unknown>) {\n super(value);\n this[REF_KEY] = key;\n this.#entity = entity;\n }\n\n get [REF_ENTITY](): AbstractType<unknown> | undefined {\n return this.#entity?.();\n }\n}\n\n/**\n * A path inside a JSON column, read off an index's refs as the `$where` key it is: `user.settings.theme`\n * for `'settings.theme'`. `V`, the value at the path, decides how the index has to read it.\n */\nexport class JsonPathRef<V = unknown> {\n declare readonly [JSON_VALUE]?: V;\n readonly [REF_KEY]: string;\n readonly [JSON_PATH]: string;\n\n constructor(key: string, path: string) {\n this[REF_KEY] = key;\n this[JSON_PATH] = path;\n }\n}\n\n/**\n * SQL where a value of type `V` goes: bare SQL, whose type is its author's to know, or a ref to a column\n * holding one, nullability aside. `Sql` is what the transport carries, so the wire's `never` stays one.\n */\nexport type SqlFor<Sql, V> = Sql & { readonly [SQL_VALUE_TYPE]?: V | null };\n\n/**\n * A relation aggregate as SQL, read off a `computed` field's refs: `(user) => user.resources.count()`.\n * It renders as the correlated subquery a `$count` reads, so a field holding one is read, filtered and\n * sorted like any other.\n *\n * `V` is the value it reads, carried in a phantom field so the aggregate a field declares decides the\n * property's type.\n */\nexport class RelationAggregate<V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n\n constructor(\n /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */\n readonly spec: RelationAggregateSpec,\n value: QuerySqlFn,\n ) {\n super(value);\n }\n}\n\n/**\n * A write `insertInto`, `updateTable` or `deleteFrom` renders, or several joined in one `sql`. It reads a\n * set-based trigger's rows through {@link QuerySqlRenderOptions.rows}, which is how `of` and `where` narrow\n * them there; SQL of its own reads `inserted` and `deleted` whole.\n */\nexport class TriggerWriteSql extends QuerySql {}\n",
|
|
8
|
+
"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\n/** Orders two strings by code unit, or two numbers by value, the order every engine sorts text by, so names and JSON keys agree across them. */\nexport function byCodeUnit<T extends string | number>(a: T, b: T): number {\n return a < b ? -1 : 1;\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. */\n/** Whether `value` is a class, which an arrow, with no `prototype`, is not. */\nexport function isClass(value: unknown): boolean {\n return typeof value === 'function' && value.prototype !== undefined;\n}\n\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** A shallow copy of `value` without `keys`. */\nexport function omitKeys<T extends object>(value: T, keys: Iterable<string>): T {\n const copy = { ...value };\n for (const key of keys) {\n Reflect.deleteProperty(copy, key);\n }\n return copy;\n}\n\n/** The value `cache` holds for `key`, computed and held the first time it is asked for. */\nexport function cachedIn<K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n compute: () => V,\n): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n\n/** What `text` spells as JSON, or nothing where it is no JSON at all. */\nexport function jsonDocument(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n",
|
|
9
9
|
"/**\n * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers\n * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization\n * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the\n * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.\n */\nexport type QueryErrorKind =\n | 'uniqueViolation'\n | 'foreignKeyViolation'\n | 'notNullViolation'\n | 'checkViolation'\n | 'optimisticLock'\n | 'retryable'\n | 'usage'\n | 'security';\n\n/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */\nexport abstract class UqlError extends Error {\n abstract readonly kind: QueryErrorKind;\n abstract readonly status: number;\n}\n\n/**\n * Thrown where the caller used the API in a way no statement can carry out: an update payload with no\n * version, a `$lock` outside a transaction, a method with no version to match. A `400` over HTTP: the\n * request is malformed, not the server's failure, and an untyped client is exactly who reaches this.\n */\nexport class UqlUsageError extends UqlError {\n override name = 'UqlUsageError';\n readonly kind = 'usage';\n readonly status = 400;\n}\n\n/**\n * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.\n * Fails the statement closed.\n */\nexport class UqlSecurityError extends UqlError {\n override name = 'UqlSecurityError';\n readonly kind = 'security';\n readonly status = 403;\n}\n\n/** What a value is, for a refusal naming what `/http` handed over instead of what the types require. */\nexport function kindOf(value: unknown): string {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Thrown when an update's `f.version()` column no longer matches the row: another writer moved it on,\n * or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`\n * where there is no row left.\n */\nexport class UqlOptimisticLockError extends UqlError {\n override name = 'UqlOptimisticLockError';\n readonly kind = 'optimisticLock';\n readonly status = 409;\n\n constructor(\n message: string,\n readonly expected: unknown,\n readonly actual: unknown,\n ) {\n super(message);\n }\n}\n",
|
|
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 * The keys accepted from the wire, mapped to how each value is decoded: every query clause ({@link QUERY_CLAUSES})\n * HTTP carries, plus the {@link WIRE_FLAGS}. Any other `$` key is refused, since dropping a clause answers a read\n * other than the one asked for; any other key (e.g. `filters`, `context`) is dropped, so a remote client can't\n * bypass a security filter or inject ambient context.\n */\nconst WIRE_VALUES: ReadonlyMap<string, QueryClause['value']> = new Map([\n ...getKeys(QUERY_CLAUSES)\n .filter((key) => carriedOverHttp(QUERY_CLAUSES[key]))\n .map((key) => [key, QUERY_CLAUSES[key].value] as const),\n ...WIRE_FLAGS.map((flag) => [flag, 'boolean'] as const),\n]);\n\nfunction carriedOverHttp(clause: QueryClause): boolean {\n return clause.wire !== false;\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 const shape = WIRE_VALUES.get(key);\n if (!shape && key.startsWith('$')) {\n throw new UqlUsageError(`'${key}' is not a query key HTTP takes`);\n }\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 { AbstractType, 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: AbstractType<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, AbstractType } 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: AbstractType<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: AbstractType<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: AbstractType<E>) {\n return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;\n }\n\n protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions) {\n if (this.defaults.readMethod === 'QUERY') {\n return httpQuery<T>(path, q ?? {}, this.buildOptions(opts));\n }\n return get<T>(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));\n }\n\n protected buildOptions(opts?: RequestOptions): RequestOptions | undefined {\n if (!this.defaults.headers && !opts?.headers) {\n return opts;\n }\n return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };\n }\n}\n"
|
|
15
15
|
],
|
|
16
|
-
"mappings": "AAEA,IAAM,EAAe,IAAI,IAElB,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAElD,OADA,EAAa,IAAI,CAAE,EACZ,IAAY,CACjB,EAAa,OAAO,CAAE,
|
|
17
|
-
"debugId": "
|
|
16
|
+
"mappings": "AAEA,IAAM,EAAe,IAAI,IAElB,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAElD,OADA,EAAa,IAAI,CAAE,EACZ,IAAY,CACjB,EAAa,OAAO,CAAE,GCiVnB,IAAM,EAAgB,CAC3B,QAAS,CAAE,MAAO,SAAU,MAAO,UAAW,EAC9C,UAAW,CAAE,MAAO,SAAU,MAAO,UAAW,EAChD,OAAQ,CAAE,MAAO,SAAU,MAAO,UAAW,EAC7C,MAAO,CAAE,MAAO,SAAU,MAAO,UAAW,EAC5C,MAAO,CAAE,MAAO,SAAU,MAAO,UAAW,EAC5C,OAAQ,CAAE,MAAO,SAAU,MAAO,UAAW,EAC7C,UAAW,CAAE,MAAO,UAAW,MAAO,UAAW,EAEjD,OAAQ,CAAE,MAAO,SAAU,MAAO,WAAY,EAE9C,YAAa,CAAE,MAAO,SAAU,MAAO,WAAY,EAEnD,MAAO,CAAE,MAAO,SAAU,MAAO,YAAa,KAAM,EAAM,EAE1D,OAAQ,CAAE,MAAO,SAAU,MAAO,WAAY,EAC9C,QAAS,CAAE,MAAO,SAAU,MAAO,WAAY,CACjD,EC3UO,IAAM,EAAwB,OAAO,OAAO,EACtC,EAA2B,OAAO,UAAU,EAC5C,EAA0B,OAAO,SAAS,EAE1C,EAAgC,OAAO,cAAc,EAErD,EAAyB,OAAO,QAAQ,EAGxC,EAA4B,OAAO,WAAW,EAE9C,EAA2B,OAAO,UAAU,EAE5C,EAA4B,OAAO,WAAW,EC8CpD,SAAS,CAAyB,CAAC,EAAiD,CACzF,OAAO,EAAO,OAAO,KAAK,CAAG,EAA6B,CAAC,EAsBtD,SAAS,CAAU,CAAC,EAAyB,CAClD,GAAI,OAAO,IAAU,UAAY,IAAU,KACzC,MAAO,GAET,GAAI,MAAM,QAAQ,CAAK,EACrB,MAAO,GAKT,IAAM,EAAQ,OAAO,eAAe,CAAK,EACzC,OAAO,IAAU,OAAO,WAAa,IAAU,KChH1C,MAAe,UAAiB,KAAM,CAG7C,CAOO,MAAM,UAAsB,CAAS,CACjC,KAAO,gBACP,KAAO,QACP,OAAS,GACpB,CCnBA,IAAM,EAAa,CAAC,aAAc,OAAO,EAcnC,GAAyD,IAAI,IAAI,CACrE,GAAG,EAAQ,CAAa,EACrB,OAAO,CAAC,IAAQ,EAAgB,EAAc,EAAI,CAAC,EACnD,IAAI,CAAC,IAAQ,CAAC,EAAK,EAAc,GAAK,KAAK,CAAU,EACxD,GAAG,EAAW,IAAI,CAAC,IAAS,CAAC,EAAM,SAAS,CAAU,CACxD,CAAC,EAED,SAAS,CAAe,CAAC,EAA8B,CACrD,OAAO,EAAO,OAAS,GA6DlB,SAAS,CAAc,CAAC,EAAyC,CACtE,GAAI,CAAC,EACH,MAAO,GAET,IAAM,EAAS,IAAI,gBACnB,QAAW,KAAO,EAAQ,CAAK,EAAG,CAChC,IAAM,EAAQ,EAAM,GACpB,GAAI,IAAU,OACZ,SAEF,EAAO,OAAO,EAAK,OAAO,IAAU,UAAY,IAAU,KAAO,EAAS,CAAK,EAAI,OAAO,CAAK,CAAC,EAElG,IAAM,EAAK,EAAO,SAAS,EAC3B,OAAO,EAAK,IAAI,IAAO,GAUlB,SAAS,CAAQ,CAAC,EAAwB,CAC/C,OAAO,KAAK,UAAU,EAAO,CAAC,EAAc,IAAkB,CAC5D,GAAI,OAAO,IAAS,UAAY,IAAS,KACvC,OAAO,EAET,GAAI,KAAU,EACZ,MAAM,IAAI,EAAc,kEAAkE,EAG5F,GAAI,aAAgB,aAAe,YAAY,OAAO,CAAI,EACxD,MAAM,IAAI,EAAc,iEAAiE,EAE3F,OAAO,EACR,ECzHI,MAAM,UAAqB,KAAM,CAG3B,OAFX,WAAW,CACT,EACS,EACT,CACA,MAAM,CAAO,EAFJ,cAGT,KAAK,KAAO,eAEhB,CAIO,SAAS,CAAM,CAAC,EAAa,EAAuB,CACzD,OAAO,EAAW,EAAK,CAAE,OAAQ,KAAM,EAAG,CAAI,EAGzC,SAAS,CAAO,CAAC,EAAa,EAAkB,EAAuB,CAC5E,OAAO,EAAW,EAAK,CAAE,OAAQ,OAAQ,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAGnE,SAAS,CAAQ,CAAC,EAAa,EAAkB,EAAuB,CAC7E,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAGpE,SAAS,CAAM,CAAC,EAAa,EAAkB,EAAuB,CAC3E,OAAO,EAAW,EAAK,CAAE,OAAQ,MAAO,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAGlE,SAAS,CAAS,CAAC,EAAa,EAAuB,CAC5D,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,EAAG,CAAI,EAO5C,SAAS,CAAQ,CAAC,EAAa,EAAkB,EAAuB,CAC7E,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,KAAM,EAAS,CAAO,CAAE,EAAG,CAAI,EAG3E,SAAS,CAAU,CAAC,EAAa,EAAmB,EAAuB,CAQzE,GAPA,EAAO,CAAE,MAAO,QAAS,MAAK,CAAC,EAE/B,EAAK,QAAU,CACb,OAAQ,mBACR,eAAgB,sBACb,GAAM,OACX,EACI,GAAM,OACR,EAAK,OAAS,EAAK,OAGrB,OAAO,MAAM,EAAK,CAAI,EACnB,KAAK,CAAC,IACL,EAAQ,KAAK,EAAE,KAAK,CAAC,IAAkB,CAErC,GADkB,EAAQ,QAAU,KAAO,EAAQ,OAAS,IAG1D,OADA,EAAO,CAAE,MAAO,UAAW,MAAK,CAAC,EAC1B,EAET,IAAM,EAAY,EACZ,EAAQ,CACZ,QAAS,GAAW,OAAO,SAAW,EAAQ,WAC9C,KAAM,GAAW,OAAO,MAAQ,EAAQ,MAC1C,EAEA,MADA,EAAO,CAAE,MAAO,QAAS,QAAO,MAAK,CAAC,EAChC,IAAI,EAAa,EAAM,QAAS,EAAM,IAAI,EACjD,CACH,EACC,QAAQ,IAAM,CACb,EAAO,CAAE,MAAO,WAAY,MAAK,CAAC,EACnC,ECjFE,SAAS,CAAS,CAAC,EAAqB,CAC7C,IAAI,EAAO,EAAI,OAAO,CAAC,EAAE,YAAY,EACrC,QAAS,EAAI,EAAG,EAAI,EAAI,OAAQ,EAAE,EAChC,GAAQ,EAAI,KAAO,EAAI,GAAG,YAAY,EAAI,IAAM,EAAI,GAAG,YAAY,EAAI,EAAI,GAE7E,OAAO,ECYF,IAAM,EAAc,CACzB,SAAU,CAAE,OAAQ,MAAO,KAAM,EAAG,EACpC,aAAc,CAAE,OAAQ,MAAO,KAAM,OAAQ,EAC7C,QAAS,CAAE,OAAQ,MAAO,KAAM,MAAO,EACvC,MAAO,CAAE,OAAQ,MAAO,KAAM,QAAS,EACvC,YAAa,CAAE,OAAQ,MAAO,KAAM,MAAO,EAC3C,UAAW,CAAE,OAAQ,OAAQ,KAAM,EAAG,EACtC,WAAY,CAAE,OAAQ,OAAQ,KAAM,OAAQ,EAC5C,QAAS,CAAE,OAAQ,MAAO,KAAM,EAAG,EACnC,SAAU,CAAE,OAAQ,MAAO,KAAM,OAAQ,EACzC,WAAY,CAAE,OAAQ,QAAS,KAAM,EAAG,EACxC,cAAe,CAAE,OAAQ,QAAS,KAAM,MAAO,EAC/C,cAAe,CAAE,OAAQ,SAAU,KAAM,MAAO,EAChD,WAAY,CAAE,OAAQ,SAAU,KAAM,EAAG,CAC3C,EAaM,EAAW,EAAQ,CAAW,EAG9B,GAAqD,IAAI,IAC7D,EAAS,OAAO,CAAC,IAAO,EAAY,GAAI,SAAW,OAAS,EAAY,GAAI,OAAS,MAAM,EAAE,IAAI,CAAC,IAAO,CACvG,EAAY,GAAI,KAChB,CACF,CAAC,CACH,EAKO,SAAS,CAAa,CAAC,EAAiC,CAC7D,OAAO,EAAU,EAAO,IAAI,EC7B9B,SAAS,CAAY,CAAC,EAAyB,EAAyB,CACtE,GAAI,CAAC,EAAW,CAAE,EAChB,MAAM,IAAI,EAAc,IAAI,EAAO,yEAAyE,EAE9G,OAAO,OAAO,CAAE,EAGX,MAAM,CAAqC,CAErC,SACA,SAFX,WAAW,CACA,EACA,EAAgC,CAAC,EAC1C,CAFS,gBACA,gBAIF,YAA4C,MAAO,EAAQ,EAAI,EAAG,IACzE,EAAI,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAI,EAAe,CAAC,IAAK,KAAK,aAAa,CAAI,CAAC,EAEhG,QAAoC,CAAC,EAAQ,EAAG,IACvD,KAAK,KAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,QAAQ,OAAQ,EAAG,CAAI,EAEpE,SAAoE,CAAC,EAAQ,EAAG,IACvF,KAAK,KAAK,KAAK,YAAY,CAAM,EAAG,GAAM,MAAQ,IAAK,EAAG,MAAO,EAAK,EAAI,EAAG,CAAI,EAE1E,iBAAoF,MAC3F,EACA,EACA,IACG,CACH,IAAM,EAAW,MAAM,KAAK,SAAS,EAAQ,EAAG,IAAK,EAAM,MAAO,EAAK,CAAC,EACxE,GAAI,OAAO,EAAS,QAAU,SAC5B,MAAU,UAAU,gDAAgD,EAEtE,MAAO,IAAK,EAAU,MAAO,EAAS,KAAM,GAGrC,aAA8C,CAAC,EAAQ,EAAG,IACjE,KAAK,KAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,aAAa,OAAQ,EAAG,CAAI,EAEzE,MAAgC,CAAC,EAAQ,EAAG,IACnD,KAAK,KAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,MAAM,OAAQ,EAAG,CAAI,EAGlE,OAAkC,MAAO,EAAQ,EAAG,IAAS,CACpE,IAAM,EAAM,MAAM,KAAK,MAAM,EAAQ,IAAK,EAAG,OAAQ,CAAE,EAAG,CAAI,EAC9D,MAAO,IAAK,EAAK,KAAM,EAAI,KAAO,CAAE,GAG7B,UAAwC,CAAC,EAAQ,EAAS,IACjE,EAAK,KAAK,YAAY,CAAM,EAAG,EAAS,KAAK,aAAa,CAAI,CAAC,EAExD,WAA0C,CAAC,EAAQ,EAAS,IACnE,EAAK,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,WAAW,OAAQ,EAAS,KAAK,aAAa,CAAI,CAAC,EAE3F,cAAgD,MAAO,EAAQ,EAAI,EAAS,IACnF,EAAM,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAK,EAAS,KAAK,aAAa,CAAI,CAAC,EAEvF,WAA0C,CAAC,EAAQ,EAAG,EAAS,IACtE,EAAM,GAAG,KAAK,YAAY,CAAM,IAAI,EAAe,CAAC,IAAK,EAAS,KAAK,aAAa,CAAI,CAAC,EAElF,QAAoC,CAAC,EAAQ,EAAS,IAC7D,EAAI,KAAK,YAAY,CAAM,EAAG,EAAS,KAAK,aAAa,CAAI,CAAC,EAEvD,SAAsC,CAAC,EAAQ,EAAS,IAC/D,EAAI,GAAG,KAAK,YAAY,CAAM,IAAI,EAAY,SAAS,OAAQ,EAAS,KAAK,aAAa,CAAI,CAAC,EAExF,cAAgD,MAAO,EAAQ,EAAI,EAAO,CAAC,IAAM,CACxF,IAAM,EAAK,EAAK,WAAa,EAAe,CAAE,WAAY,EAAK,UAAW,CAAC,EAAI,GAC/E,OAAO,EAAO,GAAG,KAAK,YAAY,CAAM,KAAK,EAAU,EAAQ,CAAE,IAAI,IAAM,KAAK,aAAa,CAAI,CAAC,GAG3F,WAA0C,CAAC,EAAQ,EAAG,EAAO,CAAC,IACrE,EACE,GAAG,KAAK,YAAY,CAAM,IAAI,EAAe,EAAK,WAAa,IAAK,EAAG,WAAY,EAAK,UAAW,EAAI,CAAC,IACxG,KAAK,aAAa,CAAI,CACxB,EAEF,WAAc,CAAC,EAAyB,CACtC,MAAO,GAAG,KAAK,aAAa,KAAK,SAAS,YAAc,GAAY,CAAM,IAGlE,IAAO,CAAC,EAAc,EAAwC,EAAuB,CAC7F,GAAI,KAAK,SAAS,aAAe,QAC/B,OAAO,EAAa,EAAM,GAAK,CAAC,EAAG,KAAK,aAAa,CAAI,CAAC,EAE5D,OAAO,EAAO,GAAG,IAAO,EAAe,CAAC,IAAK,KAAK,aAAa,CAAI,CAAC,EAG5D,YAAY,CAAC,EAAmD,CACxE,GAAI,CAAC,KAAK,SAAS,SAAW,CAAC,GAAM,QACnC,OAAO,EAET,MAAO,IAAK,EAAM,QAAS,IAAK,KAAK,SAAS,WAAY,GAAM,OAAQ,CAAE,EAE9E",
|
|
17
|
+
"debugId": "9E77C69A393BE19B64756E2164756E21",
|
|
18
18
|
"names": []
|
|
19
19
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
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 Query, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictKeys, type QueryUpsert, type QueryContext, type QueryContextOptions, 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 AbstractType, type UpdatePayload, type ReportedWrite } from '../type/index.js';
|
|
2
|
-
import { type SortDirection } from '../util/index.js';
|
|
2
|
+
import { type WriteScope, 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';
|
|
5
5
|
import { type QueryJoins, type QuerySortOptions } from './queryJoins.js';
|
|
@@ -574,28 +574,23 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
574
574
|
* {@link insert} reports them. What a found row takes is read before the insert fills `onInsert` columns, which must
|
|
575
575
|
* stay out of it, and written after the rows, in the order the statement reads its values.
|
|
576
576
|
*/
|
|
577
|
-
upsert<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[],
|
|
577
|
+
upsert<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[], returning?: readonly FieldKey<E>[]): readonly SelectTerm[];
|
|
578
578
|
/**
|
|
579
579
|
* What an upsert of rows shaped as `row` assigns a row it finds: the values its assignments bind once per
|
|
580
580
|
* statement beside its rows, and whether there are any, where none is `DO NOTHING`, which skips that row.
|
|
581
581
|
*/
|
|
582
|
-
upsertAssignments<E>(entity: AbstractType<E>, q: QueryUpsert<E>, row: E
|
|
582
|
+
upsertAssignments<E>(entity: AbstractType<E>, q: QueryUpsert<E>, row: E): {
|
|
583
583
|
readonly binds: number;
|
|
584
584
|
readonly assigns: boolean;
|
|
585
585
|
};
|
|
586
|
+
/** What a row an upsert finds takes, {@link conflictEntries}, under `q.$where`. */
|
|
587
|
+
protected conflictUpdate<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[]): ConflictUpdate;
|
|
586
588
|
/**
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
+
* The columns a row an upsert finds takes, read off the payload's first row before the insert fills it: `q.$update`
|
|
590
|
+
* where given, {@link foundRowAssigned}, with the `onUpdate` fills; by default, each payload column as the incoming
|
|
591
|
+
* row has it, and no fill of what it matched on. In a trigger, an update as written and the fills a trigger can write.
|
|
589
592
|
*/
|
|
590
|
-
protected
|
|
591
|
-
/** The columns a row an upsert finds takes, read off the payload before the insert fills it. */
|
|
592
|
-
protected conflictEntries<E>(entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[], update?: UpdatePayload<E>): [string, unknown][];
|
|
593
|
-
/**
|
|
594
|
-
* What a row an upsert of `row` finds takes, {@link foundRowAssigned}, with the `onUpdate` fills: by default, each
|
|
595
|
-
* payload column as the incoming row has it, and no fill of what it matched on. In a trigger, an update as written
|
|
596
|
-
* and the fills a trigger can write.
|
|
597
|
-
*/
|
|
598
|
-
private foundRowEntries;
|
|
593
|
+
protected conflictEntries<E>(meta: EntityMeta<E>, q: QueryUpsert<E>, payload: EntityData<E> | EntityData<E>[], scope?: WriteScope): [string, unknown][];
|
|
599
594
|
/**
|
|
600
595
|
* `entries` as a row an upsert finds takes them: its `SET` list, empty for none, and the condition it takes it
|
|
601
596
|
* under, `where` read off that row through the table's name, empty where it always does.
|
|
@@ -1484,8 +1484,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1484
1484
|
ctx.append(';');
|
|
1485
1485
|
return;
|
|
1486
1486
|
}
|
|
1487
|
-
const { q
|
|
1488
|
-
const assigned = this.
|
|
1487
|
+
const { q } = write;
|
|
1488
|
+
const assigned = this.conflictEntries(meta, q, write.row, 'trigger');
|
|
1489
1489
|
this.refuseAccumulating(meta, assigned, rows);
|
|
1490
1490
|
const found = this.foundRowUpdate(ctx, write.entity, assigned, q.$where);
|
|
1491
1491
|
this.appendTriggerUpsert(ctx, meta, q.$conflict, entries, found, rows);
|
|
@@ -1578,9 +1578,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1578
1578
|
* {@link insert} reports them. What a found row takes is read before the insert fills `onInsert` columns, which must
|
|
1579
1579
|
* stay out of it, and written after the rows, in the order the statement reads its values.
|
|
1580
1580
|
*/
|
|
1581
|
-
upsert(ctx, entity, q, payload,
|
|
1581
|
+
upsert(ctx, entity, q, payload, returning) {
|
|
1582
1582
|
const meta = getMeta(entity);
|
|
1583
|
-
const entries = this.conflictEntries(
|
|
1583
|
+
const entries = this.conflictEntries(meta, q, payload);
|
|
1584
1584
|
return this.reportedWrite(ctx, entity, returning, 'upsert', () => {
|
|
1585
1585
|
this.appendInsertValues(ctx, entity, payload);
|
|
1586
1586
|
ctx.append(this.onConflict(meta, q.$conflict, this.foundRowUpdate(ctx, entity, entries, q.$where)));
|
|
@@ -1590,36 +1590,30 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1590
1590
|
* What an upsert of rows shaped as `row` assigns a row it finds: the values its assignments bind once per
|
|
1591
1591
|
* statement beside its rows, and whether there are any, where none is `DO NOTHING`, which skips that row.
|
|
1592
1592
|
*/
|
|
1593
|
-
upsertAssignments(entity, q, row
|
|
1593
|
+
upsertAssignments(entity, q, row) {
|
|
1594
1594
|
const ctx = this.createContext();
|
|
1595
|
-
const { assignments } = this.conflictUpdate(ctx, entity, q, row
|
|
1595
|
+
const { assignments } = this.conflictUpdate(ctx, entity, q, row);
|
|
1596
1596
|
return { binds: ctx.values.length, assigns: assignments !== '' };
|
|
1597
1597
|
}
|
|
1598
|
-
/**
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
*/
|
|
1602
|
-
conflictUpdate(ctx, entity, q, payload, update) {
|
|
1603
|
-
return this.foundRowUpdate(ctx, entity, this.conflictEntries(entity, q, payload, update), q.$where);
|
|
1604
|
-
}
|
|
1605
|
-
/** The columns a row an upsert finds takes, read off the payload before the insert fills it. */
|
|
1606
|
-
conflictEntries(entity, q, payload, update) {
|
|
1607
|
-
return this.foundRowEntries(getMeta(entity), q.$conflict, Array.isArray(payload) ? payload[0] : payload, update);
|
|
1598
|
+
/** What a row an upsert finds takes, {@link conflictEntries}, under `q.$where`. */
|
|
1599
|
+
conflictUpdate(ctx, entity, q, payload) {
|
|
1600
|
+
return this.foundRowUpdate(ctx, entity, this.conflictEntries(getMeta(entity), q, payload), q.$where);
|
|
1608
1601
|
}
|
|
1609
1602
|
/**
|
|
1610
|
-
*
|
|
1611
|
-
*
|
|
1612
|
-
* and the fills a trigger can write.
|
|
1603
|
+
* The columns a row an upsert finds takes, read off the payload's first row before the insert fills it: `q.$update`
|
|
1604
|
+
* where given, {@link foundRowAssigned}, with the `onUpdate` fills; by default, each payload column as the incoming
|
|
1605
|
+
* row has it, and no fill of what it matched on. In a trigger, an update as written and the fills a trigger can write.
|
|
1613
1606
|
*/
|
|
1614
|
-
|
|
1615
|
-
const
|
|
1607
|
+
conflictEntries(meta, q, payload, scope = 'statement') {
|
|
1608
|
+
const row = Array.isArray(payload) ? payload[0] : payload;
|
|
1609
|
+
const assigned = foundRowAssigned(meta, q, row);
|
|
1616
1610
|
if (!assigned) {
|
|
1617
1611
|
return [];
|
|
1618
1612
|
}
|
|
1619
|
-
if (update) {
|
|
1613
|
+
if (q.$update) {
|
|
1620
1614
|
return scope === 'trigger' ? this.triggerUpdateEntries(meta, assigned) : this.updateEntries(meta, assigned);
|
|
1621
1615
|
}
|
|
1622
|
-
const matched = new Set([...meta.ids, ...getKeys(
|
|
1616
|
+
const matched = new Set([...meta.ids, ...getKeys(q.$conflict)]);
|
|
1623
1617
|
return this.updateEntries(meta, assigned, scope).flatMap(([key, value]) => matched.has(key) ? [] : [[key, Object.hasOwn(row, key) ? this.incoming(meta, key) : value]]);
|
|
1624
1618
|
}
|
|
1625
1619
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityMeta, FieldKey, QueryConflictKeys, QueryUpsert, QueryContext, QueryPager, TriggerRows, AbstractType
|
|
1
|
+
import type { EntityMeta, FieldKey, QueryConflictKeys, QueryUpsert, QueryContext, QueryPager, TriggerRows, AbstractType } from '../type/index.js';
|
|
2
2
|
import { AbstractSqlDialect, type ConflictUpdate, type SelectTerm } from './abstractSqlDialect.js';
|
|
3
3
|
/** What SQL Server and Oracle share: paging and upsert spelled as the standard does. */
|
|
4
4
|
export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
|
|
@@ -12,7 +12,7 @@ export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
|
|
|
12
12
|
* assignments bind their values before the rows, though they follow them in the SQL; this works only because
|
|
13
13
|
* SQL Server numbers each placeholder (`@p1`).
|
|
14
14
|
*/
|
|
15
|
-
upsert<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[],
|
|
15
|
+
upsert<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[], returning?: readonly FieldKey<E>[]): readonly SelectTerm[];
|
|
16
16
|
/** A trigger's upsert as a `MERGE` of the rows it was handed, `SELECT`ed off them as its source. */
|
|
17
17
|
protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, conflictKeys: QueryConflictKeys<E>, entries: readonly [string, unknown][], found: ConflictUpdate, rows?: TriggerRows): void;
|
|
18
18
|
/**
|
|
@@ -25,12 +25,12 @@ export class MergeSqlDialect extends AbstractSqlDialect {
|
|
|
25
25
|
* assignments bind their values before the rows, though they follow them in the SQL; this works only because
|
|
26
26
|
* SQL Server numbers each placeholder (`@p1`).
|
|
27
27
|
*/
|
|
28
|
-
upsert(ctx, entity, q, payload,
|
|
28
|
+
upsert(ctx, entity, q, payload, returning) {
|
|
29
29
|
const meta = getMeta(entity);
|
|
30
30
|
// Before the row source, which is what fills the payload's `onInsert` fields: a column that
|
|
31
31
|
// exists only there - the generated key, `createdAt` - must not join the update set, or a row
|
|
32
32
|
// that already existed has both rewritten.
|
|
33
|
-
const found = this.conflictUpdate(ctx, entity, q, payload
|
|
33
|
+
const found = this.conflictUpdate(ctx, entity, q, payload);
|
|
34
34
|
return this.reportedWrite(ctx, entity, returning, 'upsert', (afterTarget) => {
|
|
35
35
|
const shape = this.insertShape(entity, payload);
|
|
36
36
|
ctx.append(`MERGE INTO ${this.escapedTableName(meta)}${this.mergeTargetHint} USING (VALUES `);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { FieldKey, EntityMeta, InsertIdSource, Query, QueryConflictKeys, QueryContext, QueryOptions, QueryTextSearchOptions, QueryUpsert, QueryWhere, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, AbstractType,
|
|
1
|
+
import type { FieldKey, EntityMeta, InsertIdSource, Query, QueryConflictKeys, QueryContext, QueryOptions, QueryTextSearchOptions, QueryUpsert, QueryWhere, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, AbstractType, TransactionOptions } from '../type/index.js';
|
|
2
2
|
import { AbstractSqlDialect, type ConflictUpdate, type DerivedRelation, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
|
|
3
3
|
import { type JsonContainer, type JsonSlot } from './jsonSql.js';
|
|
4
4
|
/** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
|
|
@@ -30,7 +30,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
30
30
|
readonly sqlValues: SqlValues;
|
|
31
31
|
readonly insertIdSource: InsertIdSource;
|
|
32
32
|
/** `INSERT ... ON DUPLICATE KEY UPDATE`, its rows written before what a found row takes, as a `?` reads them. */
|
|
33
|
-
upsert<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[],
|
|
33
|
+
upsert<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryUpsert<E>, payload: E | E[], returning?: readonly FieldKey<E>[]): readonly SelectTerm[];
|
|
34
34
|
/**
|
|
35
35
|
* `ON DUPLICATE KEY UPDATE` takes no `WHERE`, so each assignment holds `where` itself, a `CASE WHEN`. MySQL assigns
|
|
36
36
|
* left to right, a later assignment reading a column as already set: the one column the condition reads is set
|
|
@@ -101,9 +101,9 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
101
101
|
// `innodb_autoinc_lock_mode` caveat on `buildUpdateResult` in `util/sql.util.ts`.
|
|
102
102
|
insertIdSource = 'firstId';
|
|
103
103
|
/** `INSERT ... ON DUPLICATE KEY UPDATE`, its rows written before what a found row takes, as a `?` reads them. */
|
|
104
|
-
upsert(ctx, entity, q, payload,
|
|
104
|
+
upsert(ctx, entity, q, payload, returning) {
|
|
105
105
|
const meta = getMeta(entity);
|
|
106
|
-
const entries = this.conflictEntries(
|
|
106
|
+
const entries = this.conflictEntries(meta, q, payload);
|
|
107
107
|
const insert = this.buildFragment(ctx, (fragment) => this.appendInsertValues(fragment, entity, payload));
|
|
108
108
|
const { assignments } = this.foundRowUpdate(ctx, entity, entries, q.$where);
|
|
109
109
|
const rows = Array.isArray(payload) ? payload.length : 1;
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,6 @@ export { filledKey, idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
|
10
10
|
export { withDeleted } from './util/filters.util.js';
|
|
11
11
|
export { sortOf } from './util/query.util.js';
|
|
12
12
|
export { DefaultLogger } from './util/logger.js';
|
|
13
|
-
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, tableOf, uuid, uuidv7 } from './util/sql.js';
|
|
14
|
-
export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
|
|
13
|
+
export { aliasOf, currentDate, currentTime, currentTimestamp, raw, refs, sql, tableOf, uuid, uuidv7, } from './util/sql.js';
|
|
14
|
+
export { deleteFrom, insertInto, refuse, type TriggerUpsert, updateTable, upsertInto } from './util/triggerWrite.js';
|
|
15
15
|
export { type QueryErrorKind, UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
|
package/dist/index.js
CHANGED
|
@@ -9,6 +9,6 @@ export { filledKey, idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
|
9
9
|
export { withDeleted } from './util/filters.util.js';
|
|
10
10
|
export { sortOf } from './util/query.util.js';
|
|
11
11
|
export { DefaultLogger } from './util/logger.js';
|
|
12
|
-
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, tableOf, uuid, uuidv7 } from './util/sql.js';
|
|
12
|
+
export { aliasOf, currentDate, currentTime, currentTimestamp, raw, refs, sql, tableOf, uuid, uuidv7, } from './util/sql.js';
|
|
13
13
|
export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
|
|
14
14
|
export { UqlError, UqlOptimisticLockError, UqlSecurityError, UqlUsageError, } from './util/uqlError.js';
|
|
@@ -49,7 +49,7 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
|
|
|
49
49
|
* Updating a found document `apart`, it writes only an inserted one.
|
|
50
50
|
*/
|
|
51
51
|
private upsertUpdate;
|
|
52
|
-
protected internalUpsertMany<E extends Document>(entity: Type<E>, q: QueryUpsert<E>, payload: E[]
|
|
52
|
+
protected internalUpsertMany<E extends Document>(entity: Type<E>, q: QueryUpsert<E>, payload: E[]): Promise<(UpsertedId<E> | undefined)[]>;
|
|
53
53
|
protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
|
|
54
54
|
get hasOpenTransaction(): boolean;
|
|
55
55
|
/** Every read and write goes through here, which makes it where a released querier is caught. */
|