uql-orm 0.110.0 → 0.111.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +3 -3
  2. package/dist/browser/uql-browser.min.js.map +1 -1
  3. package/dist/bunSql/bunSqlQuerier.d.ts +2 -5
  4. package/dist/d1/d1Querier.d.ts +1 -2
  5. package/dist/d1/d1Querier.js +0 -2
  6. package/dist/dialect/abstractSqlDialect.js +2 -2
  7. package/dist/dialect/aliases.d.ts +2 -0
  8. package/dist/dialect/aliases.js +2 -0
  9. package/dist/entity/columnOptionsBuilder.d.ts +1 -1
  10. package/dist/entity/columnOptionsBuilder.js +2 -2
  11. package/dist/entity/decorator/members.d.ts +15 -6
  12. package/dist/entity/metadata/definedFixture/animal.d.ts +4 -0
  13. package/dist/entity/metadata/definedFixture/animal.js +1 -1
  14. package/dist/entity/metadata/definedFixture/author.d.ts +4 -0
  15. package/dist/entity/metadata/definedFixture/author.js +1 -1
  16. package/dist/entity/metadata/definedFixture/book.d.ts +5 -0
  17. package/dist/entity/metadata/definedFixture/book.js +1 -1
  18. package/dist/entity/metadata/definition.d.ts +0 -2
  19. package/dist/entity/metadata/definition.js +3 -8
  20. package/dist/mariadb/mariadbQuerier.d.ts +2 -4
  21. package/dist/migrate/builder/columnBuilder.js +2 -2
  22. package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
  23. package/dist/migrate/codegen/fieldOptionsSource.js +2 -13
  24. package/dist/migrate/schemaGenerator.d.ts +2 -2
  25. package/dist/migrate/schemaGenerator.js +9 -5
  26. package/dist/mongodb/mongodbQuerier.d.ts +1 -2
  27. package/dist/mongodb/mongodbQuerier.js +0 -2
  28. package/dist/mssql/mssqlQuerier.d.ts +2 -4
  29. package/dist/mysql/mysql2Querier.d.ts +2 -10
  30. package/dist/pglite/pgliteQuerier.d.ts +4 -7
  31. package/dist/pglite/pgliteQuerier.js +0 -2
  32. package/dist/postgres/pgQuerier.d.ts +2 -1
  33. package/dist/querier/abstractPoolQuerier.d.ts +1 -2
  34. package/dist/querier/abstractPoolQuerier.js +0 -2
  35. package/dist/querier/abstractQuerier.d.ts +5 -8
  36. package/dist/querier/abstractQuerier.js +8 -11
  37. package/dist/querier/abstractSqlQuerier.d.ts +9 -2
  38. package/dist/querier/abstractSqlQuerier.js +36 -4
  39. package/dist/schema/canonicalType.d.ts +3 -3
  40. package/dist/schema/canonicalType.js +9 -4
  41. package/dist/schema/declaredColumn.d.ts +2 -4
  42. package/dist/schema/declaredColumn.js +4 -5
  43. package/dist/schema/schemaASTBuilder.js +1 -2
  44. package/dist/sqlite/hranaQuerier.d.ts +1 -2
  45. package/dist/sqlite/hranaQuerier.js +0 -2
  46. package/dist/sqlite/sqliteQuerier.d.ts +3 -9
  47. package/dist/sqlite/sqliteQuerier.js +0 -2
  48. package/dist/turso/tursoSessionQuerier.d.ts +1 -2
  49. package/dist/turso/tursoSessionQuerier.js +0 -2
  50. package/dist/type/column.d.ts +4 -6
  51. package/dist/type/definedEntity.d.ts +1 -1
  52. package/dist/type/entity.d.ts +4 -5
  53. package/dist/type/querier.d.ts +2 -2
  54. package/dist/type/querierPool.d.ts +1 -1
  55. package/dist/type/query.d.ts +3 -1
  56. package/dist/type/universalQuerier.d.ts +2 -2
  57. package/dist/util/field.util.d.ts +1 -7
  58. package/dist/util/field.util.js +2 -12
  59. package/package.json +1 -1
  60. package/skills/uql-orm/SKILL.md +5 -5
package/README.md CHANGED
@@ -54,7 +54,7 @@ import { Entity, f, Field, ManyToOne, OneToMany } from 'uql-orm';
54
54
 
55
55
  @Entity()
