uql-orm 0.100.1 → 0.100.2

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.
@@ -4,7 +4,7 @@
4
4
  "sourcesContent": [
5
5
  "import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors = new Set<RequestCallback>();\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.add(cb);\n return (): void => {\n subscriptors.delete(cb);\n };\n}\n",
6
6
  "import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey } 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 * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A row with the value a `$sort` projects under the name its `$project` gives - a vector's distance, or a\n * `$text` relevance - which is not inferred: `(await querier.findMany(Post, q)) as WithProjection<Post, 'score'>[]`.\n */\nexport type WithProjection<E, K extends string> = E & Record<K, number>;\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, 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 * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $exclude: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // A populated relation's rows keep their declared type, so they have no `_count` for a `$count` to fill.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Never decoded: HTTP refuses it, because a request cannot hold a lock past its response.\n $lock: { value: 'object', scope: 'statement' },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Raw = QueryRaw> = Pick<Query<E, Raw>, QueryClauseOf<{ scope: 'relation' }>> & {\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 query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Raw = QueryRaw> = Except<Query<E, Raw>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/** A {@link QueryKeyset} with its projection captured, so {@link QueryFindResult} can narrow the row. */\nexport type QueryKeysetProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n Raw = QueryRaw,\n> = QueryKeyset<E, Raw> & QueryProjection<E, S, V, X, P, C, Raw>;\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * The keys a query comes back with, as the runtime projects them: a positive `$select`'s, or every\n * field minus what `$select` or `$exclude` subtracts, plus the populated relations.\n * @internal\n */\ntype ProjectedKeys<E, S, V, X, P> =\n | ([V] extends [false | 0] ? Exclude<FieldKey<E>, S> : [S] extends [never] ? Exclude<FieldKey<E>, X> : S)\n | P;\n\n/**\n * Whether every entry of the captured map says the same thing: all selected, or all subtracted.\n * @internal\n */\ntype IsUniform<V> = [V] extends [true | 1] ? true : [V] extends [false | 0] ? true : false;\n\n/**\n * A find's row: the entity narrowed to what the query projected and populated, so reading anything\n * else does not compile. The entity itself where the projection is raw, absent or not uniform.\n * @example `QueryFindResult<User, 'id' | 'name'>`\n */\nexport type QueryFindResult<\n E,\n S extends FieldKey<E> = never,\n // A whitelist by default, so the hand-written form reads `QueryFindResult<User, 'id' | 'name'>`.\n V = true,\n X extends FieldKey<E> = never,\n P extends RelationKey<E> = never,\n C extends RelationKey<E> = never,\n> = QueryProjectedRow<E, S, V, X, P, C> & CountedRelations<C>;\n\n/**\n * The `_count` a query asked for, or an inert intersection member when it asked for none - so a read\n * without `$count` keeps exactly the row type it had.\n */\ntype CountedRelations<C extends PropertyKey> = [C] extends [never]\n ? unknown\n : { [K in typeof COUNT_RESULT_KEY]: { [R in C]: number } };\n\n/** @internal */\ntype QueryProjectedRow<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E>,\n> = [S | X] extends [never]\n ? E\n : IsUniform<V> extends true\n ? [PopulatedToMany<E, P>] extends [never]\n ? // `Pick`, not a key remap: an entity keyed by an index signature - a content type defined at\n // runtime - has `string` for its keys, and a remap keeps no literal one, so every projection\n // over one came back as `{}`.\n Pick<E, ProjectedKeys<E, S, V, X, P> & keyof E>\n : // A populated to-many is always a list, empty where the parent has no children, so it maps\n // and counts without a guard. Only that promotion needs a second member, and only a query\n // that populates one pays for it; every other key keeps the modifier the entity declared,\n // a to-one relation included, since a join that finds no row leaves it absent.\n Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E> & {\n [K in PopulatedToMany<E, P>]-?: NonNullable<E[K]>;\n }\n : E;\n\n/** The to-many relations a query populated, which come back as lists rather than as optional ones. */\ntype PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * read in the same transaction after the write (before it, for a delete), so they hold what the database filled.\n */\nexport type WriteOptions<E, S extends FieldKey<E>, V = true> = { readonly returning?: QuerySelect<E, S, V> };\n\n/** What a write resolves to: `Plain`, its ids or its count, where it names no `returning` field; else `Read`. */\nexport type ReturningResult<S, Plain, Read> = [S] extends [never] ? Plain : Read;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
7
- "import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, 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\n/**\n * What a `raw` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type RawValue = Scalar | null | readonly (Scalar | null)[] | QueryRaw;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `raw` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: RawValue[]] | readonly [sql: QueryRaw];\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, carried in a phantom field so the aggregate a field declares decides the\n * property's type.\n */\nexport class RelationAggregate<V = unknown> extends QueryRaw {\n declare readonly [RAW_VALUE_TYPE]?: V;\n\n constructor(\n /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */\n readonly spec: RelationAggregateSpec,\n value: 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",
7
+ "import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, 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\n/**\n * What a `raw` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type RawValue = Scalar | null | readonly (Scalar | null)[] | QueryRaw;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `raw` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: RawValue[]] | readonly [sql: QueryRaw];\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, text }: { readonly alias?: string; readonly 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, text: 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, carried in a phantom field so the aggregate a field declares decides the\n * property's type.\n */\nexport class RelationAggregate<V = unknown> extends QueryRaw {\n declare readonly [RAW_VALUE_TYPE]?: V;\n\n constructor(\n /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */\n readonly spec: RelationAggregateSpec,\n value: 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
  "import type { EntityMeta } from '../type/index.js';\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n if (!(size >= 1)) {\n throw new RangeError(`a chunk holds at least one item, not ${size}`);\n }\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n",
9
9
  "/**\n * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers\n * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization\n * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the\n * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.\n */\nexport type QueryErrorKind =\n | 'uniqueViolation'\n | 'foreignKeyViolation'\n | 'notNullViolation'\n | 'checkViolation'\n | 'optimisticLock'\n | 'retryable'\n | 'usage'\n | 'security';\n\n/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */\nexport abstract class UqlError extends Error {\n abstract readonly kind: QueryErrorKind;\n abstract readonly status: number;\n}\n\n/**\n * Thrown where the caller used the API in a way no statement can carry out: an update payload with no\n * version, a `$lock` outside a transaction, a method with no version to match. A `400` over HTTP: the\n * request is malformed, not the server's failure, and an untyped client is exactly who reaches this.\n */\nexport class UqlUsageError extends UqlError {\n override name = 'UqlUsageError';\n readonly kind = 'usage';\n readonly status = 400;\n}\n\n/**\n * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.\n * Fails the statement closed.\n */\nexport class UqlSecurityError extends UqlError {\n override name = 'UqlSecurityError';\n readonly kind = 'security';\n readonly status = 403;\n}\n\n/** What a value is, for a refusal naming what `/http` handed over instead of what the types require. */\nexport function kindOf(value: unknown): string {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Thrown when an update's `@Field({ version })` no longer matches the row: another writer moved it on,\n * or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`\n * where there is no row left.\n */\nexport class UqlOptimisticLockError extends UqlError {\n override name = 'UqlOptimisticLockError';\n readonly kind = 'optimisticLock';\n readonly status = 409;\n\n constructor(\n message: string,\n readonly expected: unknown,\n readonly actual: unknown,\n ) {\n super(message);\n }\n}\n",
10
10
  "import type { QueryKeyset, QueryOptions, WireQuery } from '../type/index.js';\n// the clause table itself, not the barrel: this module is in the browser bundle's graph\nimport { QUERY_CLAUSES, type QueryClause } from '../type/query.js';\n// the brand alone, not the class: importing `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/** The cursors a page request carries; only `findManyPage` reads them. */\nexport type WireCursors = Pick<QueryKeyset<unknown>, '$after' | '$before'>;\n\n/**\n * Keys that mean something locally but that this transport can never honor, so they are rejected\n * rather than dropped like the rest. Each request runs on its own auto-committing connection, so a\n * row lock taken here is released before the response is written: honoring `$lock` is impossible,\n * and ignoring it would hand the caller a read they believe is serialized and is not.\n */\nconst REJECTED_QUERY_KEYS = new Set<string>(['$lock'] satisfies (keyof WireQuery<unknown>)[]);\n\n/**\n * The keys accepted from the wire, mapped to how each value is decoded: every query clause ({@link QUERY_CLAUSES})\n * plus the {@link WIRE_FLAGS}. Anything else (e.g. `filters`, `context`, `$entity`) is dropped, so a remote\n * client can't bypass a security filter or inject ambient context.\n */\nconst WIRE_VALUES: ReadonlyMap<string, QueryClause['value']> = new Map([\n ...getKeys(QUERY_CLAUSES).map((key) => [key, QUERY_CLAUSES[key].value] as const),\n ...WIRE_FLAGS.map((flag) => [flag, 'boolean'] as const),\n]);\n\n/**\n * Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query\n * object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.\n */\nexport function parseQueryParams<E = unknown>(params: unknown = {}): WireQuery<E> & WireFlags & WireCursors {\n if (!isRecord(params)) {\n throw new UqlUsageError('the query must be a JSON object');\n }\n const query: Record<string, unknown> = {};\n for (const key of getKeys(params)) {\n if (REJECTED_QUERY_KEYS.has(key)) {\n throw new UqlUsageError(`'${key}' is not supported over HTTP`);\n }\n const shape = WIRE_VALUES.get(key);\n if (shape && params[key] !== undefined) {\n query[key] = decodeWireValue(key, shape, params[key]);\n }\n }\n query['$where'] ??= {};\n if (!isWhereMap(query['$where'])) {\n throw new UqlUsageError(\"'$where' must be a JSON object\");\n }\n return query;\n}\n\n/**\n * Decodes a value to the type its clause declares. A query string carries every value as text, so a boolean\n * must be decoded: `'false'` is a non-empty string, and taken as is, `$distinct=false` would turn it on.\n */\nfunction decodeWireValue(key: string, shape: QueryClause['value'], value: unknown): unknown {\n switch (shape) {\n case 'object':\n return typeof value === 'string' ? parseJson(key, value) : value;\n case 'number':\n return Number(value);\n case 'boolean':\n return value === true || value === 'true';\n case 'string':\n // A cursor arrives as the exact text a page handed out, never as JSON, so any other value is not a cursor.\n if (typeof value !== 'string') {\n throw new UqlUsageError(`'${key}' must be a cursor a page handed out`);\n }\n return value;\n }\n}\n\nfunction parseJson(key: string, text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new UqlUsageError(`invalid JSON in '${key}'`);\n }\n}\n\n/**\n * Serialize a UQL query object into a percent-encoded query string where object values\n * are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.\n */\nexport function stringifyQuery(query?: Record<string, unknown>): string {\n if (!query) {\n return '';\n }\n const params = new URLSearchParams();\n for (const key of getKeys(query)) {\n const value = query[key];\n if (value === undefined) {\n continue;\n }\n params.append(key, typeof value === 'object' && value !== null ? wireJson(value) : String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\n/**\n * What leaves the browser, as JSON, refusing what JSON keeps nothing of rather than letting the server\n * build a statement around the remains. A `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",
@@ -123,6 +123,11 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
123
123
  readonly maxFunctionArgs: number;
124
124
  getBeginTransactionStatements(isolationLevel?: IsolationLevel): string[];
125
125
  createContext(options?: QueryContextOptions): QueryContext;
126
+ /** A statement as it is sent: the SQL `build` writes, or a `raw` renders, and the values it binds. */
127
+ compile(build: QueryBuildFn | QueryRaw): {
128
+ sql: string;
129
+ values: unknown[];
130
+ };
126
131
  /**
127
132
  * The SQL `build` writes, as text to embed rather than appended to `ctx`. It binds into `ctx`'s own values
128
133
  * and aliases, so `$n` placeholders number against the whole statement.
@@ -150,6 +150,17 @@ export class AbstractSqlDialect extends VectorSqlDialect {
150
150
  createContext(options = {}) {
151
151
  return new SqlQueryContext(this, [], undefined, options.inlineValues);
152
152
  }
153
+ /** A statement as it is sent: the SQL `build` writes, or a `raw` renders, and the values it binds. */
154
+ compile(build) {
155
+ const ctx = this.createContext();
156
+ if (build instanceof QueryRaw) {
157
+ this.getRawValue(ctx, { value: build });
158
+ }
159
+ else {
160
+ build(ctx);
161
+ }
162
+ return { sql: ctx.sql, values: ctx.values };
163
+ }
153
164
  /**
154
165
  * The SQL `build` writes, as text to embed rather than appended to `ctx`. It binds into `ctx`'s own values
155
166
  * and aliases, so `$n` placeholders number against the whole statement.
@@ -12,10 +12,7 @@ export type MigrationModuleOptions = {
12
12
  /** Indented body inside `async down` (including newlines). */
13
13
  downInner: string;
14
14
  };
