uql-orm 0.94.0 → 0.95.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/browser/uql-browser.min.js.map +2 -2
- package/dist/dialect/abstractSqlDialect.d.ts +2 -2
- package/dist/dialect/abstractSqlDialect.js +1 -1
- package/dist/dialect/mergeSqlDialect.d.ts +2 -2
- package/dist/dialect/mergeSqlDialect.js +1 -1
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
- package/dist/migrate/cli-config.d.ts +9 -0
- package/dist/migrate/cli-config.js +24 -6
- package/dist/migrate/cli.js +9 -2
- package/dist/migrate/ddl/defaultSql.js +3 -1
- package/dist/mongo/mongodbQuerier.d.ts +3 -3
- package/dist/mongo/mongodbQuerier.js +2 -3
- package/dist/mssql/mssqlDialect.d.ts +2 -2
- package/dist/mssql/mssqlDialect.js +2 -2
- package/dist/querier/abstractQuerier.d.ts +12 -12
- package/dist/querier/abstractQuerier.js +30 -16
- package/dist/querier/abstractSqlQuerier.d.ts +3 -3
- package/dist/querier/abstractSqlQuerier.js +8 -9
- package/dist/type/dialect.d.ts +3 -3
- package/dist/type/query.d.ts +1 -12
- package/dist/type/universalQuerier.d.ts +9 -5
- package/dist/util/triggerWrite.d.ts +3 -3
- package/dist/util/triggerWrite.js +2 -2
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +5 -2
package/README.md
CHANGED
|
@@ -101,6 +101,8 @@ npx uql-migrate generate:entities initial # diffs the entities against the dat
|
|
|
101
101
|
npx uql-migrate up # applies it
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
+
On Node, `npm i -D tsx`: Node's type stripping does not run decorators, and the CLI imports a TypeScript config through the project's `tsx`. Bun needs nothing.
|
|
105
|
+
|
|
104
106
|
### 3. Query on the server
|
|
105
107
|
|
|
106
108
|
```ts
|
|
@@ -196,6 +198,7 @@ Only the entities in `include` are served: a `$populate: { author: true }` here
|
|
|
196
198
|
- [Querying](https://uql-orm.dev/querying/querier) - operators, relations, aggregates, transactions
|
|
197
199
|
- [Entities](https://uql-orm.dev/entities/basic) - decorators, relations, hooks, or the decorator-free [imperative API](https://uql-orm.dev/entities/imperative)
|
|
198
200
|
- [Switching to UQL](https://uql-orm.dev/switching-to-uql) - coming from Prisma, Drizzle, TypeORM, or MikroORM
|
|
201
|
+
- [Examples](examples) - runnable apps on [Node](examples/node), [Bun](examples/bun), [Next.js](examples/nextjs) and [Cloudflare D1](examples/cloudflare-d1), each checked in CI
|
|
199
202
|
|
|
200
203
|
Using a coding agent? The package ships a [skill](skills/uql-orm/SKILL.md) for it, and every docs page is Markdown: [set it up](https://uql-orm.dev/ai-agents).
|
|
201
204
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"sources": ["../../src/browser/http/bus.ts", "../../src/type/query.ts", "../../src/type/queryRaw.ts", "../../src/util/object.util.ts", "../../src/util/uqlError.ts", "../../src/http/query.ts", "../../src/browser/http/http.ts", "../../src/util/string.util.ts", "../../src/http/contract.ts", "../../src/browser/querier/httpQuerier.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors = new Set<RequestCallback>();\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.add(cb);\n return (): void => {\n subscriptors.delete(cb);\n };\n}\n",
|
|
6
|
-
"import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n UpdatePayload,\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 * 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 * How an upsert treats a row its conflict paths find: by default it takes the payload, less those paths. `U` is\n * what a trigger's `upsertInto` narrows the update to.\n */\nexport type UpsertOptions<E, U = UpdatePayload<E>> = {\n /**\n * What such a row takes instead, as an update does, `{ uses: { $inc: 1 } }` counting; `{}` leaves it as it is,\n * inserting only where none is. The payload still inserts.\n */\n readonly update?: U;\n};\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",
|
|
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 * 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/** 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
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
|
"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 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 * @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",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"import { queryErrorKind } from '../querier/queryError.js';\nimport type { Type, UniversalQuerier } from '../type/index.js';\n// the specific util modules, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys } from '../util/object.util.js';\nimport { kebabCase } from '../util/string.util.js';\nimport type { QueryErrorKind } from '../util/uqlError.js';\n\ntype RouteShape = {\n readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly path: '' | `/${string}`;\n};\n\n/**\n * Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.\n * Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method\n * (or routing a non-existent one) is a compile error.\n */\nexport const CRUD_ROUTES = {\n findMany: { method: 'GET', path: '' },\n findManyPage: { method: 'GET', path: '/page' },\n findOne: { method: 'GET', path: '/one' },\n count: { method: 'GET', path: '/count' },\n findOneById: { method: 'GET', path: '/:id' },\n insertOne: { method: 'POST', path: '' },\n insertMany: { method: 'POST', path: '/many' },\n saveOne: { method: 'PUT', path: '' },\n saveMany: { method: 'PUT', path: '/many' },\n updateMany: { method: 'PATCH', path: '' },\n updateOneById: { method: 'PATCH', path: '/:id' },\n deleteOneById: { method: 'DELETE', path: '/:id' },\n deleteMany: { method: 'DELETE', path: '' },\n} as const satisfies Partial<Record<keyof UniversalQuerier, RouteShape>>;\n\nexport type CrudOperation = keyof typeof CRUD_ROUTES;\n\nexport type CrudRoute = (typeof CRUD_ROUTES)[CrudOperation];\n\n/**\n * `QUERY` (RFC 10008) is an alternate transport for the read operations: same semantics as the\n * GET routes, but the JSON query travels in the request body instead of the query string,\n * avoiding URL-length limits for large queries.\n */\nexport type HttpMethod = CrudRoute['method'] | 'QUERY';\n\nconst CRUD_OPS = getKeys(CRUD_ROUTES);\n\n// derived from CRUD_ROUTES (the literal-path GET routes) so the sub-paths live in exactly one place\nconst QUERY_READ_OPS: ReadonlyMap<string, CrudOperation> = new Map(\n CRUD_OPS.filter((op) => CRUD_ROUTES[op].method === 'GET' && CRUD_ROUTES[op].path !== '/:id').map((op) => [\n CRUD_ROUTES[op].path,\n op,\n ]),\n);\n\n/**\n * URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.\n */\nexport function entityPath<E>(entity: Type<E>): string {\n return kebabCase(entity.name);\n}\n\nexport type RouteMatch = {\n readonly op: CrudOperation;\n /**\n * the resolved transport method - differs from the op's canonical route method for QUERY.\n */\n readonly method: HttpMethod;\n readonly id?: string;\n};\n\n/**\n * Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.\n */\nexport function matchRoute(method: string, subPath: string | undefined): RouteMatch | undefined {\n const raw = method.toUpperCase();\n const literal = subPath === undefined ? '' : `/${subPath}`;\n if (raw === 'QUERY') {\n const op = QUERY_READ_OPS.get(literal);\n return op ? { op, method: 'QUERY' } : undefined;\n }\n // HEAD reads like GET per HTTP semantics; the server runtime omits the response body\n const verb = raw === 'HEAD' ? 'GET' : raw;\n let idOp: CrudOperation | undefined;\n for (const op of CRUD_OPS) {\n const route = CRUD_ROUTES[op];\n if (route.method !== verb) {\n continue;\n }\n if (route.path === literal) {\n return { op, method: route.method };\n }\n if (route.path === '/:id') {\n idOp = op;\n }\n }\n return idOp && subPath !== undefined ? { op: idOp, method: CRUD_ROUTES[idOp].method, id: subPath } : undefined;\n}\n\nexport type RequestErrorResponse = {\n readonly error: {\n readonly message: string;\n readonly code: number;\n };\n};\n\n/** Generic on purpose: a driver's constraint message names tables and constraints, and Postgres echoes the value. */\nconst CONSTRAINT_ERRORS: ReadonlyMap<QueryErrorKind | undefined, RequestErrorResponse['error']> = new Map([\n ['uniqueViolation', { message: 'Conflict', code: 409 }],\n ['foreignKeyViolation', { message: 'Conflict', code: 409 }],\n ['notNullViolation', { message: 'Bad Request', code: 400 }],\n ['checkViolation', { message: 'Bad Request', code: 400 }],\n]);\n\n/**\n * Map a thrown error to the wire error envelope. Honors a numeric `status` on the error\n * (e.g. hooks throwing 403), then a constraint violation (409/400), defaults to 500; `code` mirrors the HTTP status.\n */\nexport function toErrorResponse(err: unknown): { status: number; body: RequestErrorResponse } {\n const error =\n err instanceof Error && 'status' in err && typeof err.status === 'number'\n ? { message: err.message, code: err.status }\n : (CONSTRAINT_ERRORS.get(queryErrorKind(err)) ?? {\n message: err instanceof Error ? err.message : 'Internal Server Error',\n code: 500,\n });\n return { status: error.code, body: { error } };\n}\n",
|
|
14
14
|
"import { CRUD_ROUTES, entityPath, type HttpMethod } from '../../http/contract.js';\nimport { stringifyQuery } from '../../http/query.js';\nimport type { EntityId, SharedQuerier, Type } from '../../type/index.js';\nimport { isScalarId } from '../../util/object.util.js';\nimport { UqlUsageError } from '../../util/uqlError.js';\nimport { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';\nimport type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';\n\nexport type HttpQuerierDefaults = {\n /**\n * headers sent with every request from this instance, merged under per-call headers.\n * Create one instance per request (e.g. during SSR) to scope auth headers safely.\n */\n readonly headers?: Record<string, string>;\n /**\n * transport for read queries (findOne, findMany, findManyPage, count). 'QUERY' (RFC 10008) sends the\n * JSON query in the request body, avoiding URL-length limits for large queries; requires\n * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.\n */\n readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;\n /**\n * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same\n * option the server handler takes, so one map serves both. State it where the default cannot: a\n * build that minifies class names renames every route.\n */\n readonly entityPath?: (entity: Type<unknown>) => string;\n};\n\n/** The id as one path segment, refusing a composite key, which has no spelling in `/:id` yet. Callers are `async`. */\nfunction idSegment<E>(entity: Type<E>, id: EntityId<E>): string {\n if (!isScalarId(id)) {\n throw new UqlUsageError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);\n }\n return String(id);\n}\n\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n // Typed properties instead of methods, so each takes its signature from `ClientQuerier` rather than repeating it.\n readonly findOneById: ClientQuerier['findOneById'] = async (entity, id, q, opts) =>\n get(`${this.getBasePath(entity)}/${idSegment(entity, id)}${stringifyQuery(q)}`, this.buildOptions(opts));\n\n readonly findOne: ClientQuerier['findOne'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts);\n\n readonly findMany: SharedQuerier<'client', RequestFindOptions>['findMany'] = (entity, q, opts) =>\n this.read(this.getBasePath(entity), opts?.count ? { ...q, count: true } : q, opts);\n\n readonly findManyAndCount: SharedQuerier<'client', RequestFindOptions>['findManyAndCount'] = async (\n entity,\n q,\n opts,\n ) => {\n const response = await this.findMany(entity, q, { ...opts, count: true });\n if (typeof response.count !== 'number') {\n throw new TypeError('findManyAndCount response has an invalid count');\n }\n return { ...response, count: response.count };\n };\n\n readonly findManyPage: ClientQuerier['findManyPage'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findManyPage.path}`, q, opts);\n\n readonly count: ClientQuerier['count'] = (entity, q, opts) =>\n this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);\n\n /** The `count` route capped at one row, so existence needs no endpoint of its own. */\n readonly exists: ClientQuerier['exists'] = async (entity, q, opts) => {\n const res = await this.count(entity, { ...q, $limit: 1 }, opts);\n return { ...res, data: res.data > 0 };\n };\n\n readonly insertOne: ClientQuerier['insertOne'] = (entity, payload, opts) =>\n post(this.getBasePath(entity), payload, this.buildOptions(opts));\n\n readonly insertMany: ClientQuerier['insertMany'] = (entity, payload, opts) =>\n post(`${this.getBasePath(entity)}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts));\n\n readonly updateOneById: ClientQuerier['updateOneById'] = async (entity, id, payload, opts) =>\n patch(`${this.getBasePath(entity)}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));\n\n readonly updateMany: ClientQuerier['updateMany'] = (entity, q, payload, opts) =>\n patch(`${this.getBasePath(entity)}${stringifyQuery(q)}`, payload, this.buildOptions(opts));\n\n readonly saveOne: ClientQuerier['saveOne'] = (entity, payload, opts) =>\n put(this.getBasePath(entity), payload, this.buildOptions(opts));\n\n readonly saveMany: ClientQuerier['saveMany'] = (entity, payload, opts) =>\n put(`${this.getBasePath(entity)}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts));\n\n readonly deleteOneById: ClientQuerier['deleteOneById'] = async (entity, id, opts = {}) => {\n const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';\n return remove(`${this.getBasePath(entity)}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));\n };\n\n readonly deleteMany: ClientQuerier['deleteMany'] = (entity, q, opts = {}) =>\n remove(\n `${this.getBasePath(entity)}${stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q)}`,\n this.buildOptions(opts),\n );\n\n getBasePath<E>(entity: Type<E>) {\n return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;\n }\n\n protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions) {\n if (this.defaults.readMethod === 'QUERY') {\n return httpQuery<T>(path, q ?? {}, this.buildOptions(opts));\n }\n return get<T>(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));\n }\n\n protected buildOptions(opts?: RequestOptions): RequestOptions | undefined {\n if (!this.defaults.headers && !opts?.headers) {\n return opts;\n }\n return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };\n }\n}\n"
|
|
15
15
|
],
|
|
16
|
-
"mappings": "AAEA,IAAM,EAAe,IAAI,IAElB,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAElD,OADA,EAAa,IAAI,CAAE,EACZ,IAAY,CACjB,EAAa,OAAO,CAAE,
|
|
16
|
+
"mappings": "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",
|
|
17
17
|
"debugId": "71C42BC87B2991D864756E2164756E21",
|
|
18
18
|
"names": []
|
|
19
19
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ColumnFamily, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type JsonColumnType, type JsonUpdateOp, type Query, type QueryAggMap, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryExclude, type QueryGroupMap, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QueryRaw, type QueryRawFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type Type, type UpdatePayload
|
|
1
|
+
import { type ColumnFamily, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type JsonColumnType, type JsonUpdateOp, type Query, type QueryAggMap, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryExclude, type QueryGroupMap, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QueryRaw, type QueryRawFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type Type, type UpdatePayload } from '../type/index.js';
|
|
2
2
|
import { type SortDirection } from '../util/index.js';
|
|
3
3
|
import type { HydrateKind } from './hydrateColumn.js';
|
|
4
4
|
import { type JsonAccessMode, type JsonSlot } from './jsonSql.js';
|
|
@@ -517,7 +517,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
517
517
|
* `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`. The assignments are built before the insert
|
|
518
518
|
* fills `onInsert` columns, which must stay out of them, and their values bound after it, where a `?` reads them.
|
|
519
519
|
*/
|
|
520
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
520
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
|
|
521
521
|
/** What an upsert's assignments bind once per statement, beside its rows. */
|
|
522
522
|
upsertAssignmentBinds<E>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): number;
|
|
523
523
|
/** One more `RETURNING` item saying whether the row was created, where the engine can tell; else empty. */
|
|
@@ -1457,7 +1457,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1457
1457
|
* `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`. The assignments are built before the insert
|
|
1458
1458
|
* fills `onInsert` columns, which must stay out of them, and their values bound after it, where a `?` reads them.
|
|
1459
1459
|
*/
|
|
1460
|
-
upsert(ctx, entity, conflictPaths, payload,
|
|
1460
|
+
upsert(ctx, entity, conflictPaths, payload, update) {
|
|
1461
1461
|
const meta = getMeta(entity);
|
|
1462
1462
|
const updateCtx = this.upsertUpdateBindsInPlace ? ctx : this.createContext();
|
|
1463
1463
|
const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityMeta, QueryConflictPaths, QueryContext, QueryPager, TriggerRows, Type,
|
|
1
|
+
import type { EntityMeta, QueryConflictPaths, QueryContext, QueryPager, TriggerRows, Type, UpdatePayload } from '../type/index.js';
|
|
2
2
|
import { AbstractSqlDialect } from './abstractSqlDialect.js';
|
|
3
3
|
/** What SQL Server and Oracle share: paging and upsert spelled as the standard does. */
|
|
4
4
|
export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
|
|
@@ -12,7 +12,7 @@ export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
|
|
|
12
12
|
* assignments bind their values before the rows, though they follow them in the SQL; this works only because
|
|
13
13
|
* SQL Server numbers each placeholder (`@p1`).
|
|
14
14
|
*/
|
|
15
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
15
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
|
|
16
16
|
/** A trigger's upsert as a `MERGE` of the rows it was handed, `SELECT`ed off them as its source. */
|
|
17
17
|
protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, conflictPaths: QueryConflictPaths<E>, entries: readonly [string, unknown][], assignments: string, rows?: TriggerRows): void;
|
|
18
18
|
/**
|
|
@@ -25,7 +25,7 @@ export class MergeSqlDialect extends AbstractSqlDialect {
|
|
|
25
25
|
* assignments bind their values before the rows, though they follow them in the SQL; this works only because
|
|
26
26
|
* SQL Server numbers each placeholder (`@p1`).
|
|
27
27
|
*/
|
|
28
|
-
upsert(ctx, entity, conflictPaths, payload,
|
|
28
|
+
upsert(ctx, entity, conflictPaths, payload, update) {
|
|
29
29
|
const meta = getMeta(entity);
|
|
30
30
|
// Before the row source, which is what fills the payload's `onInsert` fields: a column that
|
|
31
31
|
// exists only there - the generated key, `createdAt` - must not join the update set, or a row
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type,
|
|
1
|
+
import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type, UpdatePayload } from '../type/index.js';
|
|
2
2
|
import { AbstractSqlDialect, type DerivedRelation, type RelationRows } from './abstractSqlDialect.js';
|
|
3
3
|
import { type JsonSlot } from './jsonSql.js';
|
|
4
4
|
/** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
|
|
@@ -28,7 +28,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
28
28
|
readonly sqlValues: SqlValues;
|
|
29
29
|
readonly insertIdSource: InsertIdSource;
|
|
30
30
|
/** `INSERT ... ON DUPLICATE KEY UPDATE`, the assignments bound after the insert, where a `?` reads them. */
|
|
31
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
31
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
|
|
32
32
|
protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, _conflictPaths: QueryConflictPaths<E>, entries: readonly [string, unknown][], assignments: string): void;
|
|
33
33
|
/**
|
|
34
34
|
* `insert` on a duplicate key: `ON DUPLICATE KEY UPDATE` with the new row named, or `INSERT IGNORE` where there
|
|
@@ -93,7 +93,7 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
93
93
|
// `innodb_autoinc_lock_mode` caveat on `buildUpdateResult` in `util/sql.util.ts`.
|
|
94
94
|
insertIdSource = 'firstId';
|
|
95
95
|
/** `INSERT ... ON DUPLICATE KEY UPDATE`, the assignments bound after the insert, where a `?` reads them. */
|
|
96
|
-
upsert(ctx, entity, conflictPaths, payload,
|
|
96
|
+
upsert(ctx, entity, conflictPaths, payload, update) {
|
|
97
97
|
const meta = getMeta(entity);
|
|
98
98
|
const updateCtx = this.createContext();
|
|
99
99
|
const assignments = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, update);
|
|
@@ -1,2 +1,11 @@
|
|
|
1
1
|
import type { Config } from '../type/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* The project's own `tsx/esm/api` where Node must load a TypeScript config: Node's type stripping runs
|
|
4
|
+
* no decorators, and Bun and Deno transform them natively. uql bundles no transpiler, so the project's
|
|
5
|
+
* loader reads the project's `tsconfig.json`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function tsxApiFor(path: string, versions: {
|
|
8
|
+
bun?: string;
|
|
9
|
+
deno?: string;
|
|
10
|
+
}): string | undefined;
|
|
2
11
|
export declare function loadConfig(customPath?: string): Promise<Config>;
|
|
@@ -1,18 +1,36 @@
|
|
|
1
1
|
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
2
3
|
import { resolve } from 'node:path';
|
|
3
4
|
import { pathToFileURL } from 'node:url';
|
|
4
5
|
import { UqlUsageError } from '../util/uqlError.js';
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
7
|
+
* The project's own `tsx/esm/api` where Node must load a TypeScript config: Node's type stripping runs
|
|
8
|
+
* no decorators, and Bun and Deno transform them natively. uql bundles no transpiler, so the project's
|
|
9
|
+
* loader reads the project's `tsconfig.json`.
|
|
8
10
|
*/
|
|
11
|
+
export function tsxApiFor(path, versions) {
|
|
12
|
+
if (!/\.[mc]?ts$/.test(path) || versions.bun || versions.deno) {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
return createRequire(path).resolve('tsx/esm/api');
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
9
22
|
async function importConfig(path) {
|
|
10
|
-
const
|
|
23
|
+
const url = pathToFileURL(path).href;
|
|
24
|
+
const tsxApi = tsxApiFor(path, process.versions);
|
|
25
|
+
const loading = tsxApi
|
|
26
|
+
? import(pathToFileURL(tsxApi).href).then((api) => api.tsImport(url, import.meta.url))
|
|
27
|
+
: import(url);
|
|
28
|
+
const mod = await loading.catch((cause) => {
|
|
11
29
|
throw new UqlUsageError(`Could not import ${path}: ${cause?.message}\n` +
|
|
12
30
|
'If it reaches entity classes, their decorators need a runtime that transforms TypeScript, not ' +
|
|
13
|
-
'just one that strips its types. Run the CLI with `bun`, or
|
|
14
|
-
'
|
|
15
|
-
})
|
|
31
|
+
'just one that strips its types. Run the CLI with `bun`, or install tsx (`npm i -D tsx`), which the ' +
|
|
32
|
+
'CLI uses when it finds one. See https://uql-orm.dev/migrations#running-the-cli', { cause });
|
|
33
|
+
});
|
|
16
34
|
return mod.default ?? mod;
|
|
17
35
|
}
|
|
18
36
|
export async function loadConfig(customPath) {
|
package/dist/migrate/cli.js
CHANGED
|
@@ -31,7 +31,8 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
31
31
|
const options = {
|
|
32
32
|
migrationsPath: config.migrationsPath ?? './migrations',
|
|
33
33
|
tableName: config.tableName,
|
|
34
|
-
|
|
34
|
+
// A dry run's stdout is the SQL alone, so what the migrator notes on the way goes to stderr.
|
|
35
|
+
logger: filteredArgs.includes('--dry-run') ? console.error : console.log,
|
|
35
36
|
entities: config.entities,
|
|
36
37
|
defaultForeignKeyAction: config.defaultForeignKeyAction,
|
|
37
38
|
};
|
|
@@ -199,9 +200,15 @@ export async function runSync(migrator, args, config) {
|
|
|
199
200
|
const safe = !args.includes('--unsafe');
|
|
200
201
|
const options = { force, safe, drop: !safe };
|
|
201
202
|
// Ahead of the warning and the run: `--dry-run` means the same whatever else was asked for, `--force` included.
|
|
203
|
+
// Its stdout is only SQL, so it can be appended to a migration file another tool applies.
|
|
202
204
|
if (args.includes('--dry-run')) {
|
|
203
205
|
const statements = await migrator.planSync(options);
|
|
204
|
-
|
|
206
|
+
if (statements.length) {
|
|
207
|
+
console.log(statements.join('\n'));
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
console.error('Schema is already in sync.');
|
|
211
|
+
}
|
|
205
212
|
return;
|
|
206
213
|
}
|
|
207
214
|
if (force) {
|
|
@@ -47,8 +47,10 @@ export function sameDefault(desired, current, dialect) {
|
|
|
47
47
|
reprinted(formatDefaultValue(want, dialect)) === reprinted(formatDefaultValue(have, dialect)));
|
|
48
48
|
}
|
|
49
49
|
// Compared as text, since a catalogue may report a number either as a number or as its text.
|
|
50
|
-
return writtenDefault(want) === writtenDefault(have);
|
|
50
|
+
return writtenDefault(storedLiteral(want, dialect)) === writtenDefault(storedLiteral(have, dialect));
|
|
51
51
|
}
|
|
52
|
+
/** A boolean as the engine stores it: the integer {@link defaultLiteral} writes where it has no booleans. */
|
|
53
|
+
const storedLiteral = (value, dialect) => typeof value === 'boolean' && dialect.booleanLiteral !== 'native' ? Number(value) : value;
|
|
52
54
|
/**
|
|
53
55
|
* Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
|
|
54
56
|
* compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Document, MongoClient } from 'mongodb';
|
|
2
2
|
import { AbstractQuerier } from '../querier/index.js';
|
|
3
|
-
import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload
|
|
3
|
+
import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
|
|
4
4
|
import type { MongoDialect } from './mongoDialect.js';
|
|
5
5
|
import type { MongoQuerier } from './mongoQuerier.js';
|
|
6
6
|
export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
|
|
@@ -61,12 +61,12 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
|
|
|
61
61
|
private upsertWithUpdate;
|
|
62
62
|
/** The id and whether it was created, read off the document a `findOneAndUpdate` upsert wrote. */
|
|
63
63
|
private upserted;
|
|
64
|
-
protected internalUpsertOne<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E,
|
|
64
|
+
protected internalUpsertOne<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, update?: UpdatePayload<E>): Promise<{
|
|
65
65
|
ids: (PrimaryKey | undefined)[];
|
|
66
66
|
changes: number;
|
|
67
67
|
created: boolean;
|
|
68
68
|
}>;
|
|
69
|
-
protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[],
|
|
69
|
+
protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<{
|
|
70
70
|
ids: (PrimaryKey | undefined)[];
|
|
71
71
|
changes: number;
|
|
72
72
|
} | {
|
|
@@ -188,7 +188,6 @@ export class MongodbQuerier extends AbstractQuerier {
|
|
|
188
188
|
for (let index = 0; index < rows.length; index++) {
|
|
189
189
|
rows[index][idKey] = ids[index];
|
|
190
190
|
}
|
|
191
|
-
await this.insertRelations(entity, rows);
|
|
192
191
|
});
|
|
193
192
|
}
|
|
194
193
|
async internalUpdateMany(entity, qm, payload, opts) {
|
|
@@ -241,7 +240,7 @@ export class MongodbQuerier extends AbstractQuerier {
|
|
|
241
240
|
// `updatedExisting` is false when a new document was inserted (upserted).
|
|
242
241
|
return { id, created: res.lastErrorObject?.['updatedExisting'] === false };
|
|
243
242
|
}
|
|
244
|
-
async internalUpsertOne(entity, conflictPaths, payload,
|
|
243
|
+
async internalUpsertOne(entity, conflictPaths, payload, update) {
|
|
245
244
|
refuseTriggers(entity);
|
|
246
245
|
if (update) {
|
|
247
246
|
const { id, created, changes } = await this.upsertWithUpdate(entity, conflictPaths, payload, update);
|
|
@@ -264,7 +263,7 @@ export class MongodbQuerier extends AbstractQuerier {
|
|
|
264
263
|
return { ids: [id], changes: id === undefined ? 0 : 1, created };
|
|
265
264
|
});
|
|
266
265
|
}
|
|
267
|
-
async internalUpsertMany(entity, conflictPaths, payload,
|
|
266
|
+
async internalUpsertMany(entity, conflictPaths, payload, update) {
|
|
268
267
|
refuseTriggers(entity);
|
|
269
268
|
if (update) {
|
|
270
269
|
const ids = [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type RelationRows } from '../dialect/abstractSqlDialect.js';
|
|
2
2
|
import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
|
|
3
3
|
import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
|
|
4
|
-
import type { EntityMeta, FieldOptions, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryPager, SqlDialectFeatures, SqlValues, TriggerRows, Type,
|
|
4
|
+
import type { EntityMeta, FieldOptions, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryPager, SqlDialectFeatures, SqlValues, TriggerRows, Type, UpdatePayload, VectorDistance, VectorMetric } from '../type/index.js';
|
|
5
5
|
/** Microsoft SQL Server 2017 and up. Identifiers are `"`-quoted, the ANSI spelling `tedious` enables. */
|
|
6
6
|
export declare class MsSqlDialect extends MergeSqlDialect {
|
|
7
7
|
#private;
|
|
@@ -74,7 +74,7 @@ export declare class MsSqlDialect extends MergeSqlDialect {
|
|
|
74
74
|
* carrying a trigger, and through a table it works whether one is there or not.
|
|
75
75
|
*/
|
|
76
76
|
returningId<E>(meta: EntityMeta<E>): string;
|
|
77
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
77
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
|
|
78
78
|
/**
|
|
79
79
|
* A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
|
|
80
80
|
* `OUTPUT` fills, typed as the id column is, and the read handing that back, uncounted so the batch
|
|
@@ -181,8 +181,8 @@ export class MsSqlDialect extends MergeSqlDialect {
|
|
|
181
181
|
const expression = this.returningIdExpression(meta);
|
|
182
182
|
return expression ? this.mergeReturning(expression) : '';
|
|
183
183
|
}
|
|
184
|
-
upsert(ctx, entity, conflictPaths, payload,
|
|
185
|
-
this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload,
|
|
184
|
+
upsert(ctx, entity, conflictPaths, payload, update) {
|
|
185
|
+
this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload, update));
|
|
186
186
|
}
|
|
187
187
|
/**
|
|
188
188
|
* A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AbstractDialect } from '../dialect/abstractDialect.js';
|
|
2
|
-
import type { CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, QueryUpdateResult, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdatePayload, UpdateWrite,
|
|
2
|
+
import type { CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, QueryUpdateResult, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdatePayload, UpdateWrite, WrittenId } from '../type/index.js';
|
|
3
3
|
import { LoggerWrapper } from '../util/index.js';
|
|
4
4
|
/** Base class for all database queriers. */
|
|
5
5
|
export declare abstract class AbstractQuerier implements Querier {
|
|
@@ -101,9 +101,9 @@ export declare abstract class AbstractQuerier implements Querier {
|
|
|
101
101
|
* same rows the statement wrote.
|
|
102
102
|
*/
|
|
103
103
|
insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
|
|
104
|
-
/** Fills and guards `rows`, then writes them: an insert, and the insert half of a
|
|
104
|
+
/** Fills and guards `rows`, then writes them and their relations: an insert, and the insert half of a read upsert. */
|
|
105
105
|
private insertRows;
|
|
106
|
-
/** Writes `rows`, and onto each one the key the database generated for it, where it can tell. */
|
|
106
|
+
/** Writes `rows`, its columns only, and onto each one the key the database generated for it, where it can tell. */
|
|
107
107
|
protected abstract internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
|
|
108
108
|
updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions): Promise<number>;
|
|
109
109
|
/** Settles the rows first where the update cascades, so a payload changing what `$where` reads still names them. */
|
|
@@ -139,16 +139,16 @@ export declare abstract class AbstractQuerier implements Querier {
|
|
|
139
139
|
*/
|
|
140
140
|
private unversionedUpdate;
|
|
141
141
|
/** Fires `beforeUpsert`/`afterUpsert`: which branch a row takes is the database's to decide, so neither the insert's nor the update's pair fits. */
|
|
142
|
-
upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>,
|
|
143
|
-
upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[],
|
|
142
|
+
upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>): Promise<QueryUpsertOneResult<E>>;
|
|
143
|
+
upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>): Promise<QueryUpsertManyResult<E>>;
|
|
144
144
|
/**
|
|
145
|
-
* An upsert
|
|
146
|
-
*
|
|
147
|
-
*
|
|
145
|
+
* An upsert as a read, then writes: the rows the conflict names are read through the filters, those found update
|
|
146
|
+
* as `updateMany` does and the rest insert, so either branch writes its relations and a guarded row stays its
|
|
147
|
+
* tenant's. A row inserted concurrently fails on its key. See architecture/security-filter-writes.md.
|
|
148
148
|
*/
|
|
149
|
-
private
|
|
150
|
-
protected abstract internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E,
|
|
151
|
-
protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[],
|
|
149
|
+
private readThenUpsert;
|
|
150
|
+
protected abstract internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, update?: UpdatePayload<E>): Promise<QueryUpdateResult>;
|
|
151
|
+
protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<QueryUpdateResult>;
|
|
152
152
|
deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions): Promise<number>;
|
|
153
153
|
/** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
|
|
154
154
|
deleteMany<E extends object>(q: QuerySearch<E> & {
|
|
@@ -165,7 +165,7 @@ export declare abstract class AbstractQuerier implements Querier {
|
|
|
165
165
|
*/
|
|
166
166
|
saveMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
|
|
167
167
|
/** Writes each inserted row's relations, one set of statements per relation whatever the number of rows. */
|
|
168
|
-
|
|
168
|
+
private insertRelations;
|
|
169
169
|
/** `EntityId` because a settled composite row is an object, which {@link childrenOf} reads each foreign key column out of. */
|
|
170
170
|
private deleteRelations;
|
|
171
171
|
/**
|
|
@@ -87,6 +87,15 @@ function assertLockableUpdate(meta, q, settles) {
|
|
|
87
87
|
function writtenIds(meta, rows) {
|
|
88
88
|
return rows.map((row) => (namesKey(meta, row) ? idOf(meta, row) : undefined));
|
|
89
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Whether an upsert has to read before it writes: `ON CONFLICT` updates a guarded row whatever tenant it belongs
|
|
92
|
+
* to, and writes no relation.
|
|
93
|
+
*/
|
|
94
|
+
function upsertsByReading(meta, rows, update) {
|
|
95
|
+
const relates = (payload) => filterPersistableRelationKeys(meta, payload, 'persist').length > 0;
|
|
96
|
+
return (securityConditions(meta).length > 0 ||
|
|
97
|
+
(relates(meta.relations) && (rows.some(relates) || (update !== undefined && relates(update)))));
|
|
98
|
+
}
|
|
90
99
|
/** What `ON CONFLICT` assigns a row it finds by default: the payload, less the columns it matched on. */
|
|
91
100
|
function conflictAssignments(row, conflictPaths) {
|
|
92
101
|
const assigned = { ...row };
|
|
@@ -305,12 +314,13 @@ export class AbstractQuerier {
|
|
|
305
314
|
return writtenIds(meta, rows);
|
|
306
315
|
});
|
|
307
316
|
}
|
|
308
|
-
/** Fills and guards `rows`, then writes them: an insert, and the insert half of a
|
|
317
|
+
/** Fills and guards `rows`, then writes them and their relations: an insert, and the insert half of a read upsert. */
|
|
309
318
|
async insertRows(entity, rows) {
|
|
310
319
|
const meta = getMeta(entity);
|
|
311
320
|
fillOnFields(meta, rows, 'onInsert');
|
|
312
321
|
guardWrite(meta, rows, 'insert');
|
|
313
322
|
await this.internalInsertMany(entity, rows);
|
|
323
|
+
await this.insertRelations(entity, rows);
|
|
314
324
|
}
|
|
315
325
|
async updateOneById(entity, id, payload, opts) {
|
|
316
326
|
assertIdValue(entity, id);
|
|
@@ -412,36 +422,37 @@ export class AbstractQuerier {
|
|
|
412
422
|
return this.hooked(entity, 'Update', [payload], ([row]) => this.updateRows(entity, q, row, opts, undefined));
|
|
413
423
|
}
|
|
414
424
|
/** Fires `beforeUpsert`/`afterUpsert`: which branch a row takes is the database's to decide, so neither the insert's nor the update's pair fits. */
|
|
415
|
-
async upsertOne(entity, conflictPaths, payload,
|
|
425
|
+
async upsertOne(entity, conflictPaths, payload, update) {
|
|
416
426
|
const meta = getMeta(entity);
|
|
417
427
|
assertUnversioned(meta, "'upsertOne'");
|
|
418
428
|
return this.hooked(entity, 'Upsert', [payload], async (rows) => {
|
|
419
|
-
const { ids, changes, created } =
|
|
420
|
-
? await this.
|
|
421
|
-
: await this.internalUpsertOne(entity, conflictPaths, rows[0],
|
|
429
|
+
const { ids, changes, created } = upsertsByReading(meta, rows, update)
|
|
430
|
+
? await this.readThenUpsert(entity, conflictPaths, rows, update)
|
|
431
|
+
: await this.internalUpsertOne(entity, conflictPaths, rows[0], update);
|
|
422
432
|
adoptReportedIds(meta, rows, ids);
|
|
423
433
|
const [id] = writtenIds(meta, rows);
|
|
424
434
|
return { id, changes, created };
|
|
425
435
|
});
|
|
426
436
|
}
|
|
427
|
-
async upsertMany(entity, conflictPaths, payload,
|
|
437
|
+
async upsertMany(entity, conflictPaths, payload, update) {
|
|
428
438
|
const meta = getMeta(entity);
|
|
429
439
|
assertUnversioned(meta, "'upsertMany'");
|
|
430
440
|
return this.hooked(entity, 'Upsert', payload, async (rows) => {
|
|
431
|
-
const { ids, changes } =
|
|
432
|
-
? await this.
|
|
433
|
-
: await this.internalUpsertMany(entity, conflictPaths, rows,
|
|
441
|
+
const { ids, changes } = upsertsByReading(meta, rows, update)
|
|
442
|
+
? await this.readThenUpsert(entity, conflictPaths, rows, update)
|
|
443
|
+
: await this.internalUpsertMany(entity, conflictPaths, rows, update);
|
|
434
444
|
adoptReportedIds(meta, rows, ids);
|
|
435
445
|
return { ids: writtenIds(meta, rows), changes };
|
|
436
446
|
});
|
|
437
447
|
}
|
|
438
448
|
/**
|
|
439
|
-
* An upsert
|
|
440
|
-
*
|
|
441
|
-
*
|
|
449
|
+
* An upsert as a read, then writes: the rows the conflict names are read through the filters, those found update
|
|
450
|
+
* as `updateMany` does and the rest insert, so either branch writes its relations and a guarded row stays its
|
|
451
|
+
* tenant's. A row inserted concurrently fails on its key. See architecture/security-filter-writes.md.
|
|
442
452
|
*/
|
|
443
|
-
async
|
|
444
|
-
|
|
453
|
+
async readThenUpsert(entity, conflictPaths, rows, update) {
|
|
454
|
+
const meta = getMeta(entity);
|
|
455
|
+
guardWrite(meta, rows, 'insert');
|
|
445
456
|
if (!rows.length) {
|
|
446
457
|
return { changes: 0 };
|
|
447
458
|
}
|
|
@@ -452,7 +463,10 @@ export class AbstractQuerier {
|
|
|
452
463
|
for (const [index, row] of rows.entries()) {
|
|
453
464
|
// An empty `update` leaves a found row as it is, as `DO NOTHING` does.
|
|
454
465
|
if (ids[index] !== undefined && (update === undefined || hasKeys(update))) {
|
|
455
|
-
|
|
466
|
+
const q = { $where: whereEach(keys, (key) => row[key]) };
|
|
467
|
+
// A copy each: the update fills its `onUpdate` fields into what it is handed.
|
|
468
|
+
const assigned = update ? { ...update } : conflictAssignments(row, conflictPaths);
|
|
469
|
+
changes += await this.updateRows(entity, q, assigned, undefined, undefined);
|
|
456
470
|
}
|
|
457
471
|
}
|
|
458
472
|
const inserts = rows.filter((_, index) => ids[index] === undefined);
|
|
@@ -464,7 +478,7 @@ export class AbstractQuerier {
|
|
|
464
478
|
// A found row's key is adopted by the caller; an inserted one carries the key its insert wrote.
|
|
465
479
|
return { changes, created, ids };
|
|
466
480
|
};
|
|
467
|
-
// One row
|
|
481
|
+
// One row writes as an insert or an update of it does, with no transaction of its own.
|
|
468
482
|
return rows.length === 1 ? write() : this.transaction(write);
|
|
469
483
|
}
|
|
470
484
|
async deleteOneById(entity, id, opts) {
|
|
@@ -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, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SqlQuerier, TransactionOptions, Type, UpdatePayload
|
|
2
|
+
import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SqlQuerier, 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 {
|
|
@@ -90,8 +90,8 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
|
|
|
90
90
|
protected internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
|
|
91
91
|
internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
|
|
92
92
|
internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
|
|
93
|
-
protected internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E,
|
|
94
|
-
protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[],
|
|
93
|
+
protected internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, update?: UpdatePayload<E>): Promise<QueryUpdateResult>;
|
|
94
|
+
protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<QueryUpdateResult>;
|
|
95
95
|
private runUpsert;
|
|
96
96
|
protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
|
|
97
97
|
get hasOpenTransaction(): boolean;
|
|
@@ -328,16 +328,15 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
328
328
|
}
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
|
-
await this.insertRelations(entity, rows);
|
|
332
331
|
}
|
|
333
332
|
async internalUpdateMany(entity, q, payload, opts) {
|
|
334
333
|
const { changes = 0 } = await this.exec((ctx) => this.dialect.update(ctx, entity, q, payload, opts));
|
|
335
334
|
return changes;
|
|
336
335
|
}
|
|
337
|
-
async internalUpsertOne(entity, conflictPaths, payload,
|
|
338
|
-
return this.internalUpsertMany(entity, conflictPaths, [payload],
|
|
336
|
+
async internalUpsertOne(entity, conflictPaths, payload, update) {
|
|
337
|
+
return this.internalUpsertMany(entity, conflictPaths, [payload], update);
|
|
339
338
|
}
|
|
340
|
-
async internalUpsertMany(entity, conflictPaths, payload,
|
|
339
|
+
async internalUpsertMany(entity, conflictPaths, payload, update) {
|
|
341
340
|
if (!payload?.length) {
|
|
342
341
|
return { changes: 0 };
|
|
343
342
|
}
|
|
@@ -348,11 +347,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
348
347
|
// they assign the same. No row cap: SQL Server upserts through a MERGE, whose source takes any number.
|
|
349
348
|
const statements = groupByInsertShape(meta, payload).flatMap((group) => {
|
|
350
349
|
const rows = group.map((index) => payload[index]);
|
|
351
|
-
const assigned = this.dialect.upsertAssignmentBinds(entity, conflictPaths, rows,
|
|
350
|
+
const assigned = this.dialect.upsertAssignmentBinds(entity, conflictPaths, rows, update);
|
|
352
351
|
return chunkWithinLimits(meta, payload, group, this.dialect.maxBindValues - assigned);
|
|
353
352
|
});
|
|
354
353
|
if (statements.length === 1) {
|
|
355
|
-
return this.runUpsert(entity, conflictPaths, payload,
|
|
354
|
+
return this.runUpsert(entity, conflictPaths, payload, update);
|
|
356
355
|
}
|
|
357
356
|
// An upsert's assignment list is the statement's, so rows of different shapes go in statements
|
|
358
357
|
// of their own, together in a transaction (`transaction` is re-entrant).
|
|
@@ -362,7 +361,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
362
361
|
// than it wrote places none.
|
|
363
362
|
const ids = new Array(payload.length);
|
|
364
363
|
for (const indexes of statements) {
|
|
365
|
-
const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]),
|
|
364
|
+
const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]), update);
|
|
366
365
|
changes += written;
|
|
367
366
|
if (reported?.length === indexes.length) {
|
|
368
367
|
for (let position = 0; position < indexes.length; position++) {
|
|
@@ -374,11 +373,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
374
373
|
return { changes, ids };
|
|
375
374
|
});
|
|
376
375
|
}
|
|
377
|
-
async runUpsert(entity, conflictPaths, payload,
|
|
376
|
+
async runUpsert(entity, conflictPaths, payload, update) {
|
|
378
377
|
const meta = getMeta(entity);
|
|
379
378
|
// Asked first: the statement fills an `onInsert` key into these rows whether it inserts them or not.
|
|
380
379
|
const unnamed = meta.ids.length === 1 && payload.some((row) => !namesKey(meta, row));
|
|
381
|
-
const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload,
|
|
380
|
+
const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload, update));
|
|
382
381
|
const ordered = payload.length === 1 ||
|
|
383
382
|
(this.dialect.insertIdSource === 'returning' && this.dialect.features.orderedUpsertReturning);
|
|
384
383
|
if (ordered && result.ids?.length === payload.length) {
|
package/dist/type/dialect.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EntityMeta, EntityPredicate, UpdatePayload } from './entity.js';
|
|
2
|
-
import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery
|
|
2
|
+
import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery } from './query.js';
|
|
3
3
|
import type { QueryAggMap, QueryAggregate, QueryAggregateOp, QueryGroupMap } from './queryAggregate.js';
|
|
4
4
|
import type { QueryRawRenderOptions } from './queryRaw.js';
|
|
5
5
|
import type { QueryWhere } from './queryWhere.js';
|
|
@@ -313,8 +313,8 @@ export interface SqlQueryDialect {
|
|
|
313
313
|
insert<E>(ctx: QueryContext, entity: Type<E>, payload: E | E[], opts?: QueryRenderOptions): void;
|
|
314
314
|
/** An update of the records the query matches. */
|
|
315
315
|
update<E>(ctx: QueryContext, entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryRenderOptions): void;
|
|
316
|
-
/** An upsert of one record or many by their conflict paths,
|
|
317
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
316
|
+
/** An upsert of one record or many by their conflict paths, a conflicting row taking `update` where given. */
|
|
317
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
|
|
318
318
|
/** A write in a trigger's body; `rows` are what a set-based engine's body reads, narrowed to the ones it fires for. */
|
|
319
319
|
triggerWrite(ctx: QueryContext, write: TriggerWrite, rows?: TriggerRows): void;
|
|
320
320
|
/** A delete of the records the query matches, a soft delete where the entity has one. */
|
package/dist/type/query.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey,
|
|
1
|
+
import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey, WrittenId } from './entity.js';
|
|
2
2
|
import type { QueryLock } from './queryLock.js';
|
|
3
3
|
import type { QueryRaw } from './queryRaw.js';
|
|
4
4
|
import type { QueryWhere } from './queryWhere.js';
|
|
@@ -447,17 +447,6 @@ Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E>
|
|
|
447
447
|
} : E;
|
|
448
448
|
/** The to-many relations a query populated, which come back as lists rather than as optional ones. */
|
|
449
449
|
type PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;
|
|
450
|
-
/**
|
|
451
|
-
* How an upsert treats a row its conflict paths find: by default it takes the payload, less those paths. `U` is
|
|
452
|
-
* what a trigger's `upsertInto` narrows the update to.
|
|
453
|
-
*/
|
|
454
|
-
export type UpsertOptions<E, U = UpdatePayload<E>> = {
|
|
455
|
-
/**
|
|
456
|
-
* What such a row takes instead, as an update does, `{ uses: { $inc: 1 } }` counting; `{}` leaves it as it is,
|
|
457
|
-
* inserting only where none is. The payload still inserts.
|
|
458
|
-
*/
|
|
459
|
-
readonly update?: U;
|
|
460
|
-
};
|
|
461
450
|
/** What upserting one row reports. `created` is only knowable for a single statement, so a batch has none. */
|
|
462
451
|
export type QueryUpsertOneResult<E> = {
|
|
463
452
|
readonly id?: WrittenId<E>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EntityId, EntityWrite, FieldKey, RelationKey, UpdateWrite, WrittenId } from './entity.js';
|
|
2
|
-
import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult,
|
|
2
|
+
import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult } from './query.js';
|
|
3
3
|
import type { QueryAggMap, QueryAggregate, QueryAggregateResult, QueryGroupMap } from './queryAggregate.js';
|
|
4
4
|
import type { Type } from './utility.js';
|
|
5
5
|
import type { QuerierCountedResult, QuerierRaw, QuerierResult, QuerierTransport } from './wire.js';
|
|
@@ -92,10 +92,14 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
|
|
|
92
92
|
* than a guess where it cannot: a batch naming some keys, or a key that is not `AUTO_INCREMENT`.
|
|
93
93
|
*/
|
|
94
94
|
insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
|
|
95
|
-
/**
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Insert or update a record by its conflict paths; resolves to its id and whether it was created. A conflicting
|
|
97
|
+
* row takes the payload less those paths, or `update` as `updateMany` takes one: `{ uses: { $inc: 1 } }` counts,
|
|
98
|
+
* and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
|
|
99
|
+
*/
|
|
100
|
+
upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>): Promise<QueryUpsertOneResult<E>>;
|
|
101
|
+
/** Insert or update records by their conflict paths, as `upsertOne` does; resolves to their ids in payload order. */
|
|
102
|
+
upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>): Promise<QueryUpsertManyResult<E>>;
|
|
99
103
|
/**
|
|
100
104
|
* insert or update a record.
|
|
101
105
|
* @param entity the entity to persist on
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type
|
|
1
|
+
import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type WritableKey, type WriteRow } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* A row inserted by a trigger's body, into any table: `insertInto(PostAudit, { postId: newRow.id })`.
|
|
4
4
|
* Each value is a literal or SQL, a row's ref most often, and every engine renders it, SQL Server's
|
|
@@ -7,9 +7,9 @@ import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type Trig
|
|
|
7
7
|
export declare function insertInto<E extends object>(entity: Type<E>, row: WriteRow<E>): QueryRaw;
|
|
8
8
|
/**
|
|
9
9
|
* A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
|
|
10
|
-
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, {
|
|
10
|
+
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { count: { $inc: 1 } })`.
|
|
11
11
|
*/
|
|
12
|
-
export declare function upsertInto<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>,
|
|
12
|
+
export declare function upsertInto<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>, update?: UpdatePayload<E, QueryRaw, WritableKey<E>, never>): QueryRaw;
|
|
13
13
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
|
14
14
|
export declare function updateTable<E extends object>(entity: Type<E>, q: {
|
|
15
15
|
readonly $where: EntityPredicate<E>;
|
|
@@ -9,9 +9,9 @@ export function insertInto(entity, row) {
|
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
11
|
* A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
|
|
12
|
-
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, {
|
|
12
|
+
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { count: { $inc: 1 } })`.
|
|
13
13
|
*/
|
|
14
|
-
export function upsertInto(entity, conflictPaths, row,
|
|
14
|
+
export function upsertInto(entity, conflictPaths, row, update) {
|
|
15
15
|
return written({ kind: 'upsert', entity, conflictPaths, row, update });
|
|
16
16
|
}
|
|
17
17
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
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.95.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=24"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -22,6 +22,8 @@ npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/
|
|
|
22
22
|
|
|
23
23
|
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard: never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`. In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
24
24
|
|
|
25
|
+
Node's type stripping runs no decorators: on Node, add `tsx` (`npm i -D tsx`), which `uql-migrate` imports `uql.config.ts` through. Next.js compiles TC39 decorators only through a `babel.config.json` with `@babel/plugin-proposal-decorators` at `version: '2023-11'`. A bundle that minifies class names (Next's server build, or any bundler's `minify`) needs `@Entity({ name: 'todo' })`: a table name is the class name otherwise.
|
|
26
|
+
|
|
25
27
|
```ts
|
|
26
28
|
// uql.config.ts
|
|
27
29
|
import type { Config } from 'uql-orm';
|
|
@@ -108,7 +110,7 @@ const users = await pool.findMany(User, {
|
|
|
108
110
|
- `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
|
|
109
111
|
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`, whose handler serves only the entities its required `include` names.
|
|
110
112
|
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first.
|
|
111
|
-
- `upsertOne(Entity, { email: true }, row,
|
|
113
|
+
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update's payload with its operators (`{ uses: { $inc: 1 } }`), instead of `row`; a new one inserts `row`. An empty `{}` leaves a conflicting row as it is: insert if absent. Cascaded relations write on either branch, a found row's replaced, as `updateMany` does.
|
|
112
114
|
- `updateMany` and `deleteMany` naming no rows - no `$where` holding a value (an `undefined` or an empty group holds none), no `$limit` - throw; `{ unfiltered: true }` means the whole table.
|
|
113
115
|
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0, so a guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. On SQL the step may be a ref or `raw` of the field's type (`{ total: { $inc: newRow.amount } }` in a trigger). JSON fields take `$set`, `$unset`, `$push`, `$pull`.
|
|
114
116
|
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
|
|
@@ -132,13 +134,14 @@ A `findManyStream` holds its querier until the loop ends, which refuses any othe
|
|
|
132
134
|
|
|
133
135
|
## Migrations
|
|
134
136
|
|
|
135
|
-
`npx uql-migrate` reads `uql.config.ts
|
|
137
|
+
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|
|
136
138
|
|
|
137
139
|
- `sync` applies what the entities imply (development only).
|
|
138
140
|
- `generate:entities` writes the diff as a migration file to review. It renames a column whose field was renamed and refuses a required column with no default on a table holding rows.
|
|
139
141
|
- `up` and `down` apply and revert migrations.
|
|
140
142
|
- `generate:from-db` writes entity classes from an existing database.
|
|
141
143
|
- `drift:check` fails when the database no longer matches.
|
|
144
|
+
- `sync --dry-run` prints only SQL on stdout, to append to a migration file another tool applies: on Cloudflare D1, wrangler's (https://uql-orm.dev/cloudflare-d1.md).
|
|
142
145
|
|
|
143
146
|
Triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
|
|
144
147
|
|