56
56
  export class User {
57
- @Field(f.number().id())
57
+ @Field(f.number().autoIncrement())
58
58
  id?: number;
59
59
 
60
60
  @Field(f.string().unique())
@@ -66,7 +66,7 @@ export class User {
66
66
 
67
67
  @Entity()
68
68
  export class Post {
69
- @Field(f.number().id())
69
+ @Field(f.number().autoIncrement())
70
70
  id?: number;
71
71
 
72
72
  @Field(f.string())
@@ -91,7 +91,7 @@ import { defineEntity, f } from 'uql-orm';
91
91
  export const Post = defineEntity({
92
92
  name: 'Post',
93
93
  fields: {
94
- id: f.number().id(),
94
+ id: f.number().autoIncrement(),
95
95
  title: f.string(),
96
96
  likes: f.number().nullable(),
97
97
  authorId: f.number().nullable(),
@@ -3,7 +3,7 @@
3
3
  "sources": ["../../src/browser/http/bus.ts", "../../src/type/query.ts", "../../src/type/querySql.ts", "../../src/util/object.util.ts", "../../src/util/uqlError.ts", "../../src/http/query.ts", "../../src/browser/http/http.ts", "../../src/util/string.util.ts", "../../src/http/contract.ts", "../../src/browser/querier/httpQuerier.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors = new Set<RequestCallback>();\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.add(cb);\n return (): void => {\n subscriptors.delete(cb);\n };\n}\n",
6
- "import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n UpdateWrite,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/** The fields of a unique key an upsert finds a row by, `{ email: true }`, as `$select` names them. */\nexport type QueryConflictKeys<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * The rows an upsert writes: a row `$conflict`'s keys find, `{ email: true }`, takes `$update` where it matches `$where`,\n * as `updateMany` reads one, `{ status: ['done', 'failed'] }`, and stays as it is elsewhere; the rest insert. Without\n * `$update` a found row takes the payload less its key and `$conflict`'s; `$update: {}` keeps it as it is.\n */\nexport type QueryUpsert<E, Sql = QuerySql, U = UpdateWrite<E, Sql>> = QueryFilter<E, Sql> & {\n readonly $conflict: QueryConflictKeys<E>;\n readonly $update?: U;\n};\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * or `true` for every field a read returns, read in the same transaction after the write (before it, for a delete), so\n * they hold what the database filled. `W` is `true` for `returning: true`, and `boolean` for a map.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike, W = boolean> = {\n readonly returning?: QuerySelect<E, S, V> | W;\n};\n\n/** What each kind of write resolves to: its ids or its count where it reads nothing back, else the rows it reads. */\nexport type WriteResults<E, S, V, W = false> = [W] extends [true]\n ? ReturnedRows<Pick<E, FieldKey<E>>>\n : [W] extends [false]\n ? WrittenIds<E>\n : [S] extends [never]\n ? WrittenIds<E>\n : ReturnedRows<ReturnedRow<E, S, V>>;\n\ntype WrittenIds<E> = {\n readonly inserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n};\n\ntype ReturnedRows<R> = { readonly inserted: R; readonly affected: R | undefined; readonly affectedMany: R[] };\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
6
+ "import type {\n FieldKey,\n FieldKeyOf,\n JsonFieldPaths,\n MethodKey,\n RelationKey,\n RelationTarget,\n ToManyRelationKey,\n UpdateWrite,\n WrittenId,\n} from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QuerySql } from './querySql.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { QueryVectorQuery, QueryVectorSearch } from './vector.js';\n\nexport type QueryOptions = {\n /**\n * Toggle named entity filters for this query. `false` disables all filters;\n * `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.\n * Security filters cannot be disabled here.\n */\n filters?: false | Record<string, boolean>;\n /**\n * Delete only: physically remove rows instead of soft-deleting, ignoring the soft-delete filter so\n * already-deleted rows are removed too. No effect on entities without a soft-delete field.\n */\n hardDelete?: boolean;\n /**\n * `updateMany`/`deleteMany` only: address every row of the table on purpose. Without it a bulk write\n * that names none - no `$where` and no `$limit` - is refused, since a forgotten filter and the whole\n * table look alike. The entity's own filters never count as naming one.\n */\n unfiltered?: boolean;\n};\n\n/**\n * What a statement is rendered with, on top of the options its caller passed. Kept apart from\n * {@link QueryOptions} because that one is public - it is the third argument of every querier method -\n * and none of this is a caller's to set: an alias is the dialect's to choose and to spell.\n */\nexport type QueryRenderOptions = QueryOptions & {\n /** The alias columns are read off, escaped by the dialect unless {@link escapedPrefix} spells it. */\n prefix?: string;\n /**\n * The prefix already written out, for the one caller whose row is not an identifier: a trigger reads\n * `NEW.\"col\"`, where `NEW` is a record the engine declares, and quoting it names a table that is not\n * in scope. Defaults to {@link prefix} escaped.\n */\n escapedPrefix?: string;\n /** Whether to infer the alias where none is given. */\n autoPrefix?: boolean;\n};\n\n/**\n * Field selection - `{ name: true }` whitelists fields; relations go in `$populate`. Declared over\n * `F extends keyof E`, like every map keyed by an entity's members, so each key stays linked to its\n * property and an editor rename reaches it.\n */\nexport type QuerySelect<E, F extends keyof E = FieldKey<E>, V = BooleanLike> = {\n [K in F]?: V;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `sql()`\n * (e.g. ``[sql`*`, sql`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E, Sql = QuerySql> = QuerySelect<E> | readonly Sql[];\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E, Sql = QuerySql, R extends keyof E = RelationKey<E>> = {\n [K in R]?: BooleanLike | QueryPopulateRelationOptions<E[K], Sql>;\n};\n\n/**\n * The key a read carries its relation tallies under. One spelling for the type and the runtime that\n * fills it: they sit in different modules, so a drift would type-check and answer `undefined`.\n */\nexport const COUNT_RESULT_KEY = '_count';\n\n/**\n * How many rows each named relation holds per parent, `true` for all of them or a filter to narrow\n * which ones count: a correlated count in the read's own statement, so no related row is loaded. Comes\n * back under `_count`, which keeps it clear of a relation of the same name `$populate` filled.\n */\nexport type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {\n [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;\n};\n\n/** The fields of a unique key an upsert finds a row by, `{ email: true }`, as `$select` names them. */\nexport type QueryConflictKeys<E> = QuerySelect<E, FieldKey<E>, true>;\n\n/**\n * The rows an upsert writes: a row `$conflict`'s keys find, `{ email: true }`, takes `$update` where it matches `$where`,\n * as `updateMany` reads one, `{ status: ['done', 'failed'] }`, and stays as it is elsewhere; the rest insert. Without\n * `$update` a found row takes the payload less its key and `$conflict`'s; `$update: {}` keeps it as it is.\n */\nexport type QueryUpsert<E, Sql = QuerySql, U = UpdateWrite<E, Sql>> = QueryFilter<E, Sql> & {\n readonly $conflict: QueryConflictKeys<E>;\n readonly $update?: U;\n};\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V, Sql = QuerySql> =\n IsMany<V> extends true\n ? RelationQuery<RelationTarget<V>, Sql>\n : QueryUnique<RelationTarget<V>, Sql> & { $required?: boolean };\n\n/**\n * The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,\n * so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.\n */\nexport interface UqlContext {\n [key: string]: unknown;\n}\n\n/**\n * A filter's `$where` fragment: a plain fragment, or a function of the ambient {@link UqlContext}.\n * Return `undefined` when the condition can't resolve (see {@link FilterOptions.onMissing}).\n */\nexport type FilterWhere<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly where: FilterWhere<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\n} & (\n | {\n readonly security?: false;\n /** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */\n readonly onMissing?: FilterOnMissing;\n }\n | {\n /**\n * Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and\n * AND-merged so a client `$where` on the same field can't override it. It fails closed.\n */\n readonly security: true;\n readonly onMissing?: 'throw';\n }\n);\n\n/**\n * direction for the sort, and where nulls land in it.\n *\n * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,\n * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`\n * emulate it with a leading term, which no index can serve, which is why it is asked for and never\n * applied by default.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc' | QuerySortNullsDirection;\n\n/** A {@link QuerySortDirection} stating where nulls land. */\nexport type QuerySortNullsDirection = 'ascNullsFirst' | 'ascNullsLast' | 'descNullsFirst' | 'descNullsLast';\n\n/**\n * Accepted value for a field in `$sort` - either a direction or a vector similarity search.\n */\nexport type QuerySortValue = QuerySortDirection | QueryVectorSearch;\n\n/**\n * Ordering parents by how many rows a to-many relation holds - \"the ten users with the most posts\".\n * The tally is computed per parent as a correlated count, never by loading the rows.\n */\nexport type QuerySortByCount = {\n $count: QuerySortDirection;\n};\n\n/**\n * Ordering parents by the row of a to-many nearest a vector, per vector field: its distance is the\n * smallest of theirs. Nothing to `$project`, since no one row of the parent's answers under it. Never\n * where the target has no vector, since an empty map would admit any value at all.\n */\nexport type QuerySortByNearest<E> = [FieldKeyOf<E, readonly number[]>] extends [never]\n ? never\n : { [P in FieldKeyOf<E, readonly number[]>]?: QueryVectorQuery };\n\n/**\n * Ordering by relevance to the `$text` at the root of `$where`, in either direction as any key sorts. The\n * object form also answers it under the name `$project` gives it, most relevant first unless `$order` says.\n */\nexport type QuerySortByText = {\n $text?: QuerySortDirection | { readonly $project: string; readonly $order?: QuerySortDirection };\n};\n\n/**\n * A sort by fields, JSON paths, a to-one relation's fields, a to-many's `$count` or nearest row, a vector\n * distance, or - where `Root` says it sorts the queried entity itself, not a relation's rows - a `$text`\n * relevance or a distance it projects. One mapped type over the key sets: an intersection is checked once\n * per member, which made this the costliest.\n */\nexport type QuerySortMap<E, Root extends boolean = true, K extends keyof E = FieldKey<E> | RelationKey<E>> = {\n [P in K]?: P extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its size or nearest row.\n IsMany<E[P]> extends true\n ? QuerySortByCount | QuerySortByNearest<RelationTarget<E[P]>>\n : QuerySortMap<RelationTarget<E[P]>, false>\n : NonNullable<E[P]> extends readonly number[]\n ? Root extends true\n ? QuerySortValue\n : QuerySortDirection | QueryVectorQuery\n : QuerySortDirection;\n} & ([JsonFieldPaths<E>] extends [never] ? unknown : { [P in JsonFieldPaths<E>]?: QuerySortDirection }) &\n (Root extends true ? QuerySortByText : unknown);\n\n/**\n * pager options.\n */\nexport type QueryPager = {\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * Which rows a statement addresses.\n */\nexport type QueryFilter<E, Sql = QuerySql> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n};\n\n/**\n * A filter plus the page `count` takes. No `$sort`: ordering picks *which* rows a page holds, never\n * how many, so a count that accepted one would promise an influence it cannot have.\n */\nexport type QueryPage<E, Sql = QuerySql> = QueryFilter<E, Sql> & QueryPager;\n\n/**\n * A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the\n * rows they address with a SELECT first, so the page is portable rather than MySQL-only, and a\n * vector `$sort` is as valid here as on a read: it ranks the settle query's rows, which has the\n * projection list to hold the distance. `$lock` stays off these, declared on {@link Query} instead.\n */\nexport type QuerySearch<E, Sql = QuerySql> = QueryPage<E, Sql> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E, Sql = QuerySql> = {\n /**\n * field selection - `{ name: true }` whitelists fields, `{ body: false }` leaves fields out, or raw SQL\n * projections (``[sql`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * A map with a positive entry selects those alone. Keys a relation is assembled from (a joined row's primary\n * key, a to-many's foreign key) are read regardless, since leaving them out would leave the relation unfilled.\n */\n $select?: QuerySelectValue<E, Sql>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E, Sql>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E, Sql>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * Lock the rows this query returns, `SELECT ... FOR UPDATE`, inside an open transaction: outside one\n * it is refused, since the lock would drop before the rows are used. SQL only, and not the SQLite family.\n */\n $lock?: QueryLock;\n\n /**\n * How many candidates an ANN index explores before ranking a vector search, in that index's own units\n * (`hnsw.ef_search`, `numCandidates`...); ignored where the search is exact. Postgres needs a transaction.\n */\n $candidates?: number;\n\n // `$where`, `$skip` and `$limit` are declared here rather than intersected in from\n // {@link QueryFilter} and {@link QueryPager}: an assignability check against an intersection is\n // repeated per constituent, and every query in a consuming codebase pays that. The two shapes are\n // pinned together in `queryStatementClauses.test-d.ts` so the copies cannot drift.\n\n /**\n * filtering options.\n */\n $where?: QueryWhere<E, Sql>;\n\n /**\n * Index from where start the search\n */\n $skip?: number;\n\n /**\n * Max number of records to retrieve\n */\n $limit?: number;\n};\n\n/**\n * A {@link Query} as it travels as JSON, which a `sql` SQL fragment cannot: what the browser client takes,\n * and what an RPC contract (tRPC, oRPC, TanStack Start) declares as its input.\n */\nexport type WireQuery<E> = Query<E, never>;\n\n/**\n * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a\n * populated relation's own query, a `statement` clause only in the statement itself, and a `wire: false`\n * clause never over HTTP.\n */\nexport type QueryClause = {\n readonly value: 'object' | 'number' | 'boolean' | 'string';\n readonly scope: 'relation' | 'statement';\n readonly wire?: false;\n};\n\n/**\n * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It\n * must cover both types, so a clause added to either fails to compile until it is declared here.\n */\nexport const QUERY_CLAUSES = {\n $select: { value: 'object', scope: 'relation' },\n $populate: { value: 'object', scope: 'relation' },\n $where: { value: 'object', scope: 'relation' },\n $sort: { value: 'object', scope: 'relation' },\n $skip: { value: 'number', scope: 'relation' },\n $limit: { value: 'number', scope: 'relation' },\n $distinct: { value: 'boolean', scope: 'relation' },\n // Statement only: tallies are read for the statement's rows, never for a populated relation's.\n $count: { value: 'object', scope: 'statement' },\n // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.\n $candidates: { value: 'number', scope: 'statement' },\n // Each request commits on its own, so a lock taken over HTTP would be released before its response.\n $lock: { value: 'object', scope: 'statement', wire: false },\n // Statement only: keyset paging per parent of a populated relation is not supported.\n $after: { value: 'string', scope: 'statement' },\n $before: { value: 'string', scope: 'statement' },\n} as const satisfies { readonly [K in keyof Query<unknown> | keyof QueryKeyset<unknown>]-?: QueryClause };\n\ntype QueryClauseKey = keyof typeof QUERY_CLAUSES;\n\n/** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */\nexport type QueryClauseOf<Shape extends Partial<QueryClause>> = {\n [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;\n}[QueryClauseKey];\n\n/**\n * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime\n * check reads the same table, so the two cannot drift.\n */\nexport type RelationQuery<E = object, Sql = QuerySql> = Pick<Query<E, Sql>, QueryClauseOf<{ scope: 'relation' }>> & {\n $required?: boolean;\n};\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E, Sql = QuerySql> = Except<Query<E, Sql>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E, Sql = QuerySql> = Pick<QueryOne<E, Sql>, '$select' | '$populate' | '$where'>;\n\n/**\n * A query as a read captures it: `Q` is inferred from the literal, so the row sees every clause at every\n * depth, while the parameter is `Concrete` itself, so a typo'd key fails its excess-property check at any\n * depth too. A query assembled elsewhere, typed `Concrete`, captures nothing and reads the whole entity.\n */\nexport type Captured<Concrete, Q> = [Concrete] extends [Q] ? Q : Concrete;\n\n/**\n * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and\n * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.\n */\nexport type QueryKeyset<E, Sql = QuerySql> = Except<Query<E, Sql>, '$skip'> & {\n /** The page size, required here although `Query` leaves it optional. */\n $limit: number;\n /** A page's `endCursor`, to read the rows after it. */\n $after?: string;\n /** A page's `startCursor`, to read the rows before it. */\n $before?: string;\n};\n\n/**\n * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading\n * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,\n * `hasNextPage` backward), since checking for rows on that side would cost another statement.\n */\nexport type CursorPage<T> = {\n readonly items: T[];\n /** Pass as `$before` to read the page before this one. */\n readonly startCursor?: string;\n /** Pass as `$after` to read the page after this one. */\n readonly endCursor?: string;\n readonly hasNextPage: boolean;\n readonly hasPrevPage: boolean;\n};\n\n/**\n * A find's row: the entity narrowed to what the query `Q` projected and populated, at every depth, so\n * reading anything else does not compile, plus {@link SortProjections}. The entity itself where nothing\n * narrows it. A key union names a projection by hand.\n * @example `QueryFindResult<User, 'id' | 'name'>`, `QueryFindResult<User, typeof query>`\n */\nexport type QueryFindResult<E, Q = {}> = [Q] extends [PropertyKey] ? Pick<E, Q & keyof E> : FindRow<E, Q>;\n\n/** What a `$sort` projects, each a number under the name its `$project` gives. */\ntype SortProjections<Q> = Q extends { readonly $sort: { readonly [key: string]: infer V } }\n ? Projected<ProjectedName<V>>\n : unknown;\n\ntype ProjectedName<V> = V extends { readonly $project: infer N extends string } ? N : never;\n\ntype Projected<N extends string> = [N] extends [never] ? unknown : { readonly [K in N]: number };\n\n/** The clauses that shape a row; a query naming none of them reads the entity as it is. */\ntype ShapingQuery = { readonly $select: object } | { readonly $populate: object } | { readonly $count: object };\n\n/**\n * A row at any depth, as {@link QueryFindResult} without the key-union form. Every alias layer and\n * conditional from here down is paid on each read, measured with `bun run ts.perf`: the shaping is\n * written twice so a read with no `$sort` skips the projections, cheaper than an alias over it.\n */\ntype FindRow<E, Q> = Q extends { readonly $sort: object }\n ? (Q extends ShapingQuery ? ShapedRow<E, Q> : DataRow<E>) & SortProjections<Q>\n : Q extends ShapingQuery\n ? ShapedRow<E, Q>\n : DataRow<E>;\n\n/**\n * The entity as a row reads it: plain data, so a method of the class it is read through is `never` and does not\n * compile. Still an `E`, which generic code returning or indexing its rows relies on.\n */\ntype DataRow<E> = E & MethodMask<E>;\n\n/** Each method of `E` as `never`, built once per entity and laid over any row read off it. */\ntype MethodMask<E, M extends keyof E = MethodKey<E>> = [M] extends [never] ? unknown : { readonly [K in M]: never };\n\n/**\n * The row's own fields, and its relations beside them. A positive `$select` entry wins outright at runtime, so a\n * map with one selects its positive keys alone; one with none leaves its keys out. `Pick`,\n * not a key remap: an entity keyed by an index signature, a content type defined at runtime, has `string` for its\n * keys, which a remap drops.\n */\ntype ShapedRow<E, Q> = Q extends { readonly $select: infer M }\n ? (M extends readonly unknown[]\n ? WholeRow<E, Q>\n : M[keyof M] extends true | 1\n ? Pick<E, ([keyof M] extends [never] ? FieldKey<E> : keyof M) & keyof E>\n : M[keyof M] extends Off\n ? Pick<E, Exclude<FieldKey<E>, keyof M> & keyof E>\n : Pick<E, OnKeys<M> & keyof E> & MaybeFields<E, M>) &\n RelatedRows<E, Q>\n : WholeRow<E, Q> & RelatedRows<E, Q>;\n\ntype Off = false | 0 | undefined;\n\n/** The keys of a clause's map whose entry asks for something. */\ntype OnKeys<M> = { [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? K : never }[keyof M];\n\n/** The keys whose entry may or may not ask, a `boolean`: what they name may be absent. */\ntype MaybeKeys<M> = {\n [K in keyof M]-?: [Extract<M[K], Off>] extends [never] ? never : M[K] extends Off ? never : K;\n}[keyof M];\n\n/** The fields a `boolean` entry names, each possibly absent; inert where every entry is literal. */\ntype MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick<E, MaybeKeys<M> & keyof E>>;\n\n/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */\ntype WholeRow<E, Q> = Q extends { readonly $populate: infer M }\n ? Except<E, keyof M & keyof E> & MethodMask<E>\n : DataRow<E>;\n\n/** The populated relations, and the `_count` a query asked for. */\ntype RelatedRows<E, Q> = Q extends { readonly $populate: infer M }\n ? PopulatedRelations<E, M, keyof M & keyof E> & CountedRelations<E, Q>\n : CountedRelations<E, Q>;\n\n/**\n * Each populated relation as its own query shapes it, mapped over parameters constrained to `keyof E` so each\n * member stays linked to its declaration for a rename. A list is always there, empty where the parent has no\n * children, and so is a `$required` to-one; any other to-one may be absent, since a join can find no row.\n */\ntype PopulatedRelations<\n E,\n M,\n K extends keyof E,\n Present extends keyof E = PresentKeys<E, M, K>,\n Absent extends keyof E = Exclude<K, Present>,\n> = { [P in Present]-?: PopulatedRow<E[P], M[P & keyof M]> } & {\n [P in Absent]: PopulatedRow<E[P], M[P & keyof M]> | undefined;\n};\n\ntype PresentKeys<E, M, K extends keyof E> = {\n [P in K]: M[P & keyof M] extends true | 1 | object\n ? IsMany<E[P]> extends true\n ? P\n : M[P & keyof M] extends { readonly $required: true }\n ? P\n : never\n : never;\n}[K];\n\ntype PopulatedRow<V, O> =\n NonNullable<V> extends readonly (infer T)[]\n ? NonNullable<V> extends unknown[]\n ? FindRow<T, O>[]\n : readonly FindRow<T, O>[]\n : FindRow<NonNullable<V>, O>;\n\n/** The `_count` a query asked for, an inert intersection member where it asked for none. */\ntype CountedRelations<E, Q> = Q extends { readonly $count: infer M }\n ? { [K in typeof COUNT_RESULT_KEY]: Tallies<E, OnKeys<M> & keyof E, MaybeKeys<M> & keyof E> }\n : unknown;\n\n/**\n * Each tally a count, over parameters constrained to `keyof E` and naming `E[R]`, which is what keeps each key\n * linked to its relation for a rename: a template that never names `E[R]` loses it.\n */\ntype Tallies<E, On extends keyof E, Maybe extends keyof E> = { [R in On]-?: Tally<E[R]> } & {\n [R in Maybe]?: Tally<E[R]>;\n};\n\ntype Tally<_Relation> = number;\n\n/**\n * A write's options: `returning` projects each row it writes as `$select` projects a read, `{ id: true, createdAt: true }`,\n * or `true` for every field a read returns, read in the same transaction after the write (before it, for a delete), so\n * they hold what the database filled. `W` is `true` for `returning: true`, and `boolean` for a map.\n */\nexport type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike, W = boolean> = {\n readonly returning?: QuerySelect<E, S, V> | W;\n};\n\n/** What each kind of write resolves to: its ids or its count where it reads nothing back, else the rows it reads. */\nexport type WriteResults<E, S, V, W = false> = [W] extends [true]\n ? ReturnedRows<Pick<E, FieldKey<E>>>\n : [W] extends [false]\n ? WrittenIds<E>\n : [S] extends [never]\n ? WrittenIds<E>\n : ReturnedRows<ReturnedRow<E, S, V>>;\n\ntype WrittenIds<E> = {\n readonly inserted: NonNullable<WrittenId<E>>;\n readonly upserted: WrittenId<E> | undefined;\n readonly affected: number;\n readonly affectedMany: number;\n};\n\ntype ReturnedRows<R> = {\n readonly inserted: R;\n readonly upserted: R;\n readonly affected: R | undefined;\n readonly affectedMany: R[];\n};\n\n/**\n * The row `returning` reads back: its keys, every field but them where it subtracts, and where it mixes both, its\n * positive keys, which a key set cannot tell apart, so each may be absent. `NoInfer`: a write naming no `returning`\n * would otherwise infer `S` from the type its result is assigned to.\n */\ntype ReturnedRow<E, S, V> = [V] extends [true | 1]\n ? Pick<E, NoInfer<S> & keyof E>\n : [V] extends [false | 0]\n ? Pick<E, Exclude<FieldKey<E>, NoInfer<S>> & keyof E>\n : Partial<Pick<E, NoInfer<S> & keyof E>>;\n\n/**\n * result of an update operation, as the driver reports it - which is what `run` hands back, where\n * there is no entity to name the ids against. The `QueryUpsert*Result` pair is the entity-level shape.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the IDs the statement reported, in payload order, `undefined` where it reported none for that\n * row - a MongoDB upsert names only the documents it inserted. Exact on `'returning'` dialects;\n * inferred from the driver header on the others (see {@link InsertIdSource}), and absent\n * altogether when the header reports nothing.\n */\n ids?: (PrimaryKey | undefined)[];\n};\n",
7
7
  "import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';\nimport type { Scalar, AbstractType } from './utility.js';\n\n/** What a `sql` callback receives. See {@link QuerySqlFn}. */\nexport type QuerySqlRenderOptions = {\n /** The dialect rendering the SQL. */\n dialect: SqlQueryDialect;\n /** The alias of the table in scope, unescaped; empty where there is none. */\n prefix: string;\n /** {@link prefix} escaped, with its trailing dot. */\n escapedPrefix: string;\n /** The query context the SQL is written into. */\n ctx: QueryContext;\n /**\n * The entity being rendered, which a ref read off a definition's map resolves its column against: a\n * computed field's own, or the one whose schema is built. Absent where a statement renders SQL.\n */\n entity?: AbstractType<unknown>;\n /**\n * The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and\n * outside a trigger.\n */\n rows?: TriggerRows;\n};\n\n/** {@link QuerySqlRenderOptions} as the callers along the way fill them in, every one still optional. */\nexport type QuerySqlFnOptions = Partial<QuerySqlRenderOptions>;\n\n/**\n * A `sql` callback: write into `ctx`, or return a string or number to have it appended. Anything else\n * it returns is ignored, which is why the return type is `unknown` rather than `void | Scalar` - the\n * latter rejected `({ ctx }) => ctx.append(...)`, the form every computed field is written in, because\n * TypeScript's \"returning a value where void is expected\" allowance does not apply to a union.\n */\nexport type QuerySqlFn = (opts: QuerySqlRenderOptions) => unknown;\n\nexport const SQL_FN: unique symbol = Symbol('sqlFn');\nexport const RAW_ALIAS: unique symbol = Symbol('rawAlias');\nexport const SQL_TEXT: unique symbol = Symbol('sqlText');\n/** Keys the phantom a ref or an aggregate carries its value type in, which no value ever fills. */\nexport const SQL_VALUE_TYPE: unique symbol = Symbol('sqlValueType');\n/** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */\nexport const REF_KEY: unique symbol = Symbol('refKey');\n\n/** The entity a {@link ColumnRef} was read off, where it names one: a definition's refs name none. */\nexport const REF_ENTITY: unique symbol = Symbol('refEntity');\n/** The dotted path a {@link JsonPathRef} reads down its column's document. */\nexport const JSON_PATH: unique symbol = Symbol('jsonPath');\n/** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */\nexport const JSON_VALUE: unique symbol = Symbol('jsonValue');\n\n/**\n * What a `sql` template interpolates: a value it binds, a list of them (`= ANY(${ids})`), or SQL it renders in\n * place. Never `undefined`, which would bind nothing: leave it out, or interpolate `null`.\n */\nexport type SqlArg = Scalar | null | readonly (Scalar | null)[] | QuerySql;\n\n/** A statement as `all` and `run` take one: a tagged template's strings and values, or a `sql` built apart. */\nexport type SqlStatement = readonly [strings: TemplateStringsArray, ...values: SqlArg[]] | readonly [sql: QuerySql];\n\nexport class QuerySql {\n readonly [SQL_FN]: QuerySqlFn;\n readonly [RAW_ALIAS]?: string;\n /**\n * The SQL verbatim, set only where it is a constant: a template that interpolates nothing binds no\n * value and reads no column, so it needs no dialect to render. What a DDL clause with nowhere to\n * bind reads - see {@link constantSql}.\n */\n readonly [SQL_TEXT]?: string;\n\n constructor(value: QuerySqlFn, { alias, text }: { readonly alias?: string; readonly text?: string } = {}) {\n this[SQL_FN] = value;\n this[RAW_ALIAS] = alias;\n this[SQL_TEXT] = text;\n }\n\n /** The same expression under an alias, for a `$select` projection. */\n as(alias: string): QuerySql {\n return new QuerySql(this[SQL_FN], { alias, text: this[SQL_TEXT] });\n }\n}\n\n/** Writes `statement` into `opts.ctx`. The alias is the projection's to write, after the term. */\nexport function renderSql(statement: QuerySql, opts: QuerySqlRenderOptions): void {\n const emitted = statement[SQL_FN](opts);\n if (typeof emitted === 'string' || (typeof emitted === 'number' && !Number.isNaN(emitted))) {\n opts.ctx.append(String(emitted));\n }\n}\n\n/**\n * A field of an entity as SQL, read off `refs(Entity)` or a definition's refs: interpolated into `sql`, it\n * renders as the field's column. Its key is how an index tells a column from an expression, and `V`,\n * the field's type, is what a value slot checks it against: see {@link SqlFor}.\n */\nexport class ColumnRef<K extends string = string, V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n readonly [REF_KEY]: K;\n readonly #entity?: () => AbstractType<unknown>;\n\n /** `entity` is read when the ref is, so an entity declared after the ref resolves. */\n constructor(key: K, value: QuerySqlFn, entity?: () => AbstractType<unknown>) {\n super(value);\n this[REF_KEY] = key;\n this.#entity = entity;\n }\n\n get [REF_ENTITY](): AbstractType<unknown> | undefined {\n return this.#entity?.();\n }\n}\n\n/**\n * A path inside a JSON column, read off an index's refs as the `$where` key it is: `user.settings.theme`\n * for `'settings.theme'`. `V`, the value at the path, decides how the index has to read it.\n */\nexport class JsonPathRef<V = unknown> {\n declare readonly [JSON_VALUE]?: V;\n readonly [REF_KEY]: string;\n readonly [JSON_PATH]: string;\n\n constructor(key: string, path: string) {\n this[REF_KEY] = key;\n this[JSON_PATH] = path;\n }\n}\n\n/**\n * SQL where a value of type `V` goes: bare SQL, whose type is its author's to know, or a ref to a column\n * holding one, nullability aside. `Sql` is what the transport carries, so the wire's `never` stays one.\n */\nexport type SqlFor<Sql, V> = Sql & { readonly [SQL_VALUE_TYPE]?: V | null };\n\n/**\n * A relation aggregate as SQL, read off a `computed` field's refs: `(user) => user.resources.count()`.\n * It renders as the correlated subquery a `$count` reads, so a field holding one is read, filtered and\n * sorted like any other.\n *\n * `V` is the value it reads, carried in a phantom field so the aggregate a field declares decides the\n * property's type.\n */\nexport class RelationAggregate<V = unknown> extends QuerySql {\n declare readonly [SQL_VALUE_TYPE]?: V;\n\n constructor(\n /** What it reads, kept beside the SQL so a read decodes the value the way the target's field does. */\n readonly spec: RelationAggregateSpec,\n value: QuerySqlFn,\n ) {\n super(value);\n }\n}\n\n/**\n * A write `insertInto`, `updateTable` or `deleteFrom` renders, or several joined in one `sql`. It reads a\n * set-based trigger's rows through {@link QuerySqlRenderOptions.rows}, which is how `of` and `where` narrow\n * them there; SQL of its own reads `inserted` and `deleted` whole.\n */\nexport class TriggerWriteSql extends QuerySql {}\n",
8
8
  "import type { EntityMeta, JsonScalar } from '../type/index.js';\n\n/** Whether `value` is a {@link JsonScalar}, which `$addToSet` and an `=` on a JSON path compare by equality. */\nexport function isJsonScalar(value: unknown): value is JsonScalar {\n return typeof value === 'string' || typeof value === 'boolean' || Number.isFinite(value);\n}\n\n/** Orders two strings by code unit, or two numbers by value, the order every engine sorts text by, so names and JSON keys agree across them. */\nexport function byCodeUnit<T extends string | number>(a: T, b: T): number {\n return a < b ? -1 : 1;\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n if (!(size >= 1)) {\n throw new RangeError(`a chunk holds at least one item, not ${size}`);\n }\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\n/** Whether `value` is a class, which an arrow, with no `prototype`, is not. */\nexport function isClass(value: unknown): boolean {\n return typeof value === 'function' && value.prototype !== undefined;\n}\n\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether `key` names an operator (`$eq`, `$push`...) rather than a field. */\nexport function isOperatorKey(key: string): boolean {\n return key.startsWith('$');\n}\n\n/** Whether `value` is a non-empty object with an operator key (`$eq`, `$push`...): the one test every dialect classifies with. */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether `value` is an object that is not an array, whose keys can be read. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** A shallow copy of `value` without `keys`. */\nexport function omitKeys<T extends object>(value: T, keys: Iterable<string>): T {\n const copy = { ...value };\n for (const key of keys) {\n Reflect.deleteProperty(copy, key);\n }\n return copy;\n}\n\n/** The value `cache` holds for `key`, computed and held the first time it is asked for. */\nexport function cachedIn<K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n compute: () => V,\n): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\nexport function getKeys<T extends object>(obj: T | null | undefined): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/** The entries of `record` holding a value: a key declared but left `undefined` is no entry at all. */\nexport function definedEntries<K extends string, V>(record: Partial<Record<K, V>>): [K, V][] {\n return (Object.entries(record) as [K, V | undefined][]).filter((entry): entry is [K, V] => entry[1] !== undefined);\n}\n\n/**\n * The entity's own name, declared or its class's. `meta.name` holds only what the author wrote, so\n * the fallback is what an entity that named no table is called - which is why the sites spelling this\n * out reached for three different fallbacks, `?? ''` among them, and named nothing at all.\n */\nexport function entityName<E>(meta: EntityMeta<E>): string {\n return meta.name ?? meta.entity.name;\n}\n\n/**\n * Whether `value` addresses a row by itself rather than naming columns: every primitive, and the\n * object ids a driver deals in (`ObjectId`, `Date`, bytes). Only a plain object names columns, which\n * is what a `$where` map and a composite key's id object both are; an array is a list of either.\n */\nexport function isScalarId(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return true;\n }\n if (Array.isArray(value)) {\n return false;\n }\n // `null` as well as `Object.prototype`: an object with no prototype is what a query-string parser\n // hands back (`qs`, express's `req.params`), and reading one as a bare id would name one column\n // with a map of several.\n const proto = Object.getPrototypeOf(value);\n return proto !== Object.prototype && proto !== null;\n}\n\n/** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */\nexport function isWhereMap(value: unknown): value is Record<string, unknown> {\n return !Array.isArray(value) && !isScalarId(value);\n}\n\n/** What `text` spells as JSON, or nothing where it is no JSON at all. */\nexport function jsonDocument(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n",
9
9
  "/**\n * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers\n * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization\n * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the\n * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.\n */\nexport type QueryErrorKind =\n | 'uniqueViolation'\n | 'foreignKeyViolation'\n | 'notNullViolation'\n | 'checkViolation'\n | 'optimisticLock'\n | 'retryable'\n | 'usage'\n | 'security';\n\n/** Every error UQL raises of its own: the kind `queryErrorKind` answers, and the status HTTP answers with. */\nexport abstract class UqlError extends Error {\n abstract readonly kind: QueryErrorKind;\n abstract readonly status: number;\n}\n\n/**\n * Thrown where the caller used the API in a way no statement can carry out: an update payload with no\n * version, a `$lock` outside a transaction, a method with no version to match. A `400` over HTTP: the\n * request is malformed, not the server's failure, and an untyped client is exactly who reaches this.\n */\nexport class UqlUsageError extends UqlError {\n override name = 'UqlUsageError';\n readonly kind = 'usage';\n readonly status = 400;\n}\n\n/**\n * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.\n * Fails the statement closed.\n */\nexport class UqlSecurityError extends UqlError {\n override name = 'UqlSecurityError';\n readonly kind = 'security';\n readonly status = 403;\n}\n\n/** What a value is, for a refusal naming what `/http` handed over instead of what the types require. */\nexport function kindOf(value: unknown): string {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Thrown when an update's `f.version()` column no longer matches the row: another writer moved it on,\n * or it is gone. `expected` is what the payload carried, `actual` what the row holds now, `undefined`\n * where there is no row left.\n */\nexport class UqlOptimisticLockError extends UqlError {\n override name = 'UqlOptimisticLockError';\n readonly kind = 'optimisticLock';\n readonly status = 409;\n\n constructor(\n message: string,\n readonly expected: unknown,\n readonly actual: unknown,\n ) {\n super(message);\n }\n}\n",
@@ -1,4 +1,5 @@
1
1
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
2
+ import type { SqlExecution } from '../util/sql.util.js';
2
3
  import { type BunSqlConn } from './bunSql.util.js';
3
4
  /**
4
5
  * A querier for `bun:sql` over a reserved connection, so raw SQL goes through `pool.sql` rather than
@@ -9,10 +10,6 @@ export declare class BunSqlQuerier extends AbstractPoolQuerier<BunSqlConn> {
9
10
  * Through `.unsafe()`, which takes the compiled text where Bun's tagged template would parse its own: safe, as
10
11
  * every value is bound.
11
12
  */
12
- protected execute(sql: string, values?: unknown[]): Promise<{
13
- rows: import("../index.js").RawRow[];
14
- changes: number | undefined;
15
- id: import("../index.js").PrimaryKey | undefined;
16
- }>;
13
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
17
14
  protected releaseConn(conn: BunSqlConn): Promise<void>;
18
15
  }
@@ -26,8 +26,7 @@ export interface D1Queryable {
26
26
  }
27
27
  export declare class D1Querier extends AbstractSqlQuerier {
28
28
  readonly db: D1Queryable;
29
- readonly extra?: ExtraOptions | undefined;
30
- constructor(db: D1Queryable, dialect: D1SqliteDialect, extra?: ExtraOptions | undefined);
29
+ constructor(db: D1Queryable, dialect: D1SqliteDialect, extra?: ExtraOptions);
31
30
  protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
32
31
  /** A list as one `batch()`, which D1 runs in order as one transaction: the one it has. */
33
32
  protected executeBatch(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
@@ -3,11 +3,9 @@ import { toBindValues } from '../sqlite/bindValues.js';
3
3
  import { UqlUsageError } from '../util/uqlError.js';
4
4
  export class D1Querier extends AbstractSqlQuerier {
5
5
  db;
6
- extra;
7
6
  constructor(db, dialect, extra) {
8
7
  super(dialect, extra);
9
8
  this.db = db;
10
- this.extra = extra;
11
9
  }
12
10
  async execute(sql, values) {
13
11
  return executionOf(await this.prepared(sql, values).all());
@@ -1,5 +1,5 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
- import { generatesKey, ownsSoleKey, valueFieldOf } from '../entity/metadata/definition.js';
2
+ import { generatesKey, valueFieldOf } from '../entity/metadata/definition.js';
3
3
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, REF_ENTITY, REF_KEY, ColumnRef, renderSql, RAW_ALIAS, } from '../type/index.js';
4
4
  import { utcTimestamp } from '../util/date.js';
5
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys, lacksValueOnInsert, } from '../util/field.util.js';
@@ -1472,7 +1472,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1472
1472
  if (write.kind === 'insert' || write.kind === 'upsert') {
1473
1473
  const [row] = fillOnFields(meta, { ...write.row }, 'onInsert', 'trigger');
1474
1474
  const unfilled = definedEntries(meta.fields)
1475
- .filter(([key, field]) => row[key] === undefined && lacksValueOnInsert(field, ownsSoleKey(meta, key)))
1475
+ .filter(([key, field]) => row[key] === undefined && lacksValueOnInsert(field))
1476
1476
  .map(([key]) => key);
1477
1477
  if (unfilled.length) {
1478
1478
  throw new UqlUsageError(`a trigger's insert into '${meta.name}' leaves out ${unfilled.map((key) => `'${key}'`).join(', ')}, ` +
@@ -33,6 +33,8 @@ export declare const JSON_SKIP_KEY = "_uql_skip";
33
33
  export declare const SAVEPOINT_PREFIX = "_uql_sp";
34
34
  /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
35
35
  export declare const CURSOR_ALIAS = "_uql_cursor";
36
+ /** The column reading a key's SQL default ahead of the insert writing it, where an engine reports only a generated key. */
37
+ export declare const KEY_DEFAULT_ALIAS = "_uql_key_default";
36
38
  /** The SQL Server table variable an `OUTPUT` fills. */
37
39
  export declare const OUTPUT_TABLE = "@_uql_output";
38
40
  /** What SQL Server's report of a write's rows reads {@link OUTPUT_TABLE} as, the table its fields are projected off. */
@@ -34,6 +34,8 @@ export const JSON_SKIP_KEY = `${OWNED_PREFIX}_skip`;
34
34
  export const SAVEPOINT_PREFIX = `${OWNED_PREFIX}_sp`;
35
35
  /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
36
36
  export const CURSOR_ALIAS = `${OWNED_PREFIX}_cursor`;
37
+ /** The column reading a key's SQL default ahead of the insert writing it, where an engine reports only a generated key. */
38
+ export const KEY_DEFAULT_ALIAS = `${OWNED_PREFIX}_key_default`;
37
39
  /** The SQL Server table variable an `OUTPUT` fills. */
38
40
  export const OUTPUT_TABLE = `@${OWNED_PREFIX}_output`;
39
41
  /** What SQL Server's report of a write's rows reads {@link OUTPUT_TABLE} as, the table its fields are projected off. */
@@ -28,7 +28,7 @@ export declare class ColumnOptionsBuilder {
28
28
  stored(events?: readonly StampEvent[]): ColumnOptionsBuilder;
29
29
  precision(precision: number): ColumnOptionsBuilder;
30
30
  scale(scale: number): ColumnOptionsBuilder;
31
- autoIncrement(autoIncrement?: boolean): ColumnOptionsBuilder;
31
+ autoIncrement(): ColumnOptionsBuilder;
32
32
  length(length: number): ColumnOptionsBuilder;
33
33
  dimensions(dimensions: number): ColumnOptionsBuilder;
34
34
  distance(distance: VectorDistance): ColumnOptionsBuilder;
@@ -68,8 +68,8 @@ export class ColumnOptionsBuilder {
68
68
  scale(scale) {
69
69
  return this.with({ scale });
70
70
  }
71
- autoIncrement(autoIncrement = true) {
72
- return this.with({ autoIncrement });
71
+ autoIncrement() {
72
+ return this.with({ isId: true, autoIncrement: true });
73
73
  }
74
74
  length(length) {
75
75
  return this.with({ length });
@@ -18,7 +18,7 @@ type MemberContext<O, P, N, M, Filled, Key, Lock> = ClassFieldDecoratorContext<O
18
18
  M
19
19
  ] extends [P] ? unknown : {
20
20
  readonly __propertyMustAdmit: M;
21
- }) & FilledIfBranded<O, N, Filled> & ([Key] extends [true] ? KeyIsNamed<O> : unknown) & ([Lock] extends [true] ? VersionIsBranded<O> : unknown);
21
+ }) & FilledIfBranded<O, N, Filled> & ([Key] extends [false] ? unknown : [Key] extends ['supplied'] ? KeyIsNamed<O> & KeyIsRequired<P> : KeyIsNamed<O>) & ([Lock] extends [true] ? VersionIsBranded<O> : unknown);
22
22
  /** An {@link AdmittingDecorator} for a column: its class is the decorator's own, and `K` is the key it references, `never` if none. */
23
23
  type ColumnDecorator<V, M, Filled, Key, Lock, K = never> = <This, P extends V | undefined, N extends PropertyKey>(value: undefined, context: MemberContext<This, P, N, M, Filled, Key, Lock> & PropertyHoldsKey<P, K>) => void;
24
24
  /** Refuses a property that does not hold the key a column references: a builder cannot say, a property brands what it does not. */
@@ -35,12 +35,12 @@ type FilledIfBranded<O, N, Filled> = [Filled] extends [true] ? unknown : typeof
35
35
  readonly __filledKeyNeedsADefault: true;
36
36
  } : unknown : unknown;
37
37
  /** What `Field` answers: a column's own checks, and that a property holds the key its column references. */
38
- type FieldDecorator<O, V> = ColumnDecorator<Narrowable<V> | NullOf<O>, NullOf<O>, O extends FilledOptions ? true : false, IsKey<O>, O extends {
38
+ type FieldDecorator<O, V> = ColumnDecorator<Narrowable<V> | NullOf<O>, NullOf<O>, O extends FilledOptions ? true : false, IsKey<O, V>, O extends {
39
39
  readonly version: true;
40
40
  } ? true : false, ReferencedKeyOf<O>>;
41
41
  /**
42
42
  * Declares a persisted field, the property checked against the column: `@Field(f.string()) name!: string;`, and
43
- * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().id()`.
43
+ * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().autoIncrement()`.
44
44
  * @example `@Field(f.references(() => User).nullable()) userId?: number | null;`
45
45
  */
46
46
  export declare function Field<O, V>(column: Column<O, V>): FieldDecorator<O, V>;
@@ -60,10 +60,15 @@ type ComputedValue<C> = C extends RelationAggregate<infer V> ? V : C extends Col
60
60
  type ComputedAdmits<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O> ? NullOf<O> : never;
61
61
  /** A JSON column with no schema holds any document, which the property narrows: `Json<Settings>`. */
62
62
  type Narrowable<V> = IsEqual<V, Json> extends true ? JsonBrand | readonly JsonBrand[] : V;
63
- /** Whether the column is a key, which the class has to name. */
64
- type IsKey<O> = O extends {
63
+ /**
64
+ * Whether the column is a key, which the class has to name, and `'supplied'` where no engine fills it: a text key is
65
+ * one MongoDB fills, which an entity cannot rule out.
66
+ */
67
+ type IsKey<O, V> = O extends {
65
68
  readonly isId: true;
66
- } ? true : false;
69
+ } ? O extends FilledOptions ? true : O extends {
70
+ readonly references: unknown;
71
+ } ? 'supplied' : [V] extends [number | bigint] ? 'supplied' : true : false;
67
72
  /**
68
73
  * A key the type level cannot name, reported on each key column that leaves it unnamed. Where no `idKey`
69
74
  * brand and no conventional name applies, `IdKey` falls back to every field, and `IdValue`,
@@ -72,6 +77,10 @@ type IsKey<O> = O extends {
72
77
  type KeyIsNamed<This> = [NamedIdKey<This>] extends [never] ? {
73
78
  readonly __keyNeedsIdKeyBrand: true;
74
79
  } : unknown;
80
+ /** A key nothing fills cannot be `?`, which would let an insert leave it out. */
81
+ type KeyIsRequired<P> = undefined extends P ? {
82
+ readonly __keyNothingFillsMustBeRequired: true;
83
+ } : unknown;
75
84
  /**
76
85
  * An optimistic lock the type level cannot see. `version: true` is what makes the column a lock at run
77
86
  * time; the `versionKey` brand is what makes an update payload require it, and a lock only half
@@ -6,6 +6,7 @@ export declare const Animal: import("../../../index.js").DefinedEntity<object &
6
6
  readonly type: NumberConstructor;
7
7
  } & {
8
8
  readonly isId: true;
9
+ readonly autoIncrement: true;
9
10
  }, number>;
10
11
  readonly name: import("../../../index.js").StringColumn<{
11
12
  readonly type: StringConstructor;
@@ -22,6 +23,7 @@ export declare const Dog: import("../../../index.js").DefinedEntity<import("../.
22
23
  readonly type: NumberConstructor;
23
24
  } & {
24
25
  readonly isId: true;
26
+ readonly autoIncrement: true;
25
27
  }, number>;
26
28
  readonly name: import("../../../index.js").StringColumn<{
27
29
  readonly type: StringConstructor;
@@ -42,6 +44,7 @@ export declare const Dog: import("../../../index.js").DefinedEntity<import("../.
42
44
  readonly type: NumberConstructor;
43
45
  } & {
44
46
  readonly isId: true;
47
+ readonly autoIncrement: true;
45
48
  }, number>;
46
49
  readonly name: import("../../../index.js").StringColumn<{
47
50
  readonly type: StringConstructor;
@@ -59,6 +62,7 @@ export declare const Dog: import("../../../index.js").DefinedEntity<import("../.
59
62
  readonly type: NumberConstructor;
60
63
  } & {
61
64
  readonly isId: true;
65
+ readonly autoIncrement: true;
62
66
  }, number>;
63
67
  readonly name: import("../../../index.js").StringColumn<{
64
68
  readonly type: StringConstructor;
@@ -2,6 +2,6 @@ import { f } from '../../column.js';
2
2
  import { defineEntity } from '../definition.js';
3
3
  export const Animal = defineEntity({
4
4
  name: 'Animal',
5
- fields: { id: f.number().id(), name: f.string() },
5
+ fields: { id: f.number().autoIncrement(), name: f.string() },
6
6
  });
7
7
  export const Dog = defineEntity({ name: 'Dog', extends: Animal, fields: { tricks: f.number().nullable() } });
@@ -9,6 +9,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
9
9
  readonly type: NumberConstructor;
10
10
  } & {
11
11
  readonly isId: true;
12
+ readonly autoIncrement: true;
12
13
  }, number>;
13
14
  readonly name: import("../../../index.js").StringColumn<{
14
15
  readonly type: StringConstructor;
@@ -36,6 +37,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
36
37
  readonly type: NumberConstructor;
37
38
  } & {
38
39
  readonly isId: true;
40
+ readonly autoIncrement: true;
39
41
  }, number>;
40
42
  readonly title: import("../../../index.js").StringColumn<{
41
43
  readonly type: StringConstructor;
@@ -70,6 +72,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
70
72
  readonly type: NumberConstructor;
71
73
  } & {
72
74
  readonly isId: true;
75
+ readonly autoIncrement: true;
73
76
  }, number>;
74
77
  readonly name: import("../../../index.js").StringColumn<{
75
78
  readonly type: StringConstructor;
@@ -98,6 +101,7 @@ export declare const Author: import("../../../index.js").RelatedEntity<object &
98
101
  readonly type: NumberConstructor;
99
102
  } & {
100
103
  readonly isId: true;
104
+ readonly autoIncrement: true;
101
105
  }, number>;
102
106
  readonly name: import("../../../index.js").StringColumn<{
103
107
  readonly type: StringConstructor;
@@ -5,7 +5,7 @@ import { Book } from './book.js';
5
5
  export const Author = defineEntity({
6
6
  name: 'Author',
7
7
  fields: {
8
- id: f.number().id(),
8
+ id: f.number().autoIncrement(),
9
9
  name: f.string(),
10
10
  bio: f.string().nullable(),
11
11
  createdAt: f.date().default(currentTimestamp),
@@ -10,6 +10,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
10
10
  readonly type: NumberConstructor;
11
11
  } & {
12
12
  readonly isId: true;
13
+ readonly autoIncrement: true;
13
14
  }, number>;
14
15
  readonly title: import("../../../index.js").StringColumn<{
15
16
  readonly type: StringConstructor;
@@ -44,6 +45,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
44
45
  readonly type: NumberConstructor;
45
46
  } & {
46
47
  readonly isId: true;
48
+ readonly autoIncrement: true;
47
49
  }, number>;
48
50
  readonly name: import("../../../index.js").StringColumn<{
49
51
  readonly type: StringConstructor;
@@ -71,6 +73,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
71
73
  readonly type: NumberConstructor;
72
74
  } & {
73
75
  readonly isId: true;
76
+ readonly autoIncrement: true;
74
77
  }, number>;
75
78
  readonly title: import("../../../index.js").StringColumn<{
76
79
  readonly type: StringConstructor;
@@ -117,6 +120,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
117
120
  readonly type: NumberConstructor;
118
121
  } & {
119
122
  readonly isId: true;
123
+ readonly autoIncrement: true;
120
124
  }, number>;
121
125
  readonly name: import("../../../index.js").StringColumn<{
122
126
  readonly type: StringConstructor;
@@ -144,6 +148,7 @@ export declare const Book: import("../../../index.js").DefinedClass<object & {
144
148
  readonly type: NumberConstructor;
145
149
  } & {
146
150
  readonly isId: true;
151
+ readonly autoIncrement: true;
147
152
  }, number>;
148
153
  readonly title: import("../../../index.js").StringColumn<{
149
154
  readonly type: StringConstructor;
@@ -5,7 +5,7 @@ import { Author } from './author.js';
5
5
  export const Book = defineEntity({
6
6
  name: 'Book',
7
7
  fields: {
8
- id: f.number().id(),
8
+ id: f.number().autoIncrement(),
9
9
  title: f.string(),
10
10
  stock: f.number().default(0),
11
11
  status: f.enum(['draft', 'published']),
@@ -80,8 +80,6 @@ export declare function foreignKeysOf<E>(meta: EntityMeta<E>): RelationMeta[];
80
80
  * extending another may join by other columns. Kept once resolved.
81
81
  */
82
82
  export declare function referenceKeys<E>(meta: EntityMeta<E>): ReadonlySet<string>;
83
- /** Whether `key` is `meta`'s whole primary key and its own, not the key of the row it references. */
84
- export declare function ownsSoleKey<E>(meta: EntityMeta<E>, key: string): boolean;
85
83
  /** Whether the database generates `meta`'s key on insert: the one answer every insert path reads. */
86
84
  export declare function generatesKey<E>(meta: EntityMeta<E>): boolean;
87
85
  export {};
@@ -1,5 +1,5 @@
1
1
  import { COLUMN_OPTIONS, REF_KEY, RelationAggregate, SECTION_ENTRY, SOFT_DELETE_FILTER, } from '../../type/index.js';
2
- import { aggregateField, defaultReadKeys, fieldKeys, isAutoIncrement, isInlinedExpression, } from '../../util/field.util.js';
2
+ import { aggregateField, defaultReadKeys, fieldKeys, isInlinedExpression } from '../../util/field.util.js';
3
3
  import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, isRecord, whereWith, } from '../../util/index.js';
4
4
  import { UqlUsageError } from '../../util/uqlError.js';
5
5
  import { ownRegistrations } from '../decorator/bag.js';
@@ -362,7 +362,7 @@ export function registerEntity(entity, opts = {}, members) {
362
362
  }
363
363
  const ids = getIdKeys(meta);
364
364
  if (!ids.length && !meta.abstract) {
365
- throw new UqlUsageError(`'${entity.name}' must have at least one id field (declare one with 'id()', as in 'f.number().id()')`);
365
+ throw new UqlUsageError(`'${entity.name}' must have at least one id field (declare one with '.autoIncrement()', which the database generates, or '.id()', which the caller supplies)`);
366
366
  }
367
367
  meta.ids = ids;
368
368
  metas.set(entity, meta);
@@ -714,14 +714,9 @@ export function referenceKeys(meta) {
714
714
  return references.filter(({ foreign }) => ids.some((id) => id === foreign)).map(({ local }) => local);
715
715
  })));
716
716
  }
717
- /** Whether `key` is `meta`'s whole primary key and its own, not the key of the row it references. */
718
- export function ownsSoleKey(meta, key) {
719
- return soleId(meta)?.key === key && !referenceKeys(meta).has(key);
720
- }
721
717
  /** Whether the database generates `meta`'s key on insert: the one answer every insert path reads. */
722
718
  export function generatesKey(meta) {
723
- const sole = soleId(meta);
724
- return !!sole && isAutoIncrement(sole.field, ownsSoleKey(meta, sole.key));
719
+ return soleId(meta)?.field.autoIncrement === true;
725
720
  }
726
721
  /** The kinds a column of `type` holds as a join compares them, as `HoldsKind` does: a bigint is a number, which BIGINT widens. */
727
722
  function joinedKinds(type) {
@@ -1,12 +1,10 @@
1
1
  import type { PoolConnection } from 'mariadb';
2
2
  import { AbstractPoolQuerier } from '../querier/abstractPoolQuerier.js';
3
3
  import type { RawRow } from '../type/index.js';
4
+ import type { SqlExecution } from '../util/sql.util.js';
4
5
  export declare class MariadbQuerier extends AbstractPoolQuerier<PoolConnection> {
5
6
  /** A read, or a `RETURNING` write, answers rows, counted by them; any other write an OK packet reporting `affectedRows`. */
6
- protected execute(sql: string, values?: unknown[]): Promise<{
7
- rows: RawRow[];
8
- changes: any;
9
- }>;
7
+ protected execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
10
8
  /**
11
9
  * Closed through the driver's own `close`, which `Readable` does not type: a loop leaving early only destroys
12
10
  * the stream, which leaves the socket paused mid-result and the connection hung for its next statement.
@@ -90,7 +90,7 @@ export class TableColumn {
90
90
  if (conflict) {
91
91
  throw new UqlUsageError(`'${this.#name}' ${conflict}`);
92
92
  }
93
- const column = declaredColumn(field, { name: this.#name, soleKey: false, compile: migrationSql });
93
+ const column = declaredColumn(field, { name: this.#name, compile: migrationSql });
94
94
  return {
95
95
  ...column,
96
96
  type: this.#unsigned ? { ...column.type, unsigned: true } : column.type,
@@ -104,7 +104,7 @@ export class TableColumn {
104
104
  export function tableColumns(add) {
105
105
  const named = (name, column) => add(new TableColumn(name, column));
106
106
  return {
107
- id: (name = 'id') => named(name, columns.bigint().id().autoIncrement()),
107
+ id: (name = 'id') => named(name, columns.bigint().autoIncrement()),
108
108
  integer: (name) => named(name, columns.column('int')),
109
109
  smallint: (name) => named(name, columns.column('smallint')),
110
110
  bigint: (name) => named(name, columns.bigint()),
@@ -248,6 +248,6 @@ function propertySource(col, propertyName) {
248
248
  if (col.nullable && !col.isPrimaryKey) {
249
249
  return `${written}${propertyName}?: ${type} | null`;
250
250
  }
251
- const filled = !col.isPrimaryKey && col.defaultValue !== undefined;
251
+ const filled = col.defaultValue !== undefined || col.isAutoIncrement;
252
252
  return `${written}${propertyName}${filled ? '?' : '!'}: ${type}`;
253
253
  }
@@ -1,7 +1,6 @@
1
1
  import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalType.js';
2
2
  import { SqlExpression } from '../../schema/sqlExpression.js';
3
3
  import { DATE_PRECISION } from '../../util/date.js';
4
- import { isAutoIncrement } from '../../util/field.util.js';
5
4
  import { jsonDocument } from '../../util/object.util.js';
6
5
  import { escapeSingleQuotes } from '../../util/sqlLiteral.js';
7
6
  import { quoted, sqlTag } from './sourceLiteral.js';
@@ -19,11 +18,8 @@ const METHOD_SOURCE = {
19
18
  ],
20
19
  // A column is NOT NULL unless it says otherwise; a key is a key, which holds no null.
21
20
  nullable: (col) => (col.nullable && !col.isPrimaryKey ? ['.nullable()'] : []),
22
- isPrimaryKey: (col) => (col.isPrimaryKey ? ['.id()'] : []),
23
- // Generates where `isAutoIncrement` says, which only a column the database treats otherwise contradicts.
24
- isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, ownsSoleKey(col)) === col.isAutoIncrement
25
- ? []
26
- : [col.isAutoIncrement ? '.autoIncrement()' : '.autoIncrement(false)'],
21
+ isPrimaryKey: (col) => (col.isPrimaryKey && !col.isAutoIncrement ? ['.id()'] : []),
22
+ isAutoIncrement: (col) => (col.isPrimaryKey && col.isAutoIncrement ? ['.autoIncrement()'] : []),
27
23
  isUnique: (col) => (col.isUnique ? ['.unique()'] : []),
28
24
  defaultValue: (col) => {
29
25
  const value = defaultSource(col);
@@ -38,13 +34,6 @@ const METHOD_SOURCE = {
38
34
  // The graph link: a foreign key becomes a relation decorator, emitted beside the field rather than in it.
39
35
  table: null,
40
36
  };
41
- /** The AST's reading of the entity's `ownsSoleKey`: the table's whole key, and not the key of a row it references. */
42
- function ownsSoleKey(col) {
43
- const { primaryKey, outgoingRelations } = col.table;
44
- return (col.isPrimaryKey &&
45
- primaryKey?.columns.length === 1 &&
46
- !outgoingRelations.some(({ from }) => from.columns.includes(col)));
47
- }
48
37
  /** Whether to write `type`'s precision: not for a timestamp at a `Date`'s milliseconds, its default. */
49
38
  function writesPrecision(type) {
50
39
  return type.precision !== undefined && !(type.category === 'timestamp' && type.precision === DATE_PRECISION);