15
- /**
16
- * One `await querier.run`...`` line, the SQL a template binding nothing, so its lines and quotes read as
17
- * written; a backslash, a backtick and a `${` are escaped.
18
- */
15
+ /** One `await querier.run`...`` line, its SQL as written. */
19
16
  export declare function emitSqlRunCall(sql: string): string;
20
17
  /** Indented `up`/`down` body: one `await querier.run`...`` per SQL string. */
21
18
  export declare function emitSqlRunCalls(statements: string[]): string;
@@ -1,10 +1,8 @@
1
1
  import { mongoCommandSource } from '../../mongodb/mongoCommand.js';
2
- /**
3
- * One `await querier.run`...`` line, the SQL a template binding nothing, so its lines and quotes read as
4
- * written; a backslash, a backtick and a `${` are escaped.
5
- */
2
+ import { templateOf } from './sourceLiteral.js';
3
+ /** One `await querier.run`...`` line, its SQL as written. */
6
4
  export function emitSqlRunCall(sql) {
7
- return /*ts*/ ` await querier.run\`${sql.replace(/[\\`]|\$\{/g, (char) => `\\${char}`)}\`;`;
5
+ return /*ts*/ ` await querier.run${templateOf(sql)};`;
8
6
  }
9
7
  /** Indented `up`/`down` body: one `await querier.run`...`` per SQL string. */
