uql-orm 0.90.0 → 0.91.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +3 -3
- package/dist/entity/decorator/members.d.ts +3 -3
- package/dist/entity/decorator/members.js +1 -1
- package/dist/migrate/codegen/entityCodeGenerator.d.ts +15 -4
- package/dist/migrate/codegen/entityCodeGenerator.js +78 -47
- package/dist/migrate/codegen/entityTypes.js +22 -5
- package/dist/migrate/codegen/fieldOptionsSource.d.ts +4 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +20 -8
- package/dist/type/entity.d.ts +29 -11
- package/dist/type/queryRaw.d.ts +5 -3
- package/dist/type/queryRaw.js +2 -0
- package/dist/type/utility.d.ts +9 -3
- package/dist/util/dialect.util.d.ts +2 -10
- package/package.json +5 -5
- package/skills/uql-orm/SKILL.md +4 -3
package/README.md
CHANGED
|
@@ -55,10 +55,10 @@ import { Entity, Field, Id, ManyToOne, OneToMany } from 'uql-orm';
|
|
|
55
55
|
@Entity()
|
|
56
56
|
export class User {
|
|
57
57
|
@Id({ type: Number })
|
|
58
|
-
id
|
|
58
|
+
id!: number;
|
|
59
59
|
|
|
60
|
-
@Field({ type: String, unique: true })
|
|
61
|
-
email
|
|
60
|
+
@Field({ type: String, unique: true, nullable: false })
|
|
61
|
+
email!: string;
|
|
62
62
|
|
|
63
63
|
@OneToMany({ entity: () => Post, mappedBy: (post) => post.author })
|
|
64
64
|
posts?: Post[];
|
|
@@ -67,10 +67,10 @@ export class User {
|
|
|
67
67
|
@Entity()
|
|
68
68
|
export class Post {
|
|
69
69
|
@Id({ type: Number })
|
|
70
|
-
id
|
|
70
|
+
id!: number;
|
|
71
71
|
|
|
72
|
-
@Field({ type: String })
|
|
73
|
-
title
|
|
72
|
+
@Field({ type: String, nullable: false })
|
|
73
|
+
title!: string;
|
|
74
74
|
|
|
75
75
|
@Field({ type: Number })
|
|
76
76
|
likes?: number | null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var c=[];function d(e){for(let r of c)r(e)}function
|
|
1
|
+
var c=[];function d(e){for(let r of c)r(e)}function L(e){c.push(e);let r=c.length-1;return()=>{c.splice(r,1)}}var b=["$select","$populate","$exclude","$where","$sort"],f=["$count"],O=["$skip","$limit"],R=["$candidates"],T=["$distinct"],v=["$lock",...f,...R];var C=Symbol("rawValue"),N=Symbol("rawAlias"),D=Symbol("rawText"),I=Symbol("rawValueType");class k extends Error{}class i extends k{name="UqlUsageError";kind="usage";status=400}function l(e){return e?Object.keys(e):[]}function U(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}var _=["hardDelete","count"],re=new Set([...b,...f,...O,...R,...T,..._]);function u(e){if(!e)return"";let r=new URLSearchParams;for(let n of l(e)){let o=e[n];if(o===void 0)continue;r.append(n,typeof o==="object"&&o!==null?a(o):String(o))}let t=r.toString();return t?`?${t}`:""}function a(e){return JSON.stringify(e,(r,t)=>{if(typeof t!=="object"||t===null)return t;if(C 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 K extends Error{status;constructor(e,r){super(e);this.status=r;this.name="RequestError"}}function x(e,r){return y(e,{method:"get"},r)}function h(e,r,t){return y(e,{method:"post",body:a(r)},t)}function Q(e,r,t){return y(e,{method:"patch",body:a(r)},t)}function g(e,r,t){return y(e,{method:"put",body:a(r)},t)}function m(e,r){return y(e,{method:"delete"},r)}function q(e,r,t){return y(e,{method:"QUERY",body:a(r)},t)}function y(e,r,t){if(d({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((o)=>{if(n.status>=200&&n.status<300)return d({phase:"success",opts:t}),o;let P=o,E={message:P?.error?.message??n.statusText,code:P?.error?.code??n.status};throw d({phase:"error",error:E,opts:t}),new K(E.message,E.code)})).finally(()=>{d({phase:"complete",opts:t})})}function V(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 s={findMany:{method:"GET",path:""},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:""}},A=l(s),de=new Map(A.filter((e)=>s[e].method==="GET"&&s[e].path!=="/:id").map((e)=>[s[e].path,e]));function F(e){return V(e.name)}function w(e,r){if(!U(r))throw new i(`'${e.name}' was addressed by an id object, which the HTTP route cannot carry.`);return String(r)}class S{basePath;defaults;constructor(e,r={}){this.basePath=e;this.defaults=r}async findOneById(e,r,t,n){let o=this.getBasePath(e),p=u(t);return x(`${o}/${w(e,r)}${p}`,this.buildOptions(n))}findOne(e,r,t){return this.read(`${this.getBasePath(e)}${s.findOne.path}`,r,t)}findMany(e,r,t){let n={...r};if(t?.count)n.count=!0;return this.read(this.getBasePath(e),n,t)}async findManyAndCount(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}}count(e,r,t){return this.read(`${this.getBasePath(e)}${s.count.path}`,r,t)}async exists(e,r,t){let n=await this.count(e,{...r,$limit:1},t);return{...n,data:n.data>0}}insertOne(e,r,t){let n=this.getBasePath(e);return h(n,r,this.buildOptions(t))}insertMany(e,r,t){let n=this.getBasePath(e);return h(`${n}${s.insertMany.path}`,r,this.buildOptions(t))}async updateOneById(e,r,t,n){let o=this.getBasePath(e);return Q(`${o}/${w(e,r)}`,t,this.buildOptions(n))}updateMany(e,r,t,n){let o=this.getBasePath(e),p=u(r);return Q(`${o}${p}`,t,this.buildOptions(n))}saveOne(e,r,t){let n=this.getBasePath(e);return g(n,r,this.buildOptions(t))}saveMany(e,r,t){let n=this.getBasePath(e);return g(`${n}${s.saveMany.path}`,r,this.buildOptions(t))}async deleteOneById(e,r,t={}){let n=this.getBasePath(e),o=t.hardDelete?u({hardDelete:t.hardDelete}):"";return m(`${n}/${w(e,r)}${o}`,this.buildOptions(t))}deleteMany(e,r,t={}){let n=this.getBasePath(e),o=u(t.hardDelete?{...r,hardDelete:t.hardDelete}:r);return m(`${n}${o}`,this.buildOptions(t))}getBasePath(e){return`${this.basePath}/${(this.defaults.entityPath??F)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return q(e,r??{},this.buildOptions(t));return x(`${e}${u(r)}`,this.buildOptions(t))}buildOptions(e){if(!this.defaults.headers&&!e?.headers)return e;return{...e,headers:{...this.defaults.headers,...e?.headers}}}}var j={getQuerier:()=>new S("/api")};function Qe(e){j=e}function W(){return j}function ge(){return W().getQuerier()}export{S as HttpQuerier,K as RequestError,x as get,ge as getQuerier,W as getQuerierPool,d as notify,L as on,Q as patch,h as post,g as put,q as query,m as remove,Qe as setQuerierPool};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=E62137AC3E6D9C8264756E2164756E21
|
|
4
4
|
//# sourceMappingURL=uql-browser.min.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors: 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.push(cb);\n const index = subscriptors.length - 1;\n return (): void => {\n subscriptors.splice(index, 1);\n };\n}\n",
|
|
6
6
|
"import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QueryRaw } from './queryRaw.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it. `F` is also how a projection passes its captured key set.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `raw()`\n * (e.g. ``[raw`*`, raw`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Raw = QueryRaw> = QuerySelect<E> | readonly Raw[];\n\n/**\n * Fields to exclude from the query result - `{ name: true }` blacklists fields.\n * Mutually exclusive with positive field selections in `$select`.\n */\nexport type QueryExclude<E> = QuerySelect<E>;\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Raw = QueryRaw, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Raw>;\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, Raw = QueryRaw, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Raw>;\n};\n\n/**\n * query conflict paths - subset of field keys used to detect upsert conflicts.\n */\nexport type QueryConflictPaths<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Raw = QueryRaw> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Raw>\n : QueryUnique<RelationTarget<V>, Raw> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` / `@Filter` / `defineFilter`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Unqualified, each engine has its own answer - Postgres and CockroachDB sort nulls last on `asc`, the\n * rest sort them first - so a placement is the only portable one. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A row with the value a `$sort` projects under the name its `$project` gives - a vector's distance, or a\n * `$text` relevance - which is not inferred: `(await querier.findMany(Post, q)) as WithProjection<Post, 'score'>[]`.\n */\nexport type WithProjection<E, K extends string> = E & Record<K, number>;\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Raw = QueryRaw> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Raw>;\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, Raw = QueryRaw> = QueryFilter<E, Raw> & 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, Raw = QueryRaw> = QueryPage<E, Raw> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Raw = QueryRaw> = {\n /**\n * field selection - `{ name: true }` whitelists fields, or raw SQL projections\n * (``[raw`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * Mutually exclusive with `$exclude`.\n */\n $select?: QuerySelectValue<E, Raw>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Raw>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Raw>;\n\n /**\n * field exclusion - `{ name: true }` blacklists fields. Mutually exclusive with positive `$select`.\n * Keys a relation is assembled from (a joined row's primary key, a to-many's foreign key) are kept\n * regardless, since subtracting them would leave the relation unfilled.\n */\n $exclude?: QueryExclude<E>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Raw>;\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 `raw` 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 * `Query`'s clauses grouped by the shape of their value, for the wire parser and the relation query\n * check alike; `satisfies` keeps them in step with `Query`.\n */\nexport const QUERY_OBJECT_CLAUSES = [\n '$select',\n '$populate',\n '$exclude',\n '$where',\n '$sort',\n] as const satisfies readonly (keyof Query<unknown>)[];\n\n/**\n * Object clauses only the statement itself takes: a populated relation's rows keep their declared type,\n * so a `$count` inside one would have no `_count` to land in.\n */\nexport const QUERY_ROOT_OBJECT_CLAUSES = ['$count'] as const satisfies readonly (keyof Query<unknown>)[];\n\nexport const QUERY_NUMBER_CLAUSES = ['$skip', '$limit'] as const satisfies readonly (keyof Query<unknown>)[];\n\n/**\n * Number clauses only the statement itself takes - the numeric mirror of {@link QUERY_ROOT_OBJECT_CLAUSES}.\n * `$candidates` tunes the index behind a vector search, and a vector search only ever ranks the rows\n * the statement returns, so a relation's own query has nothing to tune.\n */\nexport const QUERY_ROOT_NUMBER_CLAUSES = ['$candidates'] as const satisfies readonly (keyof Query<unknown>)[];\n\nexport const QUERY_BOOLEAN_CLAUSES = ['$distinct'] as const satisfies readonly (keyof Query<unknown>)[];\n\n/** The clauses that describe the statement, which a populated relation's own query refuses by name. */\nexport const QUERY_STATEMENT_CLAUSES = [\n '$lock',\n ...QUERY_ROOT_OBJECT_CLAUSES,\n ...QUERY_ROOT_NUMBER_CLAUSES,\n] as const satisfies readonly (keyof Query<unknown>)[];\n\ntype RelationClause = (\n | typeof QUERY_OBJECT_CLAUSES\n | typeof QUERY_NUMBER_CLAUSES\n | typeof QUERY_BOOLEAN_CLAUSES\n)[number];\n\n/**\n * A populated relation's own query: the clause groups its runtime check accepts, so the two cannot\n * drift, and a clause added to {@link Query} stays off it until it joins one of them.\n */\nexport type RelationQuery<E = object, Raw = QueryRaw> = Pick<Query<E, Raw>, RelationClause> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Raw = QueryRaw> = Except<Query<E, Raw>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Raw = QueryRaw> = Pick<QueryOne<E, Raw>, '$select' | '$exclude' | '$populate' | '$where'>;\n\n/**\n * The clauses that shape a row, captured as key sets rather than maps: a naked type parameter skips\n * excess-property checks, while a key set fails its own constraint on a typo.\n * @internal\n */\ntype QueryProjection<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E>,\n Raw = QueryRaw,\n> = {\n $select?: QuerySelect<E, S, V> | readonly Raw[];\n $exclude?: QuerySelect<E, X, V>;\n $populate?: QueryPopulate<E, Raw, P>;\n // Narrowing the captured names to the to-many ones leaves a to-one relation no key here at all,\n // so counting one is an excess property rather than a value to check.\n $count?: QueryCount<E, Raw, C & ToManyRelationKey<E>>;\n};\n\n/**\n * A {@link Query} whose projection is captured, so {@link QueryFindResult} can shape the row.\n */\nexport type QueryProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n Raw = QueryRaw,\n> = Query<E, Raw> & QueryProjection<E, S, V, X, P, C, Raw>;\n\n/**\n * A {@link QueryOne} whose projection is captured, so {@link QueryFindResult} can shape the row.\n */\nexport type QueryOneProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n Raw = QueryRaw,\n> = QueryOne<E, Raw> & QueryProjection<E, S, V, X, P, C, Raw>;\n\n/**\n * The keys a query comes back with, as the runtime projects them: a positive `$select`'s, or every\n * field minus what `$select` or `$exclude` subtracts, plus the populated relations.\n * @internal\n */\ntype ProjectedKeys<E, S, V, X, P> =\n | ([V] extends [false | 0] ? Exclude<FieldKey<E>, S> : [S] extends [never] ? Exclude<FieldKey<E>, X> : S)\n | P;\n\n/**\n * Whether every entry of the captured map says the same thing: all selected, or all subtracted.\n * @internal\n */\ntype IsUniform<V> = [V] extends [true | 1] ? true : [V] extends [false | 0] ? true : false;\n\n/**\n * A find's row: the entity narrowed to what the query projected and populated, so reading anything\n * else does not compile. The entity itself where the projection is raw, absent or not uniform.\n * @example `QueryFindResult<User, 'id' | 'name'>`\n */\nexport type QueryFindResult<\n E,\n S extends FieldKey<E> = never,\n // A whitelist by default, so the hand-written form reads `QueryFindResult<User, 'id' | 'name'>`.\n V = true,\n X extends FieldKey<E> = never,\n P extends RelationKey<E> = never,\n C extends RelationKey<E> = never,\n> = QueryProjectedRow<E, S, V, X, P, C> & CountedRelations<C>;\n\n/**\n * The `_count` a query asked for, or an inert intersection member when it asked for none - so a read\n * without `$count` keeps exactly the row type it had.\n */\ntype CountedRelations<C extends PropertyKey> = [C] extends [never]\n ? unknown\n : { [K in typeof COUNT_RESULT_KEY]: { [R in C]: number } };\n\n/** @internal */\ntype QueryProjectedRow<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E>,\n> = [S | X] extends [never]\n ? E\n : IsUniform<V> extends true\n ? [PopulatedToMany<E, P>] extends [never]\n ? // `Pick`, not a key remap: an entity keyed by an index signature - a content type defined at\n // runtime - has `string` for its keys, and a remap keeps no literal one, so every projection\n // over one came back as `{}`.\n Pick<E, ProjectedKeys<E, S, V, X, P> & keyof E>\n : // A populated to-many is always a list, empty where the parent has no children, so it maps\n // and counts without a guard. Only that promotion needs a second member, and only a query\n // that populates one pays for it; every other key keeps the modifier the entity declared,\n // a to-one relation included, since a join that finds no row leaves it absent.\n Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E> & {\n [K in PopulatedToMany<E, P>]-?: NonNullable<E[K]>;\n }\n : E;\n\n/** The to-many relations a query populated, which come back as lists rather than as optional ones. */\ntype PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;\n\n/** What upserting one row reports. `created` is only knowable for a single statement, so a batch has none. */\nexport type QueryUpsertOneResult<E> = {\n readonly id?: WrittenId<E>;\n readonly changes?: number;\n /** Whether the record was created (`true`) or updated (`false`), where the dialect can tell. */\n readonly created?: boolean;\n};\n\n/**\n * What upserting many rows reports. `ids` is payload-aligned like an insert's, so it zips with the\n * rows that were passed, and carries a composite key as the map naming it.\n */\nexport type QueryUpsertManyResult<E> = {\n readonly ids: (WrittenId<E> | undefined)[];\n readonly changes?: number;\n};\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 * first inserted ID.\n */\n firstId?: PrimaryKey;\n /**\n * whether the record was created (`true`) or updated (`false`).\n * `undefined` when the dialect cannot determine this (e.g. SQLite).\n */\n created?: boolean;\n};\n",
|
|
7
|
-
"import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Type } from './utility.js';\n\n/** What a `raw` callback receives. See {@link QueryRawFn}. */\nexport type QueryRawRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: Type<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QueryRawRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QueryRawFnOptions = Partial<QueryRawRenderOptions>;\n\n/**\n * A `raw` 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 QueryRawFn = (opts: QueryRawRenderOptions) => unknown;\n\nexport const RAW_VALUE: unique symbol = Symbol('rawValue');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const RAW_TEXT: unique symbol = Symbol('rawText');\n\nexport class QueryRaw {\n readonly [RAW_VALUE]: QueryRawFn;\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 [RAW_TEXT]?: string;\n\n constructor(value: QueryRawFn, alias?: string, text?: string) {\n this[RAW_VALUE] = value;\n this[RAW_ALIAS] = alias;\n this[RAW_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QueryRaw {\n return new QueryRaw(this[RAW_VALUE], alias, this[RAW_TEXT]);\n }\n\n /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */\n render(opts: QueryRawRenderOptions): void {\n const emitted = this[RAW_VALUE](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `raw`, 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 RawFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QueryRaw {\n declare readonly
|
|
7
|
+
"import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Type } from './utility.js';\n\n/** What a `raw` callback receives. See {@link QueryRawFn}. */\nexport type QueryRawRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: Type<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QueryRawRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QueryRawFnOptions = Partial<QueryRawRenderOptions>;\n\n/**\n * A `raw` 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 QueryRawFn = (opts: QueryRawRenderOptions) => unknown;\n\nexport const RAW_VALUE: unique symbol = Symbol('rawValue');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const RAW_TEXT: unique symbol = Symbol('rawText');\n/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */\nexport const RAW_VALUE_TYPE: unique symbol = Symbol('rawValueType');\n\nexport class QueryRaw {\n readonly [RAW_VALUE]: QueryRawFn;\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 [RAW_TEXT]?: string;\n\n constructor(value: QueryRawFn, alias?: string, text?: string) {\n this[RAW_VALUE] = value;\n this[RAW_ALIAS] = alias;\n this[RAW_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QueryRaw {\n return new QueryRaw(this[RAW_VALUE], alias, this[RAW_TEXT]);\n }\n\n /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */\n render(opts: QueryRawRenderOptions): void {\n const emitted = this[RAW_VALUE](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `raw`, 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 RawFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QueryRaw {\n declare readonly [RAW_VALUE_TYPE]?: V;\n\n constructor(\n readonly key: K,\n value: QueryRawFn,\n ) {\n super(value);\n }\n}\n\n/**\n * SQL where a value of type `V` goes: bare SQL, whose type is its author's to know, or a ref to a column\n * holding one, nullability aside. `Raw` is what the transport carries, so the wire's `never` stays one.\n */\nexport type RawFor<Raw, V> = Raw & { readonly [RAW_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 and `Storable` whether a trigger could keep it, both carried in phantom\n * fields so the aggregate a field declares decides the property's type and refuses `stored: true` on\n * one no delta can maintain.\n */\nexport class RelationAggregate<V = unknown, Storable extends boolean = boolean> extends QueryRaw {\n declare readonly [RAW_VALUE_TYPE]?: V;\n declare private readonly __storable: Storable;\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: QueryRawFn,\n ) {\n super(value);\n }\n}\n\n/**\n * A write `insertInto`, `updateTable` or `deleteFrom` renders, or several joined in one `raw`. It reads a\n * set-based trigger's rows through {@link QueryRawRenderOptions.rows}, which is how `of` and `where` narrow\n * them there; SQL of its own reads `inserted` and `deleted` whole.\n */\nexport class TriggerWriteRaw extends QueryRaw {}\n",
|
|
8
8
|
"/**\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 * @deprecated since 0.77.1 - use {@link UqlUsageError}, which every misuse throws, lock or not. The\n * same class under both names, so an existing `instanceof` keeps working.\n */\nexport const UqlLockUsageError = UqlUsageError;\nexport type UqlLockUsageError = UqlUsageError;\n\n/**\n * Thrown when an update's `@Field({ version })` no longer matches the row: another writer moved it on,\n * or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`\n * where there is no row left.\n */\nexport class UqlOptimisticLockError extends UqlError {\n override name = 'UqlOptimisticLockError';\n readonly kind = 'optimisticLock';\n readonly status = 409;\n\n constructor(\n message: string,\n readonly expected: unknown,\n readonly actual: unknown,\n ) {\n super(message);\n }\n}\n",
|
|
9
9
|
"import type { EntityMeta } from '../type/index.js';\nimport { UqlUsageError } from './uqlError.js';\n\nexport function throwPendingTransaction(): never {\n throw new UqlUsageError('pending transaction');\n}\n\nexport function throwNoPendingTransaction(): never {\n throw new UqlUsageError('not a pending transaction');\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/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n",
|
|
10
10
|
"import type { QueryOptions, WireQuery } from '../type/index.js';\n// the clause lists themselves, not the barrel: this module is in the browser bundle's graph\nimport {\n QUERY_BOOLEAN_CLAUSES,\n QUERY_NUMBER_CLAUSES,\n QUERY_OBJECT_CLAUSES,\n QUERY_ROOT_NUMBER_CLAUSES,\n QUERY_ROOT_OBJECT_CLAUSES,\n} from '../type/query.js';\n// the brand alone, not the class: importing `QueryRaw` for an `instanceof` kept it, and `ColumnRef`\n// with it, in the browser bundle, which is on a size budget\nimport { RAW_VALUE } from '../type/queryRaw.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/**\n * Keys accepted from the wire - query structure ({@link Query}) plus the {@link WIRE_FLAGS}. Anything else\n * (e.g. `filters`, `context`, `$entity`) is dropped so a remote client can't bypass a security filter or\n * inject ambient context - those are server-only. The `satisfies` ties\n * every entry to a real query/option key, so a typo or a renamed option fails to compile.\n */\nconst ALLOWED_QUERY_KEYS = new Set<string>([\n ...QUERY_OBJECT_CLAUSES,\n ...QUERY_ROOT_OBJECT_CLAUSES,\n ...QUERY_NUMBER_CLAUSES,\n ...QUERY_ROOT_NUMBER_CLAUSES,\n ...QUERY_BOOLEAN_CLAUSES,\n ...WIRE_FLAGS,\n] satisfies (keyof WireQuery<unknown> | (typeof WIRE_FLAGS)[number])[]);\n\n/**\n * Keys that mean something locally but that this transport can never honor, so they are rejected\n * rather than dropped like the rest. Each request runs on its own auto-committing connection, so a\n * row lock taken here is released before the response is written: honoring `$lock` is impossible,\n * and ignoring it would hand the caller a read they believe is serialized and is not.\n */\nconst REJECTED_QUERY_KEYS = new Set<string>(['$lock'] satisfies (keyof WireQuery<unknown>)[]);\n\n/**\n * 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 {@link ALLOWED_QUERY_KEYS} are honored.\n */\nexport function parseQueryParams<E = unknown>(params: unknown = {}): WireQuery<E> & WireFlags {\n if (!isRecord(params)) {\n throw new UqlUsageError('the query must be a JSON object');\n }\n const query: Record<string, unknown> = {};\n for (const key of getKeys(params)) {\n if (REJECTED_QUERY_KEYS.has(key)) {\n throw new UqlUsageError(`'${key}' is not supported over HTTP`);\n }\n if (ALLOWED_QUERY_KEYS.has(key)) {\n query[key] = params[key];\n }\n }\n\n for (const key of [...QUERY_OBJECT_CLAUSES, ...QUERY_ROOT_OBJECT_CLAUSES]) {\n const value = query[key];\n if (typeof value === 'string') {\n try {\n query[key] = JSON.parse(value);\n } catch {\n throw new UqlUsageError(`invalid JSON in '${key}'`);\n }\n }\n }\n\n query['$where'] ??= {};\n if (!isWhereMap(query['$where'])) {\n throw new UqlUsageError(\"'$where' must be a JSON object\");\n }\n\n // A query string carries every value as text, so what decodes a clause is the shape its group\n // declares. `'false'` is the reason the boolean pass exists rather than the raw value being taken:\n // it is a non-empty string, so a `$distinct=false` would otherwise read as asking for one.\n for (const key of [...QUERY_NUMBER_CLAUSES, ...QUERY_ROOT_NUMBER_CLAUSES]) {\n if (query[key] !== undefined) {\n query[key] = Number(query[key]);\n }\n }\n for (const key of [...QUERY_BOOLEAN_CLAUSES, ...WIRE_FLAGS]) {\n if (query[key] !== undefined) {\n query[key] = query[key] === true || query[key] === 'true';\n }\n }\n\n return query;\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 `raw` 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 (RAW_VALUE 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",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"import { CRUD_ROUTES, entityPath, type HttpMethod } from '../../http/contract.js';\nimport { stringifyQuery } from '../../http/query.js';\nimport type {\n EntityWrite,\n EntityId,\n FieldKey,\n QueryFilter,\n QueryFindResult,\n QueryOneProjected,\n QueryOptions,\n QueryPage,\n QueryProjected,\n QuerySearch,\n RelationKey,\n RequestCountedSuccessResponse,\n RequestSuccessResponse,\n Type,\n UpdateWrite,\n WireQuery,\n WrittenId,\n} 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, count). 'QUERY' (RFC 10008) sends the\n * JSON query in the request body, avoiding URL-length limits for large queries; requires\n * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.\n */\n readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;\n /**\n * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same\n * option the server handler takes, so one map serves both. State it where the default cannot: a\n * build that minifies class names renames every route.\n */\n readonly entityPath?: (entity: Type<unknown>) => string;\n};\n\n/** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */\nfunction idSegment<E>(entity: Type<E>, id: EntityId<E>): string {\n if (!isScalarId(id)) {\n throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);\n }\n return String(id);\n}\n\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n async findOneById<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n id: EntityId<E>,\n q?: QueryOneProjected<E, S, V, X, P, C, never>,\n opts?: RequestOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>> {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(q);\n return get<QueryFindResult<E, S, V, X, P, C> | undefined>(\n `${basePath}/${idSegment(entity, id)}${qs}`,\n this.buildOptions(opts),\n );\n }\n\n findOne<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryOneProjected<E, S, V, X, P, C, never>,\n opts?: RequestOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>> {\n return this.read<QueryFindResult<E, S, V, X, P, C> | undefined>(\n `${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`,\n q,\n opts,\n );\n }\n\n findMany<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryProjected<E, S, V, X, P, C, never>,\n opts?: RequestFindOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>> {\n const data: WireQuery<E> & { count?: boolean } = { ...q };\n if (opts?.count) {\n data.count = true;\n }\n return this.read<QueryFindResult<E, S, V, X, P, C>[]>(this.getBasePath(entity), data, opts);\n }\n\n async findManyAndCount<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryProjected<E, S, V, X, P, C, never>,\n opts?: RequestFindOptions,\n ): Promise<RequestCountedSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>> {\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 count<E extends object>(entity: Type<E>, q?: QueryPage<E, never>, opts?: RequestOptions) {\n return this.read<number>(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);\n }\n\n /** The `count` route capped at one row, so existence needs no endpoint of its own. */\n async exists<E extends object>(entity: Type<E>, q?: QueryFilter<E, never>, opts?: RequestOptions) {\n const res = await this.count(entity, { ...q, $limit: 1 }, opts);\n return { ...res, data: res.data > 0 };\n }\n\n insertOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return post<WrittenId<E> | undefined>(basePath, payload, this.buildOptions(opts));\n }\n\n insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return post<(WrittenId<E> | undefined)[]>(\n `${basePath}${CRUD_ROUTES.insertMany.path}`,\n payload,\n this.buildOptions(opts),\n );\n }\n\n async updateOneById<E extends object>(\n entity: Type<E>,\n id: EntityId<E>,\n payload: UpdateWrite<E, never>,\n opts?: RequestOptions,\n ) {\n const basePath = this.getBasePath(entity);\n return patch<number>(`${basePath}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));\n }\n\n updateMany<E extends object>(\n entity: Type<E>,\n q: QuerySearch<E, never>,\n payload: UpdateWrite<E, never>,\n opts?: RequestOptions,\n ) {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(q);\n return patch<number>(`${basePath}${qs}`, payload, this.buildOptions(opts));\n }\n\n saveOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return put<WrittenId<E> | undefined>(basePath, payload, this.buildOptions(opts));\n }\n\n saveMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return put<(WrittenId<E> | undefined)[]>(\n `${basePath}${CRUD_ROUTES.saveMany.path}`,\n payload,\n this.buildOptions(opts),\n );\n }\n\n async deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts: QueryOptions & RequestOptions = {}) {\n const basePath = this.getBasePath(entity);\n const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';\n return remove<number>(`${basePath}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));\n }\n\n deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E, never>, opts: QueryOptions & RequestOptions = {}) {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q);\n return remove<number>(`${basePath}${qs}`, this.buildOptions(opts));\n }\n\n getBasePath<E>(entity: Type<E>) {\n return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;\n }\n\n protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions) {\n if (this.defaults.readMethod === 'QUERY') {\n return httpQuery<T>(path, q ?? {}, this.buildOptions(opts));\n }\n return get<T>(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));\n }\n\n protected buildOptions(opts?: RequestOptions): RequestOptions | undefined {\n if (!this.defaults.headers && !opts?.headers) {\n return opts;\n }\n return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };\n }\n}\n",
|
|
15
15
|
"import { HttpQuerier } from './querier/httpQuerier.js';\nimport type { ClientQuerier, ClientQuerierPool } from './type/index.js';\n\nlet defaultPool: ClientQuerierPool = {\n getQuerier: () => new HttpQuerier('/api'),\n};\n\nexport function setQuerierPool<T extends ClientQuerierPool>(pool: T) {\n defaultPool = pool;\n}\n\nexport function getQuerierPool(): ClientQuerierPool {\n return defaultPool;\n}\n\nexport function getQuerier(): ClientQuerier {\n return getQuerierPool().getQuerier();\n}\n"
|
|
16
16
|
],
|
|
17
|
-
"mappings": "AAEA,IAAM,EAAkC,CAAC,EAElC,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAClD,EAAa,KAAK,CAAE,EACpB,IAAM,EAAQ,EAAa,OAAS,EACpC,MAAO,IAAY,CACjB,EAAa,OAAO,EAAO,CAAC,GC6UzB,IAAM,EAAuB,CAClC,UACA,YACA,WACA,SACA,OACF,EAMa,EAA4B,CAAC,QAAQ,EAErC,EAAuB,CAAC,QAAS,QAAQ,EAOzC,EAA4B,CAAC,aAAa,EAE1C,EAAwB,CAAC,WAAW,EAGpC,EAA0B,CACrC,QACA,GAAG,EACH,GAAG,CACL,ECrVO,IAAM,EAA2B,OAAO,UAAU,EAC5C,EAA2B,OAAO,UAAU,EAC5C,EAA0B,OAAO,SAAS,
|
|
18
|
-
"debugId": "
|
|
17
|
+
"mappings": "AAEA,IAAM,EAAkC,CAAC,EAElC,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
|
18
|
+
"debugId": "E62137AC3E6D9C8264756E2164756E21",
|
|
19
19
|
"names": []
|
|
20
20
|
}
|
|
@@ -46,8 +46,8 @@ type EnumValue<Members, Declared> = Declared extends Members ? {
|
|
|
46
46
|
} : Members;
|
|
47
47
|
/**
|
|
48
48
|
* Declares a persisted field, its `type` checked against the property's.
|
|
49
|
-
* @example `@Field({ type: String }) name
|
|
50
|
-
* @example `@Field({ references: () => User }) userId?: string;`
|
|
49
|
+
* @example `@Field({ type: String, nullable: false }) name!: string;`
|
|
50
|
+
* @example `@Field({ references: () => User }) userId?: string | null;`
|
|
51
51
|
*/
|
|
52
52
|
export declare function Field<This, O extends FieldOptions<DeclaredValue<O>, This> & ({
|
|
53
53
|
type: FieldType;
|
|
@@ -96,7 +96,7 @@ type VersionIsBranded<O, This> = O extends {
|
|
|
96
96
|
type IdDecorator<V> = <This>(value: undefined, context: ClassFieldDecoratorContext<This, V> & KeyIsNamed<This>) => void;
|
|
97
97
|
/**
|
|
98
98
|
* Declares the primary key, checked like `@Field`; a key not named `id`, `_id` or `uuid` needs the `idKey` brand.
|
|
99
|
-
* @example `@Id({ type: 'uuid', onInsert: uuidv7 }) id
|
|
99
|
+
* @example `@Id({ type: 'uuid', onInsert: uuidv7 }) id!: string;`
|
|
100
100
|
*/
|
|
101
101
|
export declare function Id<O extends FieldOptions<DeclaredValue<O>> & {
|
|
102
102
|
type: FieldType;
|
|
@@ -7,7 +7,7 @@ export function Field(opts) {
|
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
9
|
* Declares the primary key, checked like `@Field`; a key not named `id`, `_id` or `uuid` needs the `idKey` brand.
|
|
10
|
-
* @example `@Id({ type: 'uuid', onInsert: uuidv7 }) id
|
|
10
|
+
* @example `@Id({ type: 'uuid', onInsert: uuidv7 }) id!: string;`
|
|
11
11
|
*/
|
|
12
12
|
export function Id(opts) {
|
|
13
13
|
return (_value, context) => {
|
|
@@ -63,13 +63,14 @@ export declare class EntityCodeGenerator {
|
|
|
63
63
|
*/
|
|
64
64
|
private buildFields;
|
|
65
65
|
/**
|
|
66
|
-
*
|
|
66
|
+
* The `idKey` brand naming the key, which the type level cannot see otherwise: needed unless the key is
|
|
67
|
+
* one column holding the conventional name the entity would be read by, the first of `_id`, `id`, `uuid`.
|
|
67
68
|
*/
|
|
68
|
-
private
|
|
69
|
+
private idKeyBrand;
|
|
69
70
|
/**
|
|
70
|
-
* Build
|
|
71
|
+
* Build a single field definition.
|
|
71
72
|
*/
|
|
72
|
-
private
|
|
73
|
+
private buildField;
|
|
73
74
|
/**
|
|
74
75
|
* Build Field decorator options.
|
|
75
76
|
*/
|
|
@@ -87,6 +88,16 @@ export declare class EntityCodeGenerator {
|
|
|
87
88
|
* Build outgoing relation (ManyToOne or OneToOne where this table has FK).
|
|
88
89
|
*/
|
|
89
90
|
private buildOutgoingRelation;
|
|
91
|
+
/**
|
|
92
|
+
* The property of the side holding the foreign key: its column's name less an `_id` or `Id` suffix
|
|
93
|
+
* (`author_id` is `author`), else the singular of the table it points at. The inverse's `mappedBy` names the same.
|
|
94
|
+
*/
|
|
95
|
+
private owningPropertyName;
|
|
96
|
+
/**
|
|
97
|
+
* The inverse side's property: the related table's name, prefixed with the owning property where that
|
|
98
|
+
* table points here more than once (`authorPosts`, `editorPosts`), so each gets a member of its own.
|
|
99
|
+
*/
|
|
100
|
+
private inversePropertyName;
|
|
90
101
|
/**
|
|
91
102
|
* The `references` callback of a to-one: its foreign key column where that is the target's whole primary
|
|
92
103
|
* key, column pairs otherwise, and nothing when the columns do not pair up.
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { canonicalToTypeScript } from '../../schema/canonicalType.js';
|
|
2
2
|
import { DEFAULT_FOREIGN_KEY_ACTION, } from '../../schema/types.js';
|
|
3
|
-
import { camelCase, lowerFirst, pascalCase, singularize } from '../../util/string.util.js';
|
|
4
|
-
import { buildFieldOptionsSource, fieldNeedsRaw } from './fieldOptionsSource.js';
|
|
3
|
+
import { camelCase, lowerFirst, pascalCase, singularize, upperFirst } from '../../util/string.util.js';
|
|
4
|
+
import { buildFieldOptionsSource, enumMembersSource, fieldNeedsRaw } from './fieldOptionsSource.js';
|
|
5
5
|
import { buildIndexDecoratorSource, indexNeedsRaw, isPlainFieldIndex } from './indexDecoratorSource.js';
|
|
6
|
-
import { memberSource } from './sourceLiteral.js';
|
|
6
|
+
import { memberSource, quoted } from './sourceLiteral.js';
|
|
7
7
|
/** The decorator on the other side of a relation. */
|
|
8
8
|
const INVERSE_RELATION = {
|
|
9
9
|
OneToOne: 'OneToOne',
|
|
@@ -56,7 +56,8 @@ export class EntityCodeGenerator {
|
|
|
56
56
|
const fileName = `${className}.ts`;
|
|
57
57
|
const imports = this.buildImports(table);
|
|
58
58
|
const decorators = this.buildEntityDecorators(table);
|
|
59
|
-
const
|
|
59
|
+
const brand = this.idKeyBrand(table);
|
|
60
|
+
const fields = brand ? `${brand}\n\n${this.buildFields(table)}` : this.buildFields(table);
|
|
60
61
|
const relations = this.options.includeRelations ? this.buildRelations(table) : '';
|
|
61
62
|
const code = [imports, '', decorators, `export class ${className} {`, fields, relations, '}', ''].join('\n');
|
|
62
63
|
return {
|
|
@@ -72,6 +73,9 @@ export class EntityCodeGenerator {
|
|
|
72
73
|
buildImports(table) {
|
|
73
74
|
const uqlImports = new Set(['Entity', 'Field']);
|
|
74
75
|
const relatedImports = [];
|
|
76
|
+
if (this.idKeyBrand(table)) {
|
|
77
|
+
uqlImports.add('idKey');
|
|
78
|
+
}
|
|
75
79
|
for (const col of table.columns.values()) {
|
|
76
80
|
if (col.isPrimaryKey) {
|
|
77
81
|
uqlImports.add('Id');
|
|
@@ -79,14 +83,22 @@ export class EntityCodeGenerator {
|
|
|
79
83
|
if (fieldNeedsRaw(col)) {
|
|
80
84
|
uqlImports.add('raw');
|
|
81
85
|
}
|
|
86
|
+
if (col.type.category === 'json') {
|
|
87
|
+
uqlImports.add('type Json');
|
|
88
|
+
}
|
|
82
89
|
}
|
|
83
90
|
// Check for relation decorators
|
|
84
91
|
if (this.options.includeRelations) {
|
|
85
|
-
for (const rel of
|
|
92
|
+
for (const rel of table.outgoingRelations) {
|
|
86
93
|
uqlImports.add(rel.type);
|
|
94
|
+
}
|
|
95
|
+
for (const rel of table.incomingRelations) {
|
|
96
|
+
uqlImports.add(INVERSE_RELATION[rel.type]);
|
|
97
|
+
}
|
|
98
|
+
for (const rel of [...table.incomingRelations, ...table.outgoingRelations]) {
|
|
87
99
|
const relatedTable = rel.from.table === table ? rel.to.table : rel.from.table;
|
|
88
100
|
const relatedClassName = this.options.classNameTransformer(relatedTable.name);
|
|
89
|
-
if (!relatedImports.includes(relatedClassName)) {
|
|
101
|
+
if (relatedTable !== table && !relatedImports.includes(relatedClassName)) {
|
|
90
102
|
relatedImports.push(relatedClassName);
|
|
91
103
|
}
|
|
92
104
|
}
|
|
@@ -100,12 +112,10 @@ export class EntityCodeGenerator {
|
|
|
100
112
|
uqlImports.add('raw');
|
|
101
113
|
}
|
|
102
114
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
return code;
|
|
115
|
+
return [
|
|
116
|
+
`import { ${Array.from(uqlImports).sort().join(', ')} } from '${this.options.uqlImportPath}';`,
|
|
117
|
+
...relatedImports.sort().map((className) => `import { ${className} } from './${className}.js';`),
|
|
118
|
+
].join('\n');
|
|
109
119
|
}
|
|
110
120
|
/**
|
|
111
121
|
* Build entity decorators.
|
|
@@ -133,13 +143,26 @@ export class EntityCodeGenerator {
|
|
|
133
143
|
}
|
|
134
144
|
return lines.join('\n\n');
|
|
135
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* The `idKey` brand naming the key, which the type level cannot see otherwise: needed unless the key is
|
|
148
|
+
* one column holding the conventional name the entity would be read by, the first of `_id`, `id`, `uuid`.
|
|
149
|
+
*/
|
|
150
|
+
idKeyBrand(table) {
|
|
151
|
+
const property = (column) => this.options.propertyNameTransformer(column);
|
|
152
|
+
const keys = (table.primaryKey?.columns ?? []).map(property);
|
|
153
|
+
const properties = [...table.columns.keys()].map(property);
|
|
154
|
+
const conventional = ['_id', 'id', 'uuid'].find((name) => properties.includes(name));
|
|
155
|
+
if (!keys.length || (keys.length === 1 && keys[0] === conventional)) {
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
return ` [idKey]?: ${keys.map(quoted).join(' | ')};`;
|
|
159
|
+
}
|
|
136
160
|
/**
|
|
137
161
|
* Build a single field definition.
|
|
138
162
|
*/
|
|
139
163
|
buildField(col) {
|
|
140
164
|
const lines = [];
|
|
141
165
|
const propertyName = this.options.propertyNameTransformer(col.name);
|
|
142
|
-
const tsType = canonicalToTypeScript(col.type);
|
|
143
166
|
// JSDoc comment if enabled
|
|
144
167
|
if (this.options.addSyncComments) {
|
|
145
168
|
lines.push(' /**');
|
|
@@ -147,28 +170,10 @@ export class EntityCodeGenerator {
|
|
|
147
170
|
lines.push(` * Column: ${col.name} (${this.formatTypeDescription(col.type)})`);
|
|
148
171
|
lines.push(' */');
|
|
149
172
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const idOptions = this.buildIdOptions(col, propertyName);
|
|
153
|
-
lines.push(` @Id(${idOptions})`);
|
|
154
|
-
}
|
|
155
|
-
else {
|
|
156
|
-
const fieldOptions = this.buildFieldOptions(col, propertyName);
|
|
157
|
-
lines.push(` @Field(${fieldOptions})`);
|
|
158
|
-
}
|
|
159
|
-
// Property. A generated column is the database's to write, so it is `readonly`: a write payload
|
|
160
|
-
// leaves those out, and one naming it would be dropped rather than persisted.
|
|
161
|
-
const nullable = col.nullable ? '?' : '';
|
|
162
|
-
const written = col.generatedAs === undefined ? '' : 'readonly ';
|
|
163
|
-
lines.push(` ${written}${propertyName}${nullable}: ${tsType};`);
|
|
173
|
+
lines.push(` @${col.isPrimaryKey ? 'Id' : 'Field'}(${this.buildFieldOptions(col, propertyName)})`);
|
|
174
|
+
lines.push(` ${propertySource(col, propertyName)};`);
|
|
164
175
|
return lines.join('\n');
|
|
165
176
|
}
|
|
166
|
-
/**
|
|
167
|
-
* Build Id decorator options.
|
|
168
|
-
*/
|
|
169
|
-
buildIdOptions(col, propertyName) {
|
|
170
|
-
return propertyName === col.name ? '' : `{ name: '${col.name}' }`;
|
|
171
|
-
}
|
|
172
177
|
/**
|
|
173
178
|
* Build Field decorator options.
|
|
174
179
|
*/
|
|
@@ -196,7 +201,7 @@ export class EntityCodeGenerator {
|
|
|
196
201
|
}
|
|
197
202
|
// Incoming relations (other tables have FK to this)
|
|
198
203
|
for (const rel of table.incomingRelations) {
|
|
199
|
-
const relCode = this.buildIncomingRelation(rel
|
|
204
|
+
const relCode = this.buildIncomingRelation(rel);
|
|
200
205
|
lines.push(relCode);
|
|
201
206
|
}
|
|
202
207
|
if (lines.length > 0) {
|
|
@@ -210,16 +215,7 @@ export class EntityCodeGenerator {
|
|
|
210
215
|
buildOutgoingRelation(rel) {
|
|
211
216
|
const lines = [];
|
|
212
217
|
const relatedClassName = this.options.classNameTransformer(rel.to.table.name);
|
|
213
|
-
|
|
214
|
-
let propertyName = '';
|
|
215
|
-
const firstCol = rel.from.columns[0]?.name;
|
|
216
|
-
if (firstCol && (firstCol.toLowerCase().endsWith('_id') || firstCol.toLowerCase().endsWith('id'))) {
|
|
217
|
-
const baseName = firstCol.replace(/_?id$/i, '');
|
|
218
|
-
propertyName = this.options.propertyNameTransformer(baseName);
|
|
219
|
-
}
|
|
220
|
-
else {
|
|
221
|
-
propertyName = this.options.propertyNameTransformer(this.options.singularize(rel.to.table.name));
|
|
222
|
-
}
|
|
218
|
+
const propertyName = this.owningPropertyName(rel);
|
|
223
219
|
// JSDoc
|
|
224
220
|
if (this.options.addSyncComments) {
|
|
225
221
|
lines.push(' /**');
|
|
@@ -242,6 +238,23 @@ export class EntityCodeGenerator {
|
|
|
242
238
|
lines.push(` ${propertyName}?: ${relatedClassName};`);
|
|
243
239
|
return lines.join('\n');
|
|
244
240
|
}
|
|
241
|
+
/**
|
|
242
|
+
* The property of the side holding the foreign key: its column's name less an `_id` or `Id` suffix
|
|
243
|
+
* (`author_id` is `author`), else the singular of the table it points at. The inverse's `mappedBy` names the same.
|
|
244
|
+
*/
|
|
245
|
+
owningPropertyName(rel) {
|
|
246
|
+
const base = rel.from.columns[0]?.name.replace(/(?:_[iI][dD]|(?<=[a-z\d])Id)$/, '');
|
|
247
|
+
return this.options.propertyNameTransformer(base && base !== rel.from.columns[0]?.name ? base : this.options.singularize(rel.to.table.name));
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* The inverse side's property: the related table's name, prefixed with the owning property where that
|
|
251
|
+
* table points here more than once (`authorPosts`, `editorPosts`), so each gets a member of its own.
|
|
252
|
+
*/
|
|
253
|
+
inversePropertyName(rel) {
|
|
254
|
+
const name = this.options.propertyNameTransformer(rel.from.table.name);
|
|
255
|
+
const pointers = rel.to.table.incomingRelations.filter((it) => it.from.table === rel.from.table);
|
|
256
|
+
return pointers.length > 1 ? `${this.owningPropertyName(rel)}${upperFirst(name)}` : name;
|
|
257
|
+
}
|
|
245
258
|
/**
|
|
246
259
|
* The `references` callback of a to-one: its foreign key column where that is the target's whole primary
|
|
247
260
|
* key, column pairs otherwise, and nothing when the columns do not pair up.
|
|
@@ -264,10 +277,10 @@ export class EntityCodeGenerator {
|
|
|
264
277
|
/**
|
|
265
278
|
* Build incoming relation (OneToMany where other tables have FK to this).
|
|
266
279
|
*/
|
|
267
|
-
buildIncomingRelation(rel
|
|
280
|
+
buildIncomingRelation(rel) {
|
|
268
281
|
const lines = [];
|
|
269
282
|
const relatedClassName = this.options.classNameTransformer(rel.from.table.name);
|
|
270
|
-
const propertyName = this.
|
|
283
|
+
const propertyName = this.inversePropertyName(rel);
|
|
271
284
|
// JSDoc
|
|
272
285
|
if (this.options.addSyncComments) {
|
|
273
286
|
lines.push(' /**');
|
|
@@ -277,7 +290,7 @@ export class EntityCodeGenerator {
|
|
|
277
290
|
}
|
|
278
291
|
// The inverse side, mapped by the related class's property that points back at this one.
|
|
279
292
|
const param = lowerFirst(relatedClassName);
|
|
280
|
-
const inverse = memberSource(param, this.
|
|
293
|
+
const inverse = memberSource(param, this.owningPropertyName(rel));
|
|
281
294
|
const inverseType = INVERSE_RELATION[rel.type];
|
|
282
295
|
lines.push(` @${inverseType}({ entity: () => ${relatedClassName}, mappedBy: (${param}) => ${inverse} })`);
|
|
283
296
|
const many = inverseType === 'OneToMany' || inverseType === 'ManyToMany';
|
|
@@ -335,6 +348,24 @@ export class EntityCodeGenerator {
|
|
|
335
348
|
return singularize(name);
|
|
336
349
|
}
|
|
337
350
|
}
|
|
351
|
+
/**
|
|
352
|
+
* A column's property as source, declared the way every read and insert types it: present (`!`) where
|
|
353
|
+
* the column is NOT NULL, left out of an insert (`?`) where a default fills it (a single-column key stays
|
|
354
|
+
* `!`, which an insert leaves out anyway), `| null` where it holds NULL, `readonly` where the database computes it.
|
|
355
|
+
*/
|
|
356
|
+
function propertySource(col, propertyName) {
|
|
357
|
+
const type = col.enum
|
|
358
|
+
? enumMembersSource(col.enum).join(' | ')
|
|
359
|
+
: col.type.category === 'json'
|
|
360
|
+
? 'Json<unknown>'
|
|
361
|
+
: canonicalToTypeScript(col.type);
|
|
362
|
+
const written = col.generatedAs === undefined ? '' : 'readonly ';
|
|
363
|
+
if (col.nullable && !col.isPrimaryKey) {
|
|
364
|
+
return `${written}${propertyName}?: ${type} | null`;
|
|
365
|
+
}
|
|
366
|
+
const filled = !col.isPrimaryKey && col.defaultValue !== undefined;
|
|
367
|
+
return `${written}${propertyName}${filled ? '?' : '!'}: ${type}`;
|
|
368
|
+
}
|
|
338
369
|
/**
|
|
339
370
|
* Create an EntityCodeGenerator from SchemaAST.
|
|
340
371
|
*/
|
|
@@ -14,8 +14,8 @@ export function entityTypesSource(entities) {
|
|
|
14
14
|
const names = interfaceNames(metas);
|
|
15
15
|
const interfaces = metas.map((meta) => {
|
|
16
16
|
const members = [
|
|
17
|
-
...Object.entries(meta.fields).map(([key, field]) =>
|
|
18
|
-
...Object.entries(meta.relations).map(([key, rel]) =>
|
|
17
|
+
...Object.entries(meta.fields).map(([key, field]) => fieldMember(key, field)),
|
|
18
|
+
...Object.entries(meta.relations).map(([key, rel]) => ` ${propertyName(key)}?: ${relationType(rel, names)};`),
|
|
19
19
|
];
|
|
20
20
|
return `export interface ${names.get(meta.entity)} {\n${members.join('\n')}\n}`;
|
|
21
21
|
});
|
|
@@ -45,9 +45,26 @@ function identifier(text) {
|
|
|
45
45
|
return isIdentifierName(stripped) ? stripped : `Entity${stripped}`;
|
|
46
46
|
}
|
|
47
47
|
/** A column name a property cannot hold - `hero-image` - is quoted rather than dropped. */
|
|
48
|
-
function
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
function propertyName(key) {
|
|
49
|
+
return isIdentifierName(key) ? key : JSON.stringify(key);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* A field as an entity class declares it: required where every read has it and an insert names it, a
|
|
53
|
+
* key included, which an insert leaves out anyway; optional where a default fills it or a read skips it
|
|
54
|
+
* (`eager: false`); `| null` where the column holds NULL; `readonly` where the database computes it.
|
|
55
|
+
*/
|
|
56
|
+
function fieldMember(key, field) {
|
|
57
|
+
const type = fieldType(field);
|
|
58
|
+
const name = propertyName(key);
|
|
59
|
+
if (!field) {
|
|
60
|
+
return ` ${name}?: ${type};`;
|
|
61
|
+
}
|
|
62
|
+
const written = field.computed === undefined ? '' : 'readonly ';
|
|
63
|
+
if (!field.isId && field.nullable !== false) {
|
|
64
|
+
return ` ${written}${name}?: ${type} | null;`;
|
|
65
|
+
}
|
|
66
|
+
const optional = !field.isId && (field.defaultValue !== undefined || field.onInsert !== undefined || field.eager === false);
|
|
67
|
+
return ` ${written}${name}${optional ? '?' : ''}: ${type};`;
|
|
51
68
|
}
|
|
52
69
|
/**
|
|
53
70
|
* The property type a column reads back as, resolved the way the DDL resolves it - so a foreign key
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import type { ColumnNode } from '../../schema/types.js';
|
|
2
|
-
/** A column's `@
|
|
1
|
+
import type { ColumnNode, EnumValues } from '../../schema/types.js';
|
|
2
|
+
/** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
|
|
3
3
|
export declare function buildFieldOptionsSource(col: ColumnNode, propertyName: string, indexName?: string): string;
|
|
4
|
+
/** An enum's members as source literals, which are also the property's type as a union. */
|
|
5
|
+
export declare function enumMembersSource(members: EnumValues): string[];
|
|
4
6
|
/** Whether the field's decorator needs `raw` imported, the way {@link indexNeedsRaw} does for an index. */
|
|
5
7
|
export declare function fieldNeedsRaw(col: ColumnNode): boolean;
|
|
@@ -1,34 +1,42 @@
|
|
|
1
|
-
import { canonicalToColumnType } from '../../schema/canonicalType.js';
|
|
1
|
+
import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalType.js';
|
|
2
|
+
import { isAutoIncrement } from '../../util/field.util.js';
|
|
2
3
|
import { quoted, rawTag } from './sourceLiteral.js';
|
|
3
4
|
/** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
|
|
4
5
|
const OPTION_SOURCE = {
|
|
5
6
|
// Without this the entity maps to a column named after the property, which for anything the
|
|
6
7
|
// transformer rewrote - every `user_id` - is a column the database does not have.
|
|
7
8
|
name: (col, { propertyName }) => (propertyName === col.name ? [] : [`name: ${quoted(col.name)}`]),
|
|
9
|
+
// The column type as `type`, which the decorator checks the property against and the schema reads
|
|
10
|
+
// exactly as it reads `columnType`.
|
|
8
11
|
type: (col) => {
|
|
9
12
|
const columnType = canonicalToColumnType(col.type);
|
|
10
13
|
return [
|
|
11
|
-
`
|
|
14
|
+
`type: ${quoted(columnType)}`,
|
|
12
15
|
...(col.type.length && col.type.category === 'string' ? [`length: ${col.type.length}`] : []),
|
|
16
|
+
...(col.type.length && isVectorCategory(col.type.category) ? [`dimensions: ${col.type.length}`] : []),
|
|
13
17
|
...(col.type.precision === undefined ? [] : [`precision: ${col.type.precision}`]),
|
|
14
18
|
...(col.type.precision !== undefined && col.type.scale !== undefined ? [`scale: ${col.type.scale}`] : []),
|
|
15
19
|
];
|
|
16
20
|
},
|
|
17
|
-
|
|
21
|
+
// A column is nullable unless it says otherwise, and a key is NOT NULL without saying so.
|
|
22
|
+
nullable: (col) => (col.nullable || col.isPrimaryKey ? [] : ['nullable: false']),
|
|
18
23
|
isUnique: (col) => (col.isUnique ? ['unique: true'] : []),
|
|
19
|
-
enum: (col) => col.enum ? [`enum: [${col.enum
|
|
24
|
+
enum: (col) => (col.enum ? [`enum: [${enumMembersSource(col.enum).join(', ')}] as const`] : []),
|
|
20
25
|
defaultValue: (col) => col.defaultValue === undefined ? [] : [`defaultValue: ${defaultValueSource(col.defaultValue)}`],
|
|
21
26
|
generatedAs: (col) => (col.generatedAs ? [`computed: ${rawTag(col.generatedAs)}`, 'stored: true'] : []),
|
|
22
27
|
comment: (col) => (col.comment ? [`comment: ${quoted(col.comment)}`] : []),
|
|
23
|
-
// A key is `@Id`,
|
|
28
|
+
// A key is `@Id`, which says it on its own, and generates where `isAutoIncrement` says, which only a
|
|
29
|
+
// column the database treats otherwise contradicts.
|
|
24
30
|
isPrimaryKey: null,
|
|
25
|
-
isAutoIncrement:
|
|
31
|
+
isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, col.isPrimaryKey && col.table.primaryKey?.columns.length === 1) === col.isAutoIncrement
|
|
32
|
+
? []
|
|
33
|
+
: [`autoIncrement: ${col.isAutoIncrement}`],
|
|
26
34
|
// Graph links. A foreign key becomes a relation decorator, emitted beside the field rather than in it.
|
|
27
35
|
table: null,
|
|
28
36
|
references: null,
|
|
29
37
|
referencedBy: null,
|
|
30
38
|
};
|
|
31
|
-
/** A column's `@
|
|
39
|
+
/** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
|
|
32
40
|
export function buildFieldOptionsSource(col, propertyName, indexName) {
|
|
33
41
|
const context = { propertyName, indexName };
|
|
34
42
|
const options = [
|
|
@@ -36,7 +44,11 @@ export function buildFieldOptionsSource(col, propertyName, indexName) {
|
|
|
36
44
|
// Not a column field: the index is a table-level object the field only borrows.
|
|
37
45
|
...(indexName ? [`index: ${quoted(indexName)}`] : []),
|
|
38
46
|
];
|
|
39
|
-
return
|
|
47
|
+
return `{ ${options.join(', ')} }`;
|
|
48
|
+
}
|
|
49
|
+
/** An enum's members as source literals, which are also the property's type as a union. */
|
|
50
|
+
export function enumMembersSource(members) {
|
|
51
|
+
return members.map((it) => (typeof it === 'number' ? String(it) : quoted(it)));
|
|
40
52
|
}
|
|
41
53
|
/** Whether the field's decorator needs `raw` imported, the way {@link indexNeedsRaw} does for an index. */
|
|
42
54
|
export function fieldNeedsRaw(col) {
|
package/dist/type/entity.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { SqlDialectName } from './dialect.js';
|
|
|
3
3
|
import type { FilterOptions, RelationQuery } from './query.js';
|
|
4
4
|
import type { ColumnRef, QueryRaw, RawFor, RelationAggregate } from './queryRaw.js';
|
|
5
5
|
import type { QueryWhere } from './queryWhere.js';
|
|
6
|
-
import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsMany, Json, Scalar, Type, Unpacked, Writable } from './utility.js';
|
|
6
|
+
import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, IsMany, Json, Scalar, Type, Unpacked, Writable } from './utility.js';
|
|
7
7
|
import type { VectorDistance, VectorIndexOptions, VectorIndexType } from './vector.js';
|
|
8
8
|
/** Brands the property an entity is identified by, where it is not `id`, `_id` or `uuid`. */
|
|
9
9
|
export declare const idKey: unique symbol;
|
|
@@ -35,8 +35,20 @@ export type FieldKey<E> = {
|
|
|
35
35
|
export type WritableKey<E> = {
|
|
36
36
|
readonly [K in FieldKey<E>]-?: IsEqual<Pick<E, K>, Writable<Pick<E, K>>> extends true ? K : never;
|
|
37
37
|
}[FieldKey<E>];
|
|
38
|
-
/**
|
|
39
|
-
|
|
38
|
+
/**
|
|
39
|
+
* What an insert may leave out however the entity declares it: a single-column key, which something
|
|
40
|
+
* usually generates, and the version, which uql starts at 0. A composite key is the references a row is
|
|
41
|
+
* made of, so an insert names it.
|
|
42
|
+
*/
|
|
43
|
+
type FilledKey<E> = SoleIdKey<E> | VersionKey<E>;
|
|
44
|
+
/**
|
|
45
|
+
* A whole-record write as a caller supplies one: {@link EntityData} without the fields it cannot write,
|
|
46
|
+
* a {@link FilledKey} optional. That part is a conditional, which TypeScript leaves shut while it types a
|
|
47
|
+
* call's payload against the generic write: as a mapped type, it doubled what checking an insert cost.
|
|
48
|
+
*/
|
|
49
|
+
export type EntityWrite<E> = EntityData<E, Exclude<WritableKey<E>, FilledKey<E>>> & ([FilledKey<E>] extends [never] ? unknown : {
|
|
50
|
+
[P in WritableKey<E> & FilledKey<E>]?: E[P];
|
|
51
|
+
});
|
|
40
52
|
/** A row a trigger's body writes: each writable field its value, or SQL - a row's ref most often. */
|
|
41
53
|
export type WriteRow<E, F extends keyof E = WritableKey<E>> = {
|
|
42
54
|
readonly [K in F]?: E[K] | RawFor<QueryRaw, E[K]>;
|
|
@@ -66,8 +78,6 @@ export type ToOneRelationKey<E> = {
|
|
|
66
78
|
}[RelationKey<E>];
|
|
67
79
|
/** The relation names a parent holds many rows of: what a populated query fills, and what an aggregate reads. */
|
|
68
80
|
export type ToManyRelationKey<E> = Exclude<RelationKey<E>, ToOneRelationKey<E>>;
|
|
69
|
-
/** Whether `T` carries the `Json` brand, read off its marker key: a primitive matches `Json<infer P>` too. */
|
|
70
|
-
type IsJson<T> = '__json' extends keyof T ? true : false;
|
|
71
81
|
/** The payload `P` of a branded `Json<P>`, or `never` for any other type. */
|
|
72
82
|
type UnwrapJson<T> = IsJson<T> extends true ? (T extends Json<infer P> ? P : never) : never;
|
|
73
83
|
/** What a JSON column declared as `V` holds, `Json<P>` or `Json<P>[]` alike; `never` on any other column. */
|
|
@@ -140,15 +150,16 @@ type FieldUpdateOpFor<V> = [NonNullable<V>] extends [number] ? FieldUpdateOp<num
|
|
|
140
150
|
type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V>;
|
|
141
151
|
/**
|
|
142
152
|
* What a whole-record write persists: the fields and relations with their declared optionality, a
|
|
143
|
-
* related row
|
|
153
|
+
* related row as a caller writes one, and no methods. Two mapped types, since asking each key costs a
|
|
154
|
+
* conditional.
|
|
144
155
|
*/
|
|
145
156
|
export type EntityData<E, F extends keyof E = FieldKey<E>, R extends keyof E = RelationKey<E>> = {
|
|
146
157
|
[P in F]: E[P];
|
|
147
158
|
} & {
|
|
148
159
|
[P in R]: E[P] | RelationData<E[P]>;
|
|
149
160
|
};
|
|
150
|
-
/** A relation's value as its rows' {@link
|
|
151
|
-
type RelationData<V> = V extends readonly (infer T)[] ?
|
|
161
|
+
/** A relation's value as its rows' {@link EntityWrite}. */
|
|
162
|
+
type RelationData<V> = V extends readonly (infer T)[] ? EntityWrite<T>[] : V extends object ? EntityWrite<V> : never;
|
|
152
163
|
/** {@link EntityData} made partial, each member also taking its {@link UpdateExtra}. */
|
|
153
164
|
export type UpdatePayload<E, Raw = QueryRaw, F extends keyof E = FieldKey<E>, R extends keyof E = RelationKey<E>> = {
|
|
154
165
|
[P in F]?: E[P] | UpdateExtra<E[P], Raw>;
|
|
@@ -171,6 +182,11 @@ export type IdKey<E> = ([NamedIdKey<E>] extends [never] ? FieldKey<E> : NamedIdK
|
|
|
171
182
|
export type IdValue<E> = E[IdKey<E>];
|
|
172
183
|
/** Whether `E`'s primary key spans several columns, which no single column can reference. */
|
|
173
184
|
export type HasCompositeKey<E> = true extends IsUnion<IdKey<E>> ? true : false;
|
|
185
|
+
/**
|
|
186
|
+
* The key an entity names where it is one column, as `soleIdOf` reads it at run time; `never` for a
|
|
187
|
+
* composite and for no named key, which {@link HasCompositeKey} tells apart where a reference needs it.
|
|
188
|
+
*/
|
|
189
|
+
type SoleIdKey<E> = true extends IsUnion<NamedIdKey<E>> ? never : NamedIdKey<E>;
|
|
174
190
|
/** Every column of a key, which is how a composite row is named and what a `$where` reduces to. */
|
|
175
191
|
type IdMap<E> = Partial<Pick<E, IdKey<E>>>;
|
|
176
192
|
/**
|
|
@@ -184,7 +200,7 @@ type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) :
|
|
|
184
200
|
* The id a write reports: the value for a single key, the map for a composite. {@link EntityId} where
|
|
185
201
|
* the entity names no key, since a composite cannot then be told from a single one.
|
|
186
202
|
*/
|
|
187
|
-
export type WrittenId<E> = [NamedIdKey<E>] extends [never] ? EntityId<E> :
|
|
203
|
+
export type WrittenId<E> = [NamedIdKey<E>] extends [never] ? EntityId<E> : [SoleIdKey<E>] extends [never] ? IdMap<E> : IdValue<E>;
|
|
188
204
|
/** Every SQL column type a field may declare, by family: the unions below and `columnFamily` both read it. */
|
|
189
205
|
export declare const COLUMN_TYPES: {
|
|
190
206
|
readonly numeric: readonly ['int', 'integer', 'tinyint', 'smallint', 'bigint', 'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'numeric', 'real'];
|
|
@@ -201,6 +217,8 @@ type ColumnTypeOf<F extends ColumnFamily> = (typeof COLUMN_TYPES)[F][number];
|
|
|
201
217
|
export type NumericColumnType = ColumnTypeOf<'numeric'>;
|
|
202
218
|
export type StringColumnType = ColumnTypeOf<'string'>;
|
|
203
219
|
export type DateColumnType = ColumnTypeOf<'date'>;
|
|
220
|
+
/** A date column holding a time of day, which names no day: every driver reads it back as text, never a `Date`. */
|
|
221
|
+
type TimeColumnType = 'time';
|
|
204
222
|
export type JsonColumnType = ColumnTypeOf<'json'>;
|
|
205
223
|
export type BlobColumnType = ColumnTypeOf<'blob'>;
|
|
206
224
|
export type BooleanColumnType = ColumnTypeOf<'boolean'>;
|
|
@@ -219,7 +237,7 @@ export type FieldType = StringConstructor | NumberConstructor | BooleanConstruct
|
|
|
219
237
|
* compile. JSON is matched on its brand, which a `Json<string>` shares with `string`, and arrays before
|
|
220
238
|
* scalars, so a vector is not read as a `number`.
|
|
221
239
|
*/
|
|
222
|
-
export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType : T extends number ? NumberConstructor | NumericColumnType : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | DateColumnType : T extends Uint8Array ? BlobColumnType : FieldType;
|
|
240
|
+
export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType | TimeColumnType : T extends number ? NumberConstructor | NumericColumnType : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | Exclude<DateColumnType, TimeColumnType> : T extends Uint8Array ? BlobColumnType : FieldType;
|
|
223
241
|
/** A field as the registry holds it: what was authored, plus what registration worked out, which no decorator can write. */
|
|
224
242
|
export type FieldMeta<V = TsTypeOf<FieldType>> = Except<FieldOptions<V>, 'computed'> & {
|
|
225
243
|
/** {@link FieldOptions.computed}, a callback resolved to the SQL it returns. */
|
|
@@ -318,7 +336,7 @@ type JsonDdlDefault = Scalar | Record<string, unknown>;
|
|
|
318
336
|
* The TypeScript type a declared `type` implies, the inverse of {@link TypeFor}: a decorator checks the
|
|
319
337
|
* property against it, `defineEntity` the other way round. `entityOptions.test-d.ts` keeps them agreeing.
|
|
320
338
|
*/
|
|
321
|
-
export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? Json<unknown> | readonly Json<unknown>[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
|
|
339
|
+
export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType | TimeColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? Json<unknown> | readonly Json<unknown>[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
|
|
322
340
|
/**
|
|
323
341
|
* {@link FieldOptions} for a field declared as `V`, `type` checked by {@link TypeFor}. A foreign key may
|
|
324
342
|
* omit it, taking the referenced key's column type instead.
|
package/dist/type/queryRaw.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export type QueryRawFn = (opts: QueryRawRenderOptions) => unknown;
|
|
|
33
33
|
export declare const RAW_VALUE: unique symbol;
|
|
34
34
|
export declare const RAW_ALIAS: unique symbol;
|
|
35
35
|
export declare const RAW_TEXT: unique symbol;
|
|
36
|
+
/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */
|
|
37
|
+
export declare const RAW_VALUE_TYPE: unique symbol;
|
|
36
38
|
export declare class QueryRaw {
|
|
37
39
|
readonly [RAW_VALUE]: QueryRawFn;
|
|
38
40
|
readonly [RAW_ALIAS]?: string;
|
|
@@ -55,7 +57,7 @@ export declare class QueryRaw {
|
|
|
55
57
|
*/
|
|
56
58
|
export declare class ColumnRef<K extends string = string, V = unknown> extends QueryRaw {
|
|
57
59
|
readonly key: K;
|
|
58
|
-
readonly
|
|
60
|
+
readonly [RAW_VALUE_TYPE]?: V;
|
|
59
61
|
constructor(key: K, value: QueryRawFn);
|
|
60
62
|
}
|
|
61
63
|
/**
|
|
@@ -63,7 +65,7 @@ export declare class ColumnRef<K extends string = string, V = unknown> extends Q
|
|
|
63
65
|
* holding one, nullability aside. `Raw` is what the transport carries, so the wire's `never` stays one.
|
|
64
66
|
*/
|
|
65
67
|
export type RawFor<Raw, V> = Raw & {
|
|
66
|
-
readonly
|
|
68
|
+
readonly [RAW_VALUE_TYPE]?: V | null;
|
|
67
69
|
};
|
|
68
70
|
/**
|
|
69
71
|
* A relation aggregate as SQL, read off a `computed` field's refs: `(user) => user.resources.count()`.
|
|
@@ -77,7 +79,7 @@ export type RawFor<Raw, V> = Raw & {
|
|
|
77
79
|
export declare class RelationAggregate<V = unknown, Storable extends boolean = boolean> extends QueryRaw {
|
|
78
80
|
/** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */
|
|
79
81
|
readonly spec: RelationAggregateSpec;
|
|
80
|
-
readonly
|
|
82
|
+
readonly [RAW_VALUE_TYPE]?: V;
|
|
81
83
|
private readonly __storable;
|
|
82
84
|
constructor(
|
|
83
85
|
/** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */
|
package/dist/type/queryRaw.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export const RAW_VALUE = Symbol('rawValue');
|
|
2
2
|
export const RAW_ALIAS = Symbol('rawAlias');
|
|
3
3
|
export const RAW_TEXT = Symbol('rawText');
|
|
4
|
+
/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */
|
|
5
|
+
export const RAW_VALUE_TYPE = Symbol('rawValueType');
|
|
4
6
|
export class QueryRaw {
|
|
5
7
|
[RAW_VALUE];
|
|
6
8
|
[RAW_ALIAS];
|
package/dist/type/utility.d.ts
CHANGED
|
@@ -20,9 +20,14 @@ export type PrimaryKey = string | number | bigint;
|
|
|
20
20
|
* Brands a JSON field, `settings?: Json<{ isArchived?: boolean }>`, so it reads as a field rather than a
|
|
21
21
|
* relation; `Json<T>[]` is a list of documents.
|
|
22
22
|
*/
|
|
23
|
-
export type Json<T = unknown> = T &
|
|
24
|
-
|
|
25
|
-
}
|
|
23
|
+
export type Json<T = unknown> = T & JsonBrand;
|
|
24
|
+
declare const json: unique symbol;
|
|
25
|
+
/** The marker {@link Json} adds: a symbol key, so no string key, path or autocomplete shows it. */
|
|
26
|
+
export interface JsonBrand {
|
|
27
|
+
readonly [json]?: never;
|
|
28
|
+
}
|
|
29
|
+
/** Whether `T` carries the {@link Json} brand: a primitive matches `Json<infer P>` too, so the key is what tells. */
|
|
30
|
+
export type IsJson<T> = typeof json extends keyof T ? true : false;
|
|
26
31
|
export type ExpandScalar<T> = T extends Date ? Date | string : T;
|
|
27
32
|
/**
|
|
28
33
|
* A raw database result row before entity mapping.
|
|
@@ -75,3 +80,4 @@ export type Unpacked<T> = T extends readonly (infer U)[] ? U : T extends (...arg
|
|
|
75
80
|
* each is load-bearing for.
|
|
76
81
|
*/
|
|
77
82
|
export type IsMany<V> = [NonNullable<V>] extends [readonly unknown[]] ? true : false;
|
|
83
|
+
export {};
|
|
@@ -14,20 +14,12 @@ export declare function insertShapeOf<E>(meta: EntityMeta<E>, record: EntityData
|
|
|
14
14
|
* whether or not it was filled yet. A record missing one writes its default.
|
|
15
15
|
*/
|
|
16
16
|
export declare function getInsertFieldKeys<E>(meta: EntityMeta<E>, payloads: EntityData<E>[]): FieldKey<E>[];
|
|
17
|
-
export declare function getFieldCallbackValue(val: OnFieldCallback): string | number | bigint | boolean | Date | QueryRaw | readonly
|
|
18
|
-
readonly __json?: never;
|
|
19
|
-
}[] | readonly number[] | Uint8Array<ArrayBufferLike> | {
|
|
20
|
-
readonly __json?: never;
|
|
21
|
-
};
|
|
17
|
+
export declare function getFieldCallbackValue(val: OnFieldCallback): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly import("../type/utility.js").JsonBrand[] | readonly number[] | Uint8Array<ArrayBufferLike>;
|
|
22
18
|
/**
|
|
23
19
|
* Resolves the value stamped on the soft-delete field when deleting a row.
|
|
24
20
|
* `true` stamps the current timestamp (`new Date()`); any other marker is an {@link OnFieldCallback}.
|
|
25
21
|
*/
|
|
26
|
-
export declare function getSoftDeleteValue(field: FieldOptions): string | number | bigint | boolean | Date | QueryRaw | readonly
|
|
27
|
-
readonly __json?: never;
|
|
28
|
-
}[] | readonly number[] | Uint8Array<ArrayBufferLike> | {
|
|
29
|
-
readonly __json?: never;
|
|
30
|
-
};
|
|
22
|
+
export declare function getSoftDeleteValue(field: FieldOptions): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly import("../type/utility.js").JsonBrand[] | readonly number[] | Uint8Array<ArrayBufferLike>;
|
|
31
23
|
/** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
|
|
32
24
|
export declare function fillOnFields<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, payload: R | R[], callbackKey: CallbackKey): R[];
|
|
33
25
|
/**
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"homepage": "https://uql-orm.dev",
|
|
4
4
|
"description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Deno, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.91.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=24"
|
|
@@ -136,9 +136,9 @@
|
|
|
136
136
|
"@electric-sql/pglite-pgvector": "0.0.9",
|
|
137
137
|
"@libsql/client": "^0.18.0",
|
|
138
138
|
"@neondatabase/serverless": "^1.1.0",
|
|
139
|
-
"@nestjs/common": "^12.1.
|
|
140
|
-
"@nestjs/core": "^12.1.
|
|
141
|
-
"@nestjs/testing": "^12.1.
|
|
139
|
+
"@nestjs/common": "^12.1.1",
|
|
140
|
+
"@nestjs/core": "^12.1.1",
|
|
141
|
+
"@nestjs/testing": "^12.1.1",
|
|
142
142
|
"@tursodatabase/database": "^0.7.2",
|
|
143
143
|
"@tursodatabase/serverless": "^1.4.0",
|
|
144
144
|
"@types/better-sqlite3": "^9.6.0",
|
|
@@ -149,7 +149,7 @@
|
|
|
149
149
|
"better-sqlite3": "^13.0.3",
|
|
150
150
|
"express": "^5.2.1",
|
|
151
151
|
"mariadb": "^3.5.4",
|
|
152
|
-
"mongodb": "^7.
|
|
152
|
+
"mongodb": "^7.7.0",
|
|
153
153
|
"mssql": "^12",
|
|
154
154
|
"mysql2": "^3.24.4",
|
|
155
155
|
"pg": "^8.23.0",
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -49,10 +49,10 @@ import { Entity, Field, Id, ManyToOne, OneToMany } from 'uql-orm';
|
|
|
49
49
|
@Entity()
|
|
50
50
|
export class User {
|
|
51
51
|
@Id({ type: 'uuid', onInsert: () => crypto.randomUUID() })
|
|
52
|
-
id
|
|
52
|
+
id!: string;
|
|
53
53
|
|
|
54
54
|
@Field({ type: String, unique: true, nullable: false })
|
|
55
|
-
email
|
|
55
|
+
email!: string;
|
|
56
56
|
|
|
57
57
|
@OneToMany({ entity: () => Post, mappedBy: (post) => post.author })
|
|
58
58
|
posts?: Post[];
|
|
@@ -61,7 +61,7 @@ export class User {
|
|
|
61
61
|
@Entity()
|
|
62
62
|
export class Post {
|
|
63
63
|
@Id({ type: Number })
|
|
64
|
-
id
|
|
64
|
+
id!: number;
|
|
65
65
|
|
|
66
66
|
@Field({ type: String })
|
|
67
67
|
title?: string | null;
|
|
@@ -76,6 +76,7 @@ export class Post {
|
|
|
76
76
|
|
|
77
77
|
- Every `@Field` states its `type` (`String`, `Number`, `Boolean`, `Date` (an instant, bound and read as UTC on every engine; `TIMESTAMPTZ` on Postgres and CockroachDB, `DATETIME(3)` on MySQL and MariaDB; `precision` sets its fractional-second digits), `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`), except a foreign key, which takes `references` and inherits the target key's type.
|
|
78
78
|
- A column is nullable unless it says `nullable: false`, and its property must admit `null` to match: `title?: string | null`. A property typed without `| null` on a nullable column is a compile error.
|
|
79
|
+
- Declare a `nullable: false` column `!` (`email!: string`): reads have it and inserts must name it, except a single-column key and a `version`, which uql fills. Declare `?` whatever an insert may leave out: a nullable, `onInsert`, `defaultValue`, `eager: false` or `computed` field, and relations.
|
|
79
80
|
- An engine's own column type is a `raw` constant, ``columnType: raw`tsvector` ``, rendered verbatim and carrying its own `length`/`precision`: never a bare string.
|
|
80
81
|
- Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
81
82
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
|