10
8
  export function emitSqlRunCalls(statements) {
@@ -9,8 +9,10 @@ export declare function quoted(text: string): string;
9
9
  /** `user.email`, or `user['first-name']` for a property name that is no identifier. */
10
10
  export declare function memberSource(param: string, property: string): string;
11
11
  /**
12
- * SQL as a `raw` tagged template. A database reprints an expression as arbitrary text, and exactly
13
- * three sequences can end or interpolate a template literal, so escaping those is the whole job.
14
- * Newlines need none, which keeps a multi-line expression readable in the generated entity.
12
+ * SQL as a template literal binding nothing. A database reprints an expression as arbitrary text, and
13
+ * exactly three sequences can end or interpolate a template, so escaping those is the whole job. Newlines
14
+ * need none, which keeps multi-line SQL readable in the generated file.
15
15
  */
16
+ export declare function templateOf(sql: string): string;
17
+ /** SQL as a `raw` tagged template. */
16
18
  export declare function rawTag(sql: string): string;
@@ -15,11 +15,14 @@ export function memberSource(param, property) {
15
15
  return isIdentifierName(property) ? `${param}.${property}` : `${param}[${quoted(property)}]`;
16
16
  }
17
17
  /**
18
- * SQL as a `raw` tagged template. A database reprints an expression as arbitrary text, and exactly
19
- * three sequences can end or interpolate a template literal, so escaping those is the whole job.
20
- * Newlines need none, which keeps a multi-line expression readable in the generated entity.
18
+ * SQL as a template literal binding nothing. A database reprints an expression as arbitrary text, and
19
+ * exactly three sequences can end or interpolate a template, so escaping those is the whole job. Newlines
20
+ * need none, which keeps multi-line SQL readable in the generated file.
21
21
  */
22
+ export function templateOf(sql) {
23
+ return `\`${sql.replace(/[\\`]|\$\{/g, (char) => `\\${char}`)}\``;
24
+ }
25
+ /** SQL as a `raw` tagged template. */
22
26
  export function rawTag(sql) {
23
- const escaped = sql.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
24
- return `raw\`${escaped}\``;
27
+ return `raw${templateOf(sql)}`;
25
28
  }
@@ -160,9 +160,7 @@ function uniqueColumns(indexes) {
160
160
  function createTableRowReader(querier) {
161
161
  const sent = new Map();
162
162
  return (sql) => {
163
- const ctx = querier.dialect.createContext();
164
- querier.dialect.getRawValue(ctx, { value: sql });
165
- const key = `${ctx.sql}\u0000${JSON.stringify(ctx.values)}`;
163
+ const key = JSON.stringify(querier.dialect.compile(sql));
166
164
  let rows = sent.get(key);
167
165
  if (!rows) {
168
166
  rows = querier.all(sql);
@@ -1,5 +1,5 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, PrimaryKey, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, RawValue, SavepointCommand, SqlQuerier, TransactionOptions, Type, UpdatePayload, QueryRaw } from '../type/index.js';
2
+ import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, PrimaryKey, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
3
3
  import type { BuildUpdateResultPayload } from '../util/sql.util.js';
4
4
  import { AbstractQuerier } from './abstractQuerier.js';
5
5
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
@@ -33,12 +33,8 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
33
33
  * caught for every SQL backend.
34
34
  */
35
35
  protected lazyConnect(): Promise<void>;
36
- all<T extends object = RawRow>(strings: TemplateStringsArray, ...values: RawValue[]): Promise<T[]>;
37
- all<T extends object = RawRow>(sql: QueryRaw): Promise<T[]>;
38
- run(strings: TemplateStringsArray, ...values: RawValue[]): Promise<QueryUpdateResult>;
39
- run(sql: QueryRaw): Promise<QueryUpdateResult>;
40
- /** How a statement handed to `all` or `run` writes itself into a context. */
41
- private rendering;
36
+ all<T extends object = RawRow>(...statement: SqlStatement): Promise<T[]>;
37
+ run(...statement: SqlStatement): Promise<QueryUpdateResult>;
42
38
  /** Refused before the driver fails it, or PGlite answers it and every read after it wrong. */
43
39
  private assertBindBudget;
44
40
  /** The rows of a statement the dialect builds. */
@@ -92,15 +92,10 @@ export class AbstractSqlQuerier extends AbstractQuerier {
92
92
  }
93
93
  }
94
94
  all(...statement) {
95
- return this.query(this.rendering(statement));
95
+ return this.query(statementOf(statement));
96
96
  }
97
97
  run(...statement) {
98
- return this.exec(this.rendering(statement));
99
- }
100
- /** How a statement handed to `all` or `run` writes itself into a context. */
101
- rendering(statement) {
102
- const sql = statementOf(statement);
103
- return (ctx) => this.dialect.getRawValue(ctx, { value: sql });
98
+ return this.exec(statementOf(statement));
104
99
  }
105
100
  /** Refused before the driver fails it, or PGlite answers it and every read after it wrong. */
106
101
  assertBindBudget(values) {
@@ -119,9 +114,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
119
114
  }
120
115
  /** Builds a statement and sends it on the connection, in turn, timed and its failure tagged with it. */
121
116
  async send(build, task) {
122
- const ctx = this.dialect.createContext();
123
- build(ctx);
124
- const { sql, values } = ctx;
117
+ const { sql, values } = this.dialect.compile(build);
125
118
  this.assertBindBudget(values);
126
119
  return this.serialize(async () => {
127
120
  await this.lazyConnect();
@@ -1,13 +1,11 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { QueryRaw, QueryUpdateResult, RawRow, RawValue, SqlQuerier, SqlQuerierPool } from '../type/index.js';
2
+ import type { QueryUpdateResult, RawRow, SqlQuerier, SqlQuerierPool, SqlStatement } from '../type/index.js';
3
3
  import { AbstractQuerierPool } from './abstractQuerierPool.js';
4
4
  /**
5
5
  * Base pool for SQL dialects; implements the raw-SQL surface of {@link SqlQuerierPool}, which owns
6
6
  * the connection-per-call semantics.
7
7
  */
8
8
  export declare abstract class AbstractSqlQuerierPool<Q extends SqlQuerier, D extends AbstractSqlDialect> extends AbstractQuerierPool<Q, D> implements SqlQuerierPool<Q, D> {
9
- all<T extends object = RawRow>(strings: TemplateStringsArray, ...values: RawValue[]): Promise<T[]>;
10
- all<T extends object = RawRow>(sql: QueryRaw): Promise<T[]>;
11
- run(strings: TemplateStringsArray, ...values: RawValue[]): Promise<QueryUpdateResult>;
12
- run(sql: QueryRaw): Promise<QueryUpdateResult>;
9
+ all<T extends object = RawRow>(...statement: SqlStatement): Promise<T[]>;
10
+ run(...statement: SqlStatement): Promise<QueryUpdateResult>;
13
11
  }
@@ -1,4 +1,3 @@
1
- import { statementOf } from '../util/raw.js';
2
1
  import { AbstractQuerierPool } from './abstractQuerierPool.js';
3
2
  /**
4
3
  * Base pool for SQL dialects; implements the raw-SQL surface of {@link SqlQuerierPool}, which owns
@@ -6,11 +5,9 @@ import { AbstractQuerierPool } from './abstractQuerierPool.js';
6
5
  */
7
6
  export class AbstractSqlQuerierPool extends AbstractQuerierPool {
8
7
  all(...statement) {
9
- const sql = statementOf(statement);
10
- return this.withQuerier((querier) => querier.all(sql));
8
+ return this.withQuerier((querier) => querier.all(...statement));
11
9
  }
12
10
  run(...statement) {
13
- const sql = statementOf(statement);
14
- return this.withQuerier((querier) => querier.run(sql));
11
+ return this.withQuerier((querier) => querier.run(...statement));
15
12
  }
16
13
  }
@@ -4,7 +4,7 @@ import type { FieldKey, HookEvent, RelationKey } from './entity.js';
4
4
  import type { LoggingOptions } from './logger.js';
5
5
  import type { NamingStrategy } from './namingStrategy.js';
6
6
  import type { QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult, ReturningResult, WriteOptions } from './query.js';
7
- import type { QueryRaw, RawValue } from './queryRaw.js';
7
+ import type { SqlStatement } from './queryRaw.js';
8
8
  import type { ProjectedQuery, ProjectedRead, ProjectedResult, UniversalQuerier } from './universalQuerier.js';
9
9
  import type { BooleanLike, RawRow, Type } from './utility.js';
10
10
  import type { QuerierRaw } from './wire.js';
@@ -105,11 +105,9 @@ export interface SqlQuerier extends Querier {
105
105
  * The rows a statement answers, written as a tag, `all<Row>`SELECT ... WHERE id = ${id}``, each interpolated
106
106
  * value bound, never spliced; or a `raw` built apart.
107
107
  */
108
- all<T extends object = RawRow>(strings: TemplateStringsArray, ...values: RawValue[]): Promise<T[]>;
109
- all<T extends object = RawRow>(sql: QueryRaw): Promise<T[]>;
108
+ all<T extends object = RawRow>(...statement: SqlStatement): Promise<T[]>;
110
109
  /** Runs a statement (INSERT, UPDATE, DELETE, DDL), written as a tag or a `raw`, each interpolated value bound. */
111
- run(strings: TemplateStringsArray, ...values: RawValue[]): Promise<QueryUpdateResult>;
112
- run(sql: QueryRaw): Promise<QueryUpdateResult>;
110
+ run(...statement: SqlStatement): Promise<QueryUpdateResult>;
113
111
  }
114
112
  /**
115
113
  * Type guard to check if a querier supports raw SQL execution
@@ -51,7 +51,10 @@ export declare class QueryRaw {
51
51
  * bind reads - see {@link constantSql}.
52
52
  */
53
53
  readonly [RAW_TEXT]?: string;
54
- constructor(value: QueryRawFn, alias?: string, text?: string);
54
+ constructor(value: QueryRawFn, { alias, text }?: {
55
+ readonly alias?: string;
56
+ readonly text?: string;
57
+ });
55
58
  /** The same expression under an alias, for a `$select` projection. */
56
59
  as(alias: string): QueryRaw;
57
60
  /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */
@@ -12,14 +12,14 @@ export class QueryRaw {
12
12
  * bind reads - see {@link constantSql}.
13
13
  */
14
14
  [RAW_TEXT];
15
- constructor(value, alias, text) {
15
+ constructor(value, { alias, text } = {}) {
16
16
  this[RAW_VALUE] = value;
17
17
  this[RAW_ALIAS] = alias;
18
18
  this[RAW_TEXT] = text;
19
19
  }
20
20
  /** The same expression under an alias, for a `$select` projection. */
21
21
  as(alias) {
22
- return new QueryRaw(this[RAW_VALUE], alias, this[RAW_TEXT]);
22
+ return new QueryRaw(this[RAW_VALUE], { alias, text: this[RAW_TEXT] });
23
23
  }
24
24
  /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */
25
25
  render(opts) {
package/dist/util/raw.js CHANGED
@@ -3,28 +3,31 @@ import { ColumnRef, QueryRaw, RAW_TEXT, RelationAggregate, TriggerWriteRaw, } fr
3
3
  import { aggregateOf, isInlinedExpression } from './field.util.js';
4
4
  import { entityName, hasKeys } from './object.util.js';
5
5
  import { UqlUsageError } from './uqlError.js';
6
- export function raw(value, ...rest) {
7
- if (!isTemplateStrings(value)) {
8
- return new QueryRaw(value);
6
+ export function raw(source, ...values) {
7
+ if (!isTemplateStrings(source)) {
8
+ return new QueryRaw(source);
9
9
  }
10
- if (rest.some((value) => value === undefined)) {
10
+ if (!values.length) {
11
+ return raw.text(source[0]);
12
+ }
13
+ if (values.some((value) => value === undefined)) {
11
14
  throw new UqlUsageError('a raw template interpolated undefined, which binds nothing: leave it out, or write null');
12
15
  }
13
16
  // Writes joined by whitespace alone are still only writes, so a set-based trigger narrows each one.
14
- const writes = rest.length > 0 && rest.every((v) => v instanceof TriggerWriteRaw) && value.every((part) => !part.trim());
17
+ const writes = values.every((value) => value instanceof TriggerWriteRaw) && source.every((part) => !part.trim());
15
18
  return new (writes ? TriggerWriteRaw : QueryRaw)((opts) => {
16
19
  const { ctx } = opts;
17
- ctx.append(value[0]);
18
- rest.forEach((interpolated, i) => {
19
- if (interpolated instanceof QueryRaw) {
20
- interpolated.render(opts);
20
+ ctx.append(source[0]);
21
+ values.forEach((value, i) => {
22
+ if (value instanceof QueryRaw) {
23
+ value.render(opts);
21
24
  }
22
25
  else {
23
- ctx.addValue(interpolated);
26
+ ctx.addValue(value);
24
27
  }
25
- ctx.append(value[i + 1]);
28
+ ctx.append(source[i + 1]);
26
29
  });
27
- }, undefined, rest.length === 0 ? value[0] : undefined);
30
+ });
28
31
  }
29
32
  /** `parts` one after another, `separator` between each, every part binding its own values: `raw.join(conditions, ' AND ')`. */
30
33
  raw.join = function join(parts, separator = ', ') {
@@ -37,14 +40,14 @@ raw.join = function join(parts, separator = ', ') {
37
40
  });
38
41
  });
39
42
  };
43
+ /** SQL held in a string, run as written, binding nothing: for trusted text only, never built from user input. */
44
+ raw.text = function text(sql) {
45
+ return new QueryRaw(() => sql, { text: sql });
46
+ };
40
47
  /** The statement `all` or `run` was handed: a tagged template's, or a `raw` built apart. */
41
48
  export function statementOf([sql, ...values]) {
42
49
  return sql instanceof QueryRaw ? sql : raw(sql, ...values);
43
50
  }
44
- /** SQL held in a string, run as written, binding nothing: for trusted text only, never built from user input. */
45
- raw.text = function text(sql) {
46
- return new QueryRaw(() => sql, undefined, sql);
47
- };
48
51
  /**
49
52
  * The SQL of a `raw` that names a constant, for a DDL clause with no dialect to render against and
50
53
  * nowhere to bind a value; `undefined` where it interpolates and so needs one.
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.100.1",
6
+ "version": "0.100.2",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=24"
@@ -141,7 +141,7 @@
141
141
  "@types/pg": "^8.23.1",
142
142
  "@types/ws": "^8.18.2",
143
143
  "better-sqlite3": "^13.0.3",
144
- "express": "^5.2.1",
144
+ "express": "^5.3.0",
145
145
  "mariadb": "^3.5.4",
146
146
  "mongodb": "^7.7.0",
147
147
  "mssql": "^12.7.4",