uql-orm 0.47.0 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/querier/httpQuerier.d.ts +2 -2
- package/dist/browser/type/clientQuerier.d.ts +3 -3
- package/dist/browser/uql-browser.min.js.map +2 -2
- package/dist/dialect/abstractDialect.d.ts +35 -1
- package/dist/dialect/abstractDialect.js +29 -0
- package/dist/dialect/abstractSqlDialect.d.ts +13 -5
- package/dist/dialect/abstractSqlDialect.js +45 -49
- package/dist/entity/decorator/members.d.ts +2 -0
- package/dist/entity/decorator/members.js +2 -0
- package/dist/entity/index.d.ts +1 -1
- package/dist/entity/index.js +1 -1
- package/dist/entity/metadata/definition.d.ts +11 -2
- package/dist/entity/metadata/definition.js +11 -0
- package/dist/mongo/mongoDialect.d.ts +36 -6
- package/dist/mongo/mongoDialect.js +116 -31
- package/dist/mongo/mongodbQuerier.d.ts +8 -3
- package/dist/mongo/mongodbQuerier.js +30 -11
- package/dist/querier/abstractQuerier.d.ts +33 -4
- package/dist/querier/abstractQuerier.js +92 -43
- package/dist/querier/abstractQuerierPool.d.ts +2 -2
- package/dist/querier/abstractSqlQuerier.d.ts +3 -2
- package/dist/querier/abstractSqlQuerier.js +132 -31
- package/dist/querier/relationCount.js +15 -9
- package/dist/type/entity.d.ts +1 -1
- package/dist/type/queryRaw.d.ts +1 -1
- package/dist/type/queryWhere.d.ts +11 -1
- package/dist/type/universalQuerier.d.ts +2 -2
- package/dist/util/dialect.util.d.ts +7 -0
- package/dist/util/dialect.util.js +14 -0
- package/dist/util/fieldOption.util.d.ts +1 -1
- package/dist/util/fieldOption.util.js +1 -1
- package/dist/util/relationQuery.util.d.ts +9 -6
- package/dist/util/relationQuery.util.js +11 -11
- package/dist/util/rowKey.util.d.ts +18 -4
- package/dist/util/rowKey.util.js +29 -5
- package/package.json +1 -1
|
@@ -38,8 +38,8 @@ export declare class HttpQuerier implements ClientQuerier {
|
|
|
38
38
|
insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<(IdValue<E> | undefined)[]>>;
|
|
39
39
|
updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdatePayload<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
40
40
|
updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
41
|
-
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<
|
|
42
|
-
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<(
|
|
41
|
+
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<EntityId<E> | undefined>>;
|
|
42
|
+
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<(EntityId<E> | undefined)[]>>;
|
|
43
43
|
deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
44
44
|
deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
45
45
|
getBasePath<E>(entity: Type<E>): string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityData, IdValue, QuerierResult, QueryOptions, SharedQuerier, Type } from '../../type/index.js';
|
|
1
|
+
import type { EntityData, EntityId, IdValue, QuerierResult, QueryOptions, SharedQuerier, Type } from '../../type/index.js';
|
|
2
2
|
import type { RequestOptions } from './request.js';
|
|
3
3
|
/**
|
|
4
4
|
* Client-side querier: {@link SharedQuerier} on the `'client'` transport, so every result arrives in
|
|
@@ -9,6 +9,6 @@ import type { RequestOptions } from './request.js';
|
|
|
9
9
|
export interface ClientQuerier extends SharedQuerier<'client', RequestOptions, QueryOptions & RequestOptions> {
|
|
10
10
|
insertOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): QuerierResult<'client', IdValue<E> | undefined>;
|
|
11
11
|
insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): QuerierResult<'client', (IdValue<E> | undefined)[]>;
|
|
12
|
-
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): QuerierResult<'client',
|
|
13
|
-
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): QuerierResult<'client', (
|
|
12
|
+
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): QuerierResult<'client', EntityId<E> | undefined>;
|
|
13
|
+
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): QuerierResult<'client', (EntityId<E> | undefined)[]>;
|
|
14
14
|
}
|
|
@@ -9,10 +9,10 @@
|
|
|
9
9
|
"import type { Type, UniversalQuerier } from '../type/index.js';\n// the specific util modules, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys } from '../util/object.util.js';\nimport { kebabCase } from '../util/string.util.js';\n\ntype RouteShape = {\n readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly path: '' | `/${string}`;\n};\n\n/**\n * Single source of truth for the CRUD-over-HTTP surface, shared by server adapters and the browser client.\n * Keys are constrained to {@link UniversalQuerier} method names, so renaming a querier method\n * (or routing a non-existent one) is a compile error.\n */\nexport const CRUD_ROUTES = {\n findMany: { method: 'GET', path: '' },\n findOne: { method: 'GET', path: '/one' },\n count: { method: 'GET', path: '/count' },\n findOneById: { method: 'GET', path: '/:id' },\n insertOne: { method: 'POST', path: '' },\n insertMany: { method: 'POST', path: '/many' },\n saveOne: { method: 'PUT', path: '' },\n saveMany: { method: 'PUT', path: '/many' },\n updateMany: { method: 'PATCH', path: '' },\n updateOneById: { method: 'PATCH', path: '/:id' },\n deleteOneById: { method: 'DELETE', path: '/:id' },\n deleteMany: { method: 'DELETE', path: '' },\n} as const satisfies Partial<Record<keyof UniversalQuerier, RouteShape>>;\n\nexport type CrudOperation = keyof typeof CRUD_ROUTES;\n\nexport type CrudRoute = (typeof CRUD_ROUTES)[CrudOperation];\n\n/**\n * `QUERY` (RFC 10008) is an alternate transport for the read operations: same semantics as the\n * GET routes, but the JSON query travels in the request body instead of the query string,\n * avoiding URL-length limits for large queries.\n */\nexport type HttpMethod = CrudRoute['method'] | 'QUERY';\n\nconst CRUD_OPS = getKeys(CRUD_ROUTES);\n\n// derived from CRUD_ROUTES (the literal-path GET routes) so the sub-paths live in exactly one place\nconst QUERY_READ_OPS: ReadonlyMap<string, CrudOperation> = new Map(\n CRUD_OPS.filter((op) => CRUD_ROUTES[op].method === 'GET' && CRUD_ROUTES[op].path !== '/:id').map((op) => [\n CRUD_ROUTES[op].path,\n op,\n ]),\n);\n\n/**\n * URL segment for an entity, e.g. `entityPath(UserProfile) === 'user-profile'`.\n */\nexport function entityPath<E>(entity: Type<E>): string {\n return kebabCase(entity.name);\n}\n\nexport type RouteMatch = {\n readonly op: CrudOperation;\n /**\n * the resolved transport method - differs from the op's canonical route method for QUERY.\n */\n readonly method: HttpMethod;\n readonly id?: string;\n};\n\n/**\n * Resolve a (method, sub-path) pair to a CRUD operation. Literal sub-paths win over `:id`.\n */\nexport function matchRoute(method: string, subPath: string | undefined): RouteMatch | undefined {\n const raw = method.toUpperCase();\n const literal = subPath === undefined ? '' : `/${subPath}`;\n if (raw === 'QUERY') {\n const op = QUERY_READ_OPS.get(literal);\n return op ? { op, method: 'QUERY' } : undefined;\n }\n // HEAD reads like GET per HTTP semantics; the server runtime omits the response body\n const verb = raw === 'HEAD' ? 'GET' : raw;\n let idOp: CrudOperation | undefined;\n for (const op of CRUD_OPS) {\n const route = CRUD_ROUTES[op];\n if (route.method !== verb) {\n continue;\n }\n if (route.path === literal) {\n return { op, method: route.method };\n }\n if (route.path === '/:id') {\n idOp = op;\n }\n }\n return idOp && subPath !== undefined ? { op: idOp, method: CRUD_ROUTES[idOp].method, id: subPath } : undefined;\n}\n\nexport type RequestErrorResponse = {\n readonly error: {\n readonly message: string;\n readonly code: number;\n };\n};\n\n/**\n * Map a thrown error to the wire error envelope. Honors a numeric `status` on the error\n * (e.g. hooks throwing 403), defaults to 500; `code` mirrors the HTTP status.\n */\nexport function toErrorResponse(err: unknown): { status: number; body: RequestErrorResponse } {\n const status = err instanceof Error && 'status' in err && typeof err.status === 'number' ? err.status : 500;\n const message = err instanceof Error ? err.message : 'Internal Server Error';\n return { status, body: { error: { message, code: status } } };\n}\n",
|
|
10
10
|
"import type { FieldKey, IdKey, JsonFieldPaths, RelationKey, RelationTarget } from './entity.js';\nimport type { QueryLock } from './queryLock.js';\nimport type { QueryRaw } from './queryRaw.js';\nimport type { QueryWhere } from './queryWhere.js';\nimport type { BooleanLike, Except, IsMany, PrimaryKey } from './utility.js';\nimport type { 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 * prefix the query with this.\n */\n prefix?: string;\n /**\n * automatically infer the prefix for the query.\n */\n autoPrefix?: boolean;\n};\n\nexport type QuerySelectOptions = {\n /**\n * prefix the query with this.\n */\n prefix?: string;\n /**\n * automatically add the prefix for the alias.\n */\n autoPrefixAlias?: boolean;\n};\n\n/**\n * Query field selection - `{ name: true }` whitelists specific fields. Fields only: a relation is a\n * sub-query rather than a projection flag, and a whitelist naming one could not say whether the\n * scalars come with it. Relations go in `$populate`.\n */\nexport type QuerySelect<E> = {\n [K in FieldKey<E>]?: BooleanLike;\n};\n\n/**\n * Accepted `$select` value: a field map, or raw SQL projections built with `raw()`\n * (e.g. ``[raw`*`, raw`LOG10(points)`.as('score')]``). The raw form is SQL-only.\n */\nexport type QuerySelectValue<E> = QuerySelect<E> | readonly QueryRaw[];\n\n/**\n * Fields to exclude from the query result - `{ name: true }` blacklists fields.\n * Mutually exclusive with positive field selections in `$select`.\n */\nexport type QueryExclude<E> = QuerySelect<E>;\n\n/**\n * relation population map.\n */\nexport type QueryPopulate<E> = {\n [K in RelationKey<E>]?: BooleanLike | QueryPopulateRelationOptions<E[K]>;\n};\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. One statement per relation named here, batched over every parent at once, so it\n * stays flat however many rows the read returned. Comes back under `_count`, which keeps it clear of\n * a relation of the same name that `$populate` filled with rows.\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\nexport type QueryCount<E> = {\n [K in ToManyRelationKey<E>]?: BooleanLike | QueryFilter<RelationTarget<E[K]>>;\n};\n\n/**\n * query conflict paths - subset of field keys used to detect upsert conflicts.\n */\nexport type QueryConflictPaths<E> = {\n [K in FieldKey<E>]?: true;\n};\n\n/**\n * Options to populate a relation declared as `V`, by its cardinality.\n */\nexport type QueryPopulateRelationOptions<V> = (IsMany<V> extends true\n ? // `$lock` is statement-level, so it is excluded here rather than being silently ignored per\n // relation. `QueryUnique` is a `Pick` and already leaves it out.\n Except<Query<RelationTarget<V>>, '$lock'>\n : QueryUnique<RelationTarget<V>>) & {\n $required?: boolean;\n};\n\n/**\n * Ambient per-request context (e.g. `{ tenantId, userId, roles }`) resolved by parameterized\n * filters. Set with `withContext(ctx, cb)`. It's an `interface` (not a type alias) so you can type\n * your keys once via declaration merging and get them typed wherever context is read:\n *\n * ```ts\n * declare module 'uql-orm' {\n * interface UqlContext { tenantId: number; userId: string }\n * }\n * ```\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 FilterCondition<E> = QueryWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);\n\n/**\n * What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);\n * `throw` fails closed (the default for `security` filters).\n */\nexport type FilterOnMissing = 'skip' | 'throw';\n\n/**\n * Authoring shape for `@Entity({ filters })` / `@Filter` / `defineFilter`.\n */\nexport type FilterOptions<E = unknown> = {\n readonly condition: FilterCondition<E>;\n /** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */\n readonly default?: boolean;\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.\n */\n readonly security?: boolean;\n /** What to do when the condition returns `undefined`. Defaults to `skip`, or `throw` for `security`. */\n readonly onMissing?: FilterOnMissing;\n};\n\n/**\n * direction for the sort.\n */\nexport type QuerySortDirection = -1 | 1 | 'asc' | 'desc';\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 * To-one relations only: a parent holds many rows of a to-many, so there is no single value to order\n * it by, and joining one in would duplicate the parent instead. Order those inside `$populate`.\n */\ntype ToOneRelationKey<E> = { [K in RelationKey<E>]: IsMany<E[K]> extends true ? never : K }[RelationKey<E>];\n\n/** The relation names a parent holds many rows of, which a populated query fills with a list. */\ntype ToManyRelationKey<E> = Exclude<RelationKey<E>, ToOneRelationKey<E>>;\n\n/**\n * sort by map - supports field keys, JSON dot-notation paths (restricted to real JSON fields,\n * like `QueryWhereMap`), relation sort via nested objects, and vector similarity search on\n * `number[]` fields. `Vector` is what confines a vector search to the level the statement ranks:\n * the queried entity. A relation of it is joined in one row at a time, so there is nothing to rank\n * there - the SQL dialects throw, and MongoDB would quietly drop it, so this is its only guard.\n *\n * One mapped type over the three key sets rather than three intersected. The sets are disjoint - a\n * JSON path is dotted, and a field key cannot also be a relation key - and an assignability check\n * against an intersection is repeated per constituent, which made this the single most expensive\n * type in the package to check.\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\nexport type QuerySortMap<E, Vector extends boolean = true> = {\n [K in FieldKey<E> | JsonFieldPaths<E> | RelationKey<E>]?: K extends RelationKey<E>\n ? // A to-many has no single value to order by, so what it offers instead is its own size.\n IsMany<E[K]> extends true\n ? QuerySortByCount\n : QuerySortMap<RelationTarget<E[K]>, false>\n : K extends FieldKey<E>\n ? Vector extends true\n ? NonNullable<E[K]> extends readonly number[]\n ? QuerySortValue\n : QuerySortDirection\n : QuerySortDirection\n : QuerySortDirection;\n};\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> = {\n /**\n * filtering options.\n */\n $where?: QueryWhere<E>;\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> = QueryFilter<E> & 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> = QueryPage<E> & {\n /**\n * sorting options.\n */\n $sort?: QuerySortMap<E>;\n};\n\n/**\n * query options.\n */\nexport type Query<E> = {\n /**\n * field selection - `{ name: true }` whitelists fields, or raw SQL projections\n * (``[raw`LOG10(points)`.as('score')]``, SQL dialects only - MongoDB rejects the raw-array form).\n * Mutually exclusive with `$exclude`.\n */\n $select?: QuerySelectValue<E>;\n\n /**\n * relation population options.\n */\n $populate?: QueryPopulate<E>;\n\n /**\n * how many rows each named relation holds, under `_count` on every row. See {@link QueryCount}.\n */\n $count?: QueryCount<E>;\n\n /**\n * field exclusion - `{ name: true }` blacklists fields. Mutually exclusive with positive `$select`.\n * Keys a relation is assembled from (a joined row's primary key, a to-many's foreign key) are kept\n * regardless, since subtracting them would leave the relation unfilled.\n */\n $exclude?: QueryExclude<E>;\n\n /**\n * sorting options, vector similarity search included: a SELECT is the one statement with a\n * projection list to hold the distance such a search computes.\n */\n $sort?: QuerySortMap<E>;\n\n /**\n * whether to return only distinct rows.\n */\n $distinct?: boolean;\n\n /**\n * take a row-level lock on the rows this query returns (`SELECT ... FOR UPDATE`). Needs an open\n * transaction: outside one the statement commits and drops the lock before the caller can act on\n * the rows, so it is rejected rather than emitted. Locks only the queried entity, never anything\n * reached through `$populate`. SQL only; MongoDB and the SQLite family reject it.\n *\n * Declared here rather than on {@link QuerySearch}, which `update`/`delete` take: that placement\n * is what keeps the clause off those statements at the type level.\n */\n $lock?: QueryLock;\n\n /**\n * how many candidates an approximate-nearest-neighbour index explores before ranking, for a vector\n * search. Higher trades speed for recall; the default is whatever the engine's own is, which is\n * tuned for speed. Ignored where the search is exact (SQLite, libSQL and Turso scan every row) and\n * where the field carries no ANN index, since there is nothing to widen.\n *\n * The units are the index's, not UQL's, so the number is not comparable across index types: it\n * becomes `hnsw.ef_search` or `ivfflat.probes` on Postgres, `mhnsw_ef_search` on MariaDB, and\n * `numCandidates` on MongoDB Atlas. On Postgres it needs an open transaction, since a `SET LOCAL`\n * outside one applies to nothing.\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>;\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 * `Query`'s clauses grouped by the shape of their value - what a parser reading one off the wire and\n * a validator checking a relation's own query both need, and what each used to enumerate for itself.\n * Declared beside the type they describe so the two cannot drift, and `satisfies` fails the build\n * rather than the runtime if a clause is ever renamed.\n *\n * `$lock` belongs to no group on purpose: it is the one clause neither a wire query nor a relation's\n * query accepts, so leaving it out is what excludes it from both.\n */\nexport const QUERY_OBJECT_CLAUSES = [\n '$select',\n '$populate',\n '$exclude',\n '$where',\n '$sort',\n] as const satisfies readonly (keyof Query<unknown>)[];\n\n/**\n * Object clauses only the statement itself takes, never a relation's own query - the mirror of\n * `$lock`, which neither takes. Counting a relation is batched over the rows a read returned, and a\n * populated relation's rows are assembled after that, so there is nothing for a nested one to count.\n */\nexport const QUERY_ROOT_OBJECT_CLAUSES = ['$count'] as const satisfies readonly (keyof Query<unknown>)[];\n\nexport const QUERY_NUMBER_CLAUSES = ['$skip', '$limit'] as const satisfies readonly (keyof Query<unknown>)[];\n\n/**\n * Number clauses only the statement itself takes - the numeric mirror of {@link QUERY_ROOT_OBJECT_CLAUSES}.\n * `$candidates` tunes the index behind a vector search, and a vector search only ever ranks the rows\n * the statement returns, so a relation's own query has nothing to tune.\n */\nexport const QUERY_ROOT_NUMBER_CLAUSES = ['$candidates'] as const satisfies readonly (keyof Query<unknown>)[];\n\nexport const QUERY_BOOLEAN_CLAUSES = ['$distinct'] as const satisfies readonly (keyof Query<unknown>)[];\n\n/**\n * options to get a single record.\n */\nexport type QueryOne<E> = Except<Query<E>, '$limit'>;\n\n/**\n * options to get an unique record.\n */\nexport type QueryUnique<E> = Pick<QueryOne<E>, '$select' | '$exclude' | '$populate' | '$where'>;\n\n/**\n * The clauses that decide a row's shape, captured from the query as written: the field names\n * `$select` and `$exclude` list, the value those maps carry (a falsy one subtracts instead of\n * selecting, as it does at runtime, and a widened map is how a projection that is not statically\n * known announces itself), and the relation names `$populate` lists.\n *\n * Each is captured as a *key set* rather than as the map itself, which is what keeps the checks\n * intact: TypeScript skips excess-property checking on a naked type parameter, so a captured map\n * would take a typo'd key without a word, while a captured key set makes that typo fail its own\n * `FieldKey<E>` / `RelationKey<E>` constraint. Every other clause - `$where`, `$sort`, and each\n * populated relation's own query - stays the concrete {@link Query} it is today.\n * @internal\n */\ntype QueryProjection<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E>,\n> = QueryStreamProjection<E, S, V, X, P> & {\n // Intersecting the captured names with {@link QueryCount}'s own leaves a to-one relation no key\n // here at all, so counting one is an excess property rather than a value to check. Narrowing the\n // key rather than the value also instantiates `QueryCount<E>` once instead of once per counted\n // relation, worth ~87k instantiations in a consuming project.\n $count?: { [K in C & keyof QueryCount<E>]?: QueryCount<E>[K] };\n};\n\n/**\n * {@link QueryProjection} without `$count`, which a stream cannot honor. Split out rather than\n * subtracted afterwards: an optional key is a *known* key even when its value maps over `never`, so\n * a statement that must not take the clause has to be built without it in the first place.\n * @internal\n */\ntype QueryStreamProjection<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P extends RelationKey<E>> = {\n $select?: { [K in S]?: V } | readonly QueryRaw[];\n $exclude?: { [K in X]?: V };\n $populate?: { [K in P]?: QueryPopulate<E>[K] };\n};\n\n/**\n * A {@link QueryProjected} a stream can honor: no `$count`, which is batched over a result set a\n * stream never holds all of.\n */\nexport type QueryStreamProjected<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P extends RelationKey<E>> = Except<\n Query<E>,\n '$count'\n> &\n QueryStreamProjection<E, S, V, X, P>;\n\n/**\n * A {@link Query} whose projection is captured, so {@link QueryFindResult} can shape the row.\n */\nexport type QueryProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n> = Query<E> & QueryProjection<E, S, V, X, P, C>;\n\n/**\n * A {@link QueryOne} whose projection is captured, so {@link QueryFindResult} can shape the row.\n */\nexport type QueryOneProjected<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E> = never,\n> = QueryOne<E> & QueryProjection<E, S, V, X, P, C>;\n\n/**\n * The keys a query comes back with, mirroring what the runtime projects: the fields a positive\n * `$select` names, or every field minus what a falsy `$select` entry or a truthy `$exclude` entry\n * subtracts, plus the relations `$populate` asked for. A positive `$select` wins outright, which is\n * why `$exclude` is only read on the branch where there is none.\n * @internal\n */\ntype ProjectedKeys<E, S, V, X, P, C> =\n | ([V] extends [false | 0] ? Exclude<FieldKey<E>, S> : [S] extends [never] ? Exclude<FieldKey<E>, X> : S)\n | P\n // Populating a relation keeps the id whatever the projection says, and so does counting one: both\n // assemble their result by it (`selectFields` puts it back, as does MongoDB's `pipelineProjection`).\n | ([P | C] extends [never] ? never : NamedIdKey<E>);\n\n/**\n * The id key when it can be named, and nothing when it cannot: {@link IdKey} widens to *every* field\n * for an entity whose id is neither branded nor called `id`/`_id`/`uuid`, and adding that back would\n * hand the caller a row claiming fields the query never fetched. Missing an id costs a `$select`\n * entry; promising absent fields is the bug this type exists to prevent.\n * @internal\n */\ntype NamedIdKey<E> = [FieldKey<E>] extends [IdKey<E>] ? never : IdKey<E>;\n\n/**\n * Whether every entry of the captured map says the same thing: all selected, or all subtracted.\n * @internal\n */\ntype IsUniform<V> = [V] extends [true | 1] ? true : [V] extends [false | 0] ? true : false;\n\n/**\n * A row of a find result: the entity narrowed to the fields the query projected, plus the relations\n * it populated - reading anything the query left out is a compile error rather than a silent\n * `undefined`. Modifiers are preserved, so an optional field stays optional. Name a projected row\n * with it where a helper has to take one: `QueryFindResult<User, 'id' | 'name'>`.\n *\n * The entity itself when the query projects nothing, when it uses a raw-projection array (columns,\n * not fields), and when the projection is not uniform - a `Query<E>` built elsewhere, or a map\n * mixing selected and subtracted entries, whose positive keys inference cannot recover. Relations\n * keep their declared type: narrowing them means capturing their queries as maps, which costs those\n * queries their own checks.\n */\nexport type QueryFindResult<\n E,\n S extends FieldKey<E> = never,\n // A whitelist by default, so the hand-written form reads `QueryFindResult<User, 'id' | 'name'>`.\n V = true,\n X extends FieldKey<E> = never,\n P extends RelationKey<E> = never,\n C extends RelationKey<E> = never,\n> = QueryProjectedRow<E, S, V, X, P, C> & CountedRelations<C>;\n\n/**\n * The `_count` a query asked for, or an inert intersection member when it asked for none - so a read\n * without `$count` keeps exactly the row type it had.\n */\ntype CountedRelations<C extends PropertyKey> = [C] extends [never]\n ? unknown\n : { [K in typeof COUNT_RESULT_KEY]: { [R in C]: number } };\n\n/** @internal */\ntype QueryProjectedRow<\n E,\n S extends FieldKey<E>,\n V,\n X extends FieldKey<E>,\n P extends RelationKey<E>,\n C extends RelationKey<E>,\n> = [S | X] extends [never]\n ? E\n : IsUniform<V> extends true\n ? [PopulatedToMany<E, P>] extends [never]\n ? // `Pick`, not a key remap: an entity keyed by an index signature - a content type defined at\n // runtime - has `string` for its keys, and a remap keeps no literal one, so every projection\n // over one came back as `{}`.\n Pick<E, ProjectedKeys<E, S, V, X, P, C> & keyof E>\n : // A populated to-many is always a list, empty where the parent has no children, so it maps\n // and counts without a guard. Only that promotion needs a second member, and only a query\n // that populates one pays for it; every other key keeps the modifier the entity declared,\n // a to-one relation included, since a join that finds no row leaves it absent.\n Pick<E, Exclude<ProjectedKeys<E, S, V, X, P, C>, PopulatedToMany<E, P>> & keyof E> & {\n [K in PopulatedToMany<E, P>]-?: NonNullable<E[K]>;\n }\n : E;\n\n/** The to-many relations a query populated, which come back as lists rather than as optional ones. */\ntype PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;\n\n/**\n * stringified query.\n */\nexport type QueryStringified = {\n [K in keyof Query<unknown>]?: string;\n};\n\n/**\n * result of an update operation.\n */\nexport type QueryUpdateResult = {\n /**\n * number of affected records.\n */\n changes?: number;\n /**\n * the inserted IDs, in insertion order. Exact on `'returning'` dialects; inferred from the\n * driver header on the others (see {@link InsertIdSource}), and empty when the header\n * reports no generated ID.\n */\n ids?: PrimaryKey[];\n /**\n * first inserted ID.\n */\n firstId?: PrimaryKey;\n /**\n * whether the record was created (`true`) or updated (`false`).\n * `undefined` when the dialect cannot determine this (e.g. SQLite).\n */\n created?: boolean;\n};\n",
|
|
11
11
|
"import type { Query, QueryOptions } from '../type/index.js';\n// the clause lists themselves, not the barrel: this module is in the browser bundle's graph\nimport {\n QUERY_BOOLEAN_CLAUSES,\n QUERY_NUMBER_CLAUSES,\n QUERY_OBJECT_CLAUSES,\n QUERY_ROOT_NUMBER_CLAUSES,\n QUERY_ROOT_OBJECT_CLAUSES,\n} from '../type/query.js';\n// the specific util module, not the barrel, so the browser bundle does not pull in entity metadata\nimport { getKeys } from '../util/object.util.js';\n\n/**\n * Keys accepted from the wire - query structure ({@link Query}) plus the `hardDelete`/`count` scalar\n * flags. Anything else (e.g. `filters`, `context`, `$entity`) is dropped so a remote client can't\n * bypass a security filter or inject ambient context - those are server-only. The `satisfies` ties\n * every entry to a real query/option key, so a typo or a renamed option fails to compile.\n */\nconst ALLOWED_QUERY_KEYS = new Set<string>([\n ...QUERY_OBJECT_CLAUSES,\n ...QUERY_ROOT_OBJECT_CLAUSES,\n ...QUERY_NUMBER_CLAUSES,\n ...QUERY_ROOT_NUMBER_CLAUSES,\n ...QUERY_BOOLEAN_CLAUSES,\n 'hardDelete',\n 'count',\n] satisfies (keyof Query<unknown> | keyof Pick<QueryOptions, 'hardDelete'> | 'count')[]);\n\n/**\n * Keys that mean something locally but that this transport can never honor, so they are rejected\n * rather than dropped like the rest. Each request runs on its own auto-committing connection, so a\n * row lock taken here is released before the response is written: honoring `$lock` is impossible,\n * and ignoring it would hand the caller a read they believe is serialized and is not.\n */\nconst REJECTED_QUERY_KEYS = new Set<string>(['$lock'] satisfies (keyof Query<unknown>)[]);\n\n/**\n * Parse raw query-string entries (with JSON-stringified values) into a UQL query object.\n * Symmetric counterpart of {@link stringifyQuery}. Only {@link ALLOWED_QUERY_KEYS} are honored.\n */\nexport function parseQueryParams(params: Record<string, unknown> = {}): Query<unknown> {\n const query: Record<string, unknown> = {};\n for (const key of getKeys(params)) {\n if (REJECTED_QUERY_KEYS.has(key)) {\n throw Object.assign(new TypeError(`'${key}' is not supported over HTTP`), { status: 400 });\n }\n if (ALLOWED_QUERY_KEYS.has(key)) {\n query[key] = params[key];\n }\n }\n\n for (const key of [...QUERY_OBJECT_CLAUSES, ...QUERY_ROOT_OBJECT_CLAUSES]) {\n const value = query[key];\n if (typeof value === 'string') {\n try {\n query[key] = JSON.parse(value);\n } catch {\n throw Object.assign(new SyntaxError(`invalid JSON in '${key}'`), { status: 400 });\n }\n }\n }\n\n query['$where'] ??= {};\n\n // A query string carries every value as text, so what decodes a clause is the shape its group\n // declares. `'false'` is the reason the boolean pass exists rather than the raw value being taken:\n // it is a non-empty string, so a `$distinct=false` would otherwise read as asking for one.\n for (const key of [...QUERY_NUMBER_CLAUSES, ...QUERY_ROOT_NUMBER_CLAUSES]) {\n if (query[key] !== undefined) {\n query[key] = Number(query[key]);\n }\n }\n for (const key of QUERY_BOOLEAN_CLAUSES) {\n if (query[key] !== undefined) {\n query[key] = query[key] === true || query[key] === 'true';\n }\n }\n\n return query as Query<unknown>;\n}\n\n/**\n * Serialize a UQL query object into a percent-encoded query string where object values\n * are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.\n */\nexport function stringifyQuery(query?: Record<string, unknown>): string {\n if (!query) {\n return '';\n }\n const params = new URLSearchParams();\n for (const key of getKeys(query)) {\n const value = query[key];\n if (value === undefined) {\n continue;\n }\n params.append(key, typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value));\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n",
|
|
12
|
-
"import { CRUD_ROUTES, entityPath, type HttpMethod } from '../../http/contract.js';\nimport { stringifyQuery } from '../../http/query.js';\nimport type {\n EntityData,\n EntityId,\n FieldKey,\n IdValue,\n Query,\n QueryFilter,\n QueryFindResult,\n QueryOneProjected,\n QueryOptions,\n QueryPage,\n QueryProjected,\n QuerySearch,\n RelationKey,\n RequestCountedSuccessResponse,\n RequestSuccessResponse,\n Type,\n UpdatePayload,\n} from '../../type/index.js';\nimport { isScalarId } from '../../util/object.util.js';\nimport { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';\nimport type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';\n\nexport type HttpQuerierDefaults = {\n /**\n * headers sent with every request from this instance, merged under per-call headers.\n * Create one instance per request (e.g. during SSR) to scope auth headers safely.\n */\n readonly headers?: Record<string, string>;\n /**\n * transport for read queries (findOne, findMany, count). 'QUERY' (RFC 10008) sends the\n * JSON query in the request body, avoiding URL-length limits for large queries; requires\n * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.\n */\n readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;\n /**\n * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same\n * option the server handler takes, so one map serves both. State it where the default cannot: a\n * build that minifies class names renames every route.\n */\n readonly entityPath?: (entity: Type<unknown>) => string;\n};\n\n/**\n * The id as one path segment.\n *\n * A composite key has no spelling here yet - the route is `/:id`, and how several columns share one\n * segment is a serialization to invent rather than copy. Refused rather than interpolated, which\n * would have sent `[object Object]` for the server to reject. Its callers are `async` so this\n * surfaces as a rejection, like every other failure they can hand back.\n */\nfunction idSegment<E>(entity: Type<E>, id: EntityId<E>): string {\n if (!isScalarId(id)) {\n throw new TypeError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);\n }\n return String(id);\n}\n\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n async findOneById<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n id: EntityId<E>,\n q?: QueryOneProjected<E, S, V, X, P, C>,\n opts?: RequestOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>> {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(q);\n return get<QueryFindResult<E, S, V, X, P, C> | undefined>(\n `${basePath}/${idSegment(entity, id)}${qs}`,\n this.buildOptions(opts),\n );\n }\n\n findOne<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryOneProjected<E, S, V, X, P, C>,\n opts?: RequestOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>> {\n return this.read<QueryFindResult<E, S, V, X, P, C> | undefined>(\n `${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`,\n q,\n opts,\n );\n }\n\n findMany<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryProjected<E, S, V, X, P, C>,\n opts?: RequestFindOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>> {\n const data: Query<E> & { count?: boolean } = { ...q };\n if (opts?.count) {\n data.count = true;\n }\n return this.read<QueryFindResult<E, S, V, X, P, C>[]>(this.getBasePath(entity), data, opts);\n }\n\n async findManyAndCount<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryProjected<E, S, V, X, P, C>,\n opts?: RequestFindOptions,\n ): Promise<RequestCountedSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>> {\n const response = await this.findMany(entity, q, { ...opts, count: true });\n if (typeof response.count !== 'number') {\n throw new TypeError('findManyAndCount response has an invalid count');\n }\n return { ...response, count: response.count };\n }\n\n count<E extends object>(entity: Type<E>, q?: QueryPage<E>, opts?: RequestOptions) {\n return this.read<number>(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);\n }\n\n /** The `count` route capped at one row, so existence needs no endpoint of its own. */\n async exists<E extends object>(entity: Type<E>, q?: QueryFilter<E>, opts?: RequestOptions) {\n const res = await this.count(entity, { ...q, $limit: 1 }, opts);\n return { ...res, data: res.data > 0 };\n }\n\n insertOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return post<IdValue<E> | undefined>(basePath, payload, this.buildOptions(opts));\n }\n\n insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return post<(IdValue<E> | undefined)[]>(\n `${basePath}${CRUD_ROUTES.insertMany.path}`,\n payload,\n this.buildOptions(opts),\n );\n }\n\n async updateOneById<E extends object>(\n entity: Type<E>,\n id: EntityId<E>,\n payload: UpdatePayload<E>,\n opts?: RequestOptions,\n ) {\n const basePath = this.getBasePath(entity);\n return patch<number>(`${basePath}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));\n }\n\n updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(q);\n return patch<number>(`${basePath}${qs}`, payload, this.buildOptions(opts));\n }\n\n saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return put<
|
|
12
|
+
"import { CRUD_ROUTES, entityPath, type HttpMethod } from '../../http/contract.js';\nimport { stringifyQuery } from '../../http/query.js';\nimport type {\n EntityData,\n EntityId,\n FieldKey,\n IdValue,\n Query,\n QueryFilter,\n QueryFindResult,\n QueryOneProjected,\n QueryOptions,\n QueryPage,\n QueryProjected,\n QuerySearch,\n RelationKey,\n RequestCountedSuccessResponse,\n RequestSuccessResponse,\n Type,\n UpdatePayload,\n} from '../../type/index.js';\nimport { isScalarId } from '../../util/object.util.js';\nimport { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';\nimport type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';\n\nexport type HttpQuerierDefaults = {\n /**\n * headers sent with every request from this instance, merged under per-call headers.\n * Create one instance per request (e.g. during SSR) to scope auth headers safely.\n */\n readonly headers?: Record<string, string>;\n /**\n * transport for read queries (findOne, findMany, count). 'QUERY' (RFC 10008) sends the\n * JSON query in the request body, avoiding URL-length limits for large queries; requires\n * infrastructure (proxies, CDNs) that forwards the QUERY method. Defaults to 'GET'.\n */\n readonly readMethod?: Extract<HttpMethod, 'GET' | 'QUERY'>;\n /**\n * The URL segment an entity is addressed by, defaulting to its kebab-cased class name - the same\n * option the server handler takes, so one map serves both. State it where the default cannot: a\n * build that minifies class names renames every route.\n */\n readonly entityPath?: (entity: Type<unknown>) => string;\n};\n\n/**\n * The id as one path segment.\n *\n * A composite key has no spelling here yet - the route is `/:id`, and how several columns share one\n * segment is a serialization to invent rather than copy. Refused rather than interpolated, which\n * would have sent `[object Object]` for the server to reject. Its callers are `async` so this\n * surfaces as a rejection, like every other failure they can hand back.\n */\nfunction idSegment<E>(entity: Type<E>, id: EntityId<E>): string {\n if (!isScalarId(id)) {\n throw new TypeError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);\n }\n return String(id);\n}\n\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n async findOneById<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n id: EntityId<E>,\n q?: QueryOneProjected<E, S, V, X, P, C>,\n opts?: RequestOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>> {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(q);\n return get<QueryFindResult<E, S, V, X, P, C> | undefined>(\n `${basePath}/${idSegment(entity, id)}${qs}`,\n this.buildOptions(opts),\n );\n }\n\n findOne<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryOneProjected<E, S, V, X, P, C>,\n opts?: RequestOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>> {\n return this.read<QueryFindResult<E, S, V, X, P, C> | undefined>(\n `${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`,\n q,\n opts,\n );\n }\n\n findMany<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryProjected<E, S, V, X, P, C>,\n opts?: RequestFindOptions,\n ): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>> {\n const data: Query<E> & { count?: boolean } = { ...q };\n if (opts?.count) {\n data.count = true;\n }\n return this.read<QueryFindResult<E, S, V, X, P, C>[]>(this.getBasePath(entity), data, opts);\n }\n\n async findManyAndCount<\n E extends object,\n const S extends FieldKey<E> = never,\n const V = true,\n const X extends FieldKey<E> = never,\n const P extends RelationKey<E> = never,\n const C extends RelationKey<E> = never,\n >(\n entity: Type<E>,\n q: QueryProjected<E, S, V, X, P, C>,\n opts?: RequestFindOptions,\n ): Promise<RequestCountedSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>> {\n const response = await this.findMany(entity, q, { ...opts, count: true });\n if (typeof response.count !== 'number') {\n throw new TypeError('findManyAndCount response has an invalid count');\n }\n return { ...response, count: response.count };\n }\n\n count<E extends object>(entity: Type<E>, q?: QueryPage<E>, opts?: RequestOptions) {\n return this.read<number>(`${this.getBasePath(entity)}${CRUD_ROUTES.count.path}`, q, opts);\n }\n\n /** The `count` route capped at one row, so existence needs no endpoint of its own. */\n async exists<E extends object>(entity: Type<E>, q?: QueryFilter<E>, opts?: RequestOptions) {\n const res = await this.count(entity, { ...q, $limit: 1 }, opts);\n return { ...res, data: res.data > 0 };\n }\n\n insertOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return post<IdValue<E> | undefined>(basePath, payload, this.buildOptions(opts));\n }\n\n insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return post<(IdValue<E> | undefined)[]>(\n `${basePath}${CRUD_ROUTES.insertMany.path}`,\n payload,\n this.buildOptions(opts),\n );\n }\n\n async updateOneById<E extends object>(\n entity: Type<E>,\n id: EntityId<E>,\n payload: UpdatePayload<E>,\n opts?: RequestOptions,\n ) {\n const basePath = this.getBasePath(entity);\n return patch<number>(`${basePath}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));\n }\n\n updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(q);\n return patch<number>(`${basePath}${qs}`, payload, this.buildOptions(opts));\n }\n\n saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return put<EntityId<E> | undefined>(basePath, payload, this.buildOptions(opts));\n }\n\n saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions) {\n const basePath = this.getBasePath(entity);\n return put<(EntityId<E> | undefined)[]>(\n `${basePath}${CRUD_ROUTES.saveMany.path}`,\n payload,\n this.buildOptions(opts),\n );\n }\n\n async deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts: QueryOptions & RequestOptions = {}) {\n const basePath = this.getBasePath(entity);\n const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';\n return remove<number>(`${basePath}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));\n }\n\n deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts: QueryOptions & RequestOptions = {}) {\n const basePath = this.getBasePath(entity);\n const qs = stringifyQuery(opts.hardDelete ? { ...q, hardDelete: opts.hardDelete } : q);\n return remove<number>(`${basePath}${qs}`, this.buildOptions(opts));\n }\n\n getBasePath<E>(entity: Type<E>) {\n return `${this.basePath}/${(this.defaults.entityPath ?? entityPath)(entity)}`;\n }\n\n protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions) {\n if (this.defaults.readMethod === 'QUERY') {\n return httpQuery<T>(path, q ?? {}, this.buildOptions(opts));\n }\n return get<T>(`${path}${stringifyQuery(q)}`, this.buildOptions(opts));\n }\n\n protected buildOptions(opts?: RequestOptions): RequestOptions | undefined {\n if (!this.defaults.headers && !opts?.headers) {\n return opts;\n }\n return { ...opts, headers: { ...this.defaults.headers, ...opts?.headers } };\n }\n}\n",
|
|
13
13
|
"import { HttpQuerier } from './querier/httpQuerier.js';\nimport type { ClientQuerier, ClientQuerierPool } from './type/index.js';\n\nlet defaultPool: ClientQuerierPool = {\n getQuerier: () => new HttpQuerier('/api'),\n};\n\nexport function setQuerierPool<T extends ClientQuerierPool>(pool: T) {\n defaultPool = pool;\n}\n\nexport function getQuerierPool(): ClientQuerierPool {\n return defaultPool;\n}\n\nexport function getQuerier(): ClientQuerier {\n return getQuerierPool().getQuerier();\n}\n"
|
|
14
14
|
],
|
|
15
|
-
"mappings": "AAEA,IAAM,EAAkC,CAAC,EAElC,SAAS,CAAM,CAAC,EAAyC,CAC9D,QAAW,KAAe,EACxB,EAAY,CAAY,EAIrB,SAAS,CAAE,CAAC,EAAiC,CAClD,EAAa,KAAK,CAAE,EACpB,IAAM,EAAQ,EAA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EAAsB,CAClD,OAAO,EAGF,SAAS,EAAU,EAAkB,CAC1C,OAAO,EAAe,EAAE,WAAW",
|
|
16
16
|
"debugId": "565BC245D18F9E8464756E2164756E21",
|
|
17
17
|
"names": []
|
|
18
18
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, FieldOptions, InsertIdSource, NamingStrategy, QueryOptions, QueryWhere, QueryWhereMap } from '../type/index.js';
|
|
1
|
+
import type { DialectFeatures, DialectName, EntityMeta, ExtraOptions, FieldOptions, InsertIdSource, NamingStrategy, QueryGroupOp, QueryOptions, QueryWhere, QueryWhereArray, QueryWhereMap } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Options for initializing a dialect.
|
|
4
4
|
*/
|
|
@@ -77,4 +77,38 @@ export declare abstract class AbstractDialect {
|
|
|
77
77
|
* filters skipped. Recursion within one scope renders the returned map directly instead.
|
|
78
78
|
*/
|
|
79
79
|
protected scopedWhereMap<E>(meta: EntityMeta<E>, where?: QueryWhere<E>, opts?: QueryOptions): QueryWhereMap<E>;
|
|
80
|
+
/**
|
|
81
|
+
* How each clause-grouping operator renders: which operator joins its clauses, and whether the
|
|
82
|
+
* group is negated afterwards - so `$not` is `NOT (a AND b)` and `$nor` is `NOT (a OR b)`. SQL
|
|
83
|
+
* negates the rendered group; MongoDB spells the same thing with its own `$nor`.
|
|
84
|
+
*
|
|
85
|
+
* Total over {@link QueryGroupOp}, so a fifth operator cannot reach a dialect without both being
|
|
86
|
+
* told how to render it.
|
|
87
|
+
*/
|
|
88
|
+
protected static readonly GROUP_OPS: {
|
|
89
|
+
readonly $and: {
|
|
90
|
+
readonly join: '$and';
|
|
91
|
+
readonly negate: false;
|
|
92
|
+
};
|
|
93
|
+
readonly $or: {
|
|
94
|
+
readonly join: '$or';
|
|
95
|
+
readonly negate: false;
|
|
96
|
+
};
|
|
97
|
+
readonly $not: {
|
|
98
|
+
readonly join: '$and';
|
|
99
|
+
readonly negate: true;
|
|
100
|
+
};
|
|
101
|
+
readonly $nor: {
|
|
102
|
+
readonly join: '$or';
|
|
103
|
+
readonly negate: true;
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
/** Whether a `$where` key groups clauses, narrowing it for the renderers that read {@link GROUP_OPS}. */
|
|
107
|
+
protected static isGroupOp(key: string): key is QueryGroupOp;
|
|
108
|
+
/**
|
|
109
|
+
* A group operator's clauses, rejecting what the types do not cover: `/http` casts client JSON
|
|
110
|
+
* straight to `Query`, so a scalar can arrive where an array belongs. Shared so both backends
|
|
111
|
+
* refuse the same payload rather than one throwing and the other failing further in.
|
|
112
|
+
*/
|
|
113
|
+
protected static groupClauses<E>(key: QueryGroupOp, val: QueryWhereArray<E>): QueryWhereArray<E>;
|
|
80
114
|
}
|
|
@@ -88,4 +88,33 @@ export class AbstractDialect {
|
|
|
88
88
|
scopedWhereMap(meta, where = {}, opts) {
|
|
89
89
|
return applyFilters(meta, buildQueryWhereAsMap(meta, where), opts);
|
|
90
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* How each clause-grouping operator renders: which operator joins its clauses, and whether the
|
|
93
|
+
* group is negated afterwards - so `$not` is `NOT (a AND b)` and `$nor` is `NOT (a OR b)`. SQL
|
|
94
|
+
* negates the rendered group; MongoDB spells the same thing with its own `$nor`.
|
|
95
|
+
*
|
|
96
|
+
* Total over {@link QueryGroupOp}, so a fifth operator cannot reach a dialect without both being
|
|
97
|
+
* told how to render it.
|
|
98
|
+
*/
|
|
99
|
+
static GROUP_OPS = {
|
|
100
|
+
$and: { join: '$and', negate: false },
|
|
101
|
+
$or: { join: '$or', negate: false },
|
|
102
|
+
$not: { join: '$and', negate: true },
|
|
103
|
+
$nor: { join: '$or', negate: true },
|
|
104
|
+
};
|
|
105
|
+
/** Whether a `$where` key groups clauses, narrowing it for the renderers that read {@link GROUP_OPS}. */
|
|
106
|
+
static isGroupOp(key) {
|
|
107
|
+
return Object.hasOwn(AbstractDialect.GROUP_OPS, key);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A group operator's clauses, rejecting what the types do not cover: `/http` casts client JSON
|
|
111
|
+
* straight to `Query`, so a scalar can arrive where an array belongs. Shared so both backends
|
|
112
|
+
* refuse the same payload rather than one throwing and the other failing further in.
|
|
113
|
+
*/
|
|
114
|
+
static groupClauses(key, val) {
|
|
115
|
+
if (val !== undefined && !Array.isArray(val)) {
|
|
116
|
+
throw TypeError(`${key} expects an array, got ${val === null ? 'null' : typeof val}`);
|
|
117
|
+
}
|
|
118
|
+
return val ?? [];
|
|
119
|
+
}
|
|
91
120
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EntityMeta, type FieldKey, type FieldOptions, type IsolationLevel, type JsonColumnType, type JsonUpdateOp, type Query, type QueryAggMap, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryDialect, type QueryExclude, type QueryFilter, type QueryGroupMap, type QueryHavingMap, type QueryOptions, type QueryPager, QueryRaw, type QueryRawFnOptions, type QuerySearch, type QuerySelectOptions, type QuerySelectValue, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorNear, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOperatorMap, type QueryWhereMap, type QueryWhereOptions, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type Type, type UpdatePayload } from '../type/index.js';
|
|
1
|
+
import { type EntityMeta, type FieldKey, type FieldOptions, type IsolationLevel, type JsonColumnType, type JsonUpdateOp, type Query, type QueryAggMap, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryDialect, type QueryExclude, type QueryFilter, type QueryGroupMap, type QueryGroupOp, type QueryHavingMap, type QueryOptions, type QueryPager, QueryRaw, type QueryRawFnOptions, type QuerySearch, type QuerySelectOptions, type QuerySelectValue, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorNear, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOperatorMap, type QueryWhereMap, type QueryWhereOptions, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type Type, type UpdatePayload } from '../type/index.js';
|
|
2
2
|
import { type ParentPartition } from '../util/index.js';
|
|
3
3
|
import type { HydrateKind } from './hydrateColumn.js';
|
|
4
4
|
import { type JsonAccessMode } from './jsonSql.js';
|
|
@@ -76,6 +76,15 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
76
76
|
* shared for the same reason - see {@link SqlQueryContext}.
|
|
77
77
|
*/
|
|
78
78
|
protected buildFragment(ctx: QueryContext, build: QueryBuildFn): string;
|
|
79
|
+
/**
|
|
80
|
+
* Each operand rendered into its own fragment, keeping only those that emitted SQL.
|
|
81
|
+
*
|
|
82
|
+
* Nothing reaches `ctx` until every one has rendered, because an operand that emits nothing - an
|
|
83
|
+
* empty `$and`, an `{}` entry - must leave behind neither a dangling separator nor a clause with no
|
|
84
|
+
* condition after it. How many terms really emit is also what decides the parentheses, which is why
|
|
85
|
+
* the caller counts what comes back rather than what it passed in.
|
|
86
|
+
*/
|
|
87
|
+
protected renderOperands<T>(ctx: QueryContext, operands: readonly T[], render: (ctx: QueryContext, operand: T) => void): string[];
|
|
79
88
|
addValue(values: unknown[], value: unknown): string;
|
|
80
89
|
/**
|
|
81
90
|
* Normalizes a parameter value for the database driver.
|
|
@@ -134,13 +143,12 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
134
143
|
protected selectRelationFields(ctx: QueryContext, joins: QueryJoins): void;
|
|
135
144
|
protected selectRelationJoins<E>(ctx: QueryContext, meta: EntityMeta<E>, rootAlias: string, joins: QueryJoins): void;
|
|
136
145
|
where<E>(ctx: QueryContext, entity: Type<E>, where?: QueryWhere<E>, opts?: QueryWhereOptions): void;
|
|
137
|
-
/** Renders a `$where` tree without applying entity filters (used for same-scope
|
|
146
|
+
/** Renders a `$where` tree without applying entity filters (used for same-scope group-operator recursion). */
|
|
138
147
|
protected renderWhere<E>(ctx: QueryContext, entity: Type<E>, where?: QueryWhere<E>, opts?: QueryWhereOptions): void;
|
|
139
148
|
compare<E>(ctx: QueryContext, entity: Type<E>, key: string, val: unknown, opts?: QueryComparisonOptions): void;
|
|
140
|
-
protected compareLogicalOperator<E>(ctx: QueryContext, entity: Type<E>, key:
|
|
149
|
+
protected compareLogicalOperator<E>(ctx: QueryContext, entity: Type<E>, key: QueryGroupOp, val: QueryWhereArray<E>, opts: QueryComparisonOptions): void;
|
|
141
150
|
/** Memoizes {@link escapedColumnName}; see there for why it is per dialect instance. */
|
|
142
151
|
private readonly escapedColumns;
|
|
143
|
-
private static readonly NEGATE_OP_MAP;
|
|
144
152
|
private static readonly COMPARE_OP_MAP;
|
|
145
153
|
/** What a `$near` says about the search itself; everything else in it is a bound. */
|
|
146
154
|
private static readonly VECTOR_QUERY_KEYS;
|
|
@@ -179,7 +187,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
179
187
|
/** Builds `prefix.column` from an already-resolved field, through the same memo writes use. */
|
|
180
188
|
private columnWithPrefix;
|
|
181
189
|
/**
|
|
182
|
-
* The SQL a field comparison reads its left-hand side from.
|
|
190
|
+
* The SQL a field comparison reads its left-hand side from. An inlined field builds its expression
|
|
183
191
|
* as text rather than appending it, so every operator gets a real operand to wrap - `LOWER(...)`,
|
|
184
192
|
* `NOT (... <=> ...)` - instead of having to fall back to a form that takes none.
|
|
185
193
|
*/
|
|
@@ -100,6 +100,19 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
100
100
|
build(fragmentCtx);
|
|
101
101
|
return fragmentCtx.sql;
|
|
102
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Each operand rendered into its own fragment, keeping only those that emitted SQL.
|
|
105
|
+
*
|
|
106
|
+
* Nothing reaches `ctx` until every one has rendered, because an operand that emits nothing - an
|
|
107
|
+
* empty `$and`, an `{}` entry - must leave behind neither a dangling separator nor a clause with no
|
|
108
|
+
* condition after it. How many terms really emit is also what decides the parentheses, which is why
|
|
109
|
+
* the caller counts what comes back rather than what it passed in.
|
|
110
|
+
*/
|
|
111
|
+
renderOperands(ctx, operands, render) {
|
|
112
|
+
return operands
|
|
113
|
+
.map((operand) => this.buildFragment(ctx, (fragmentCtx) => render(fragmentCtx, operand)))
|
|
114
|
+
.filter((part) => part !== '');
|
|
115
|
+
}
|
|
103
116
|
addValue(values, value) {
|
|
104
117
|
values.push(this.normalizeValue(value));
|
|
105
118
|
return this.placeholder(values.length);
|
|
@@ -190,10 +203,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
190
203
|
if (!field)
|
|
191
204
|
return;
|
|
192
205
|
if (isInlinedExpression(field)) {
|
|
206
|
+
// Qualified even when nothing else in this statement is: the expression is spliced in, and
|
|
207
|
+
// one that opens a correlated subquery has the inner table's columns in scope, so a bare
|
|
208
|
+
// `"id"` would bind to *that* table instead of this one. `SELECT "Item"."id" FROM "Item"`
|
|
209
|
+
// is valid on every engine, so naming the table costs nothing where it is not needed.
|
|
210
|
+
const qualified = opts.prefix ?? this.resolveTableAlias(meta);
|
|
193
211
|
this.getRawValue(ctx, {
|
|
194
212
|
value: computedExpression(field).as(key),
|
|
195
|
-
prefix:
|
|
196
|
-
escapedPrefix,
|
|
213
|
+
prefix: qualified,
|
|
214
|
+
escapedPrefix: this.escapeId(qualified, true, true),
|
|
197
215
|
autoPrefixAlias: opts.autoPrefixAlias,
|
|
198
216
|
});
|
|
199
217
|
return;
|
|
@@ -306,40 +324,29 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
306
324
|
// Filters are applied once, here at the scope entry point; recursion uses `renderWhere`.
|
|
307
325
|
this.renderWhere(ctx, entity, this.scopedWhereMap(meta, where, opts), opts);
|
|
308
326
|
}
|
|
309
|
-
/** Renders a `$where` tree without applying entity filters (used for same-scope
|
|
327
|
+
/** Renders a `$where` tree without applying entity filters (used for same-scope group-operator recursion). */
|
|
310
328
|
renderWhere(ctx, entity, where = {}, opts = {}) {
|
|
311
329
|
const meta = getMeta(entity);
|
|
312
330
|
const { clause = 'WHERE' } = opts;
|
|
313
|
-
|
|
331
|
+
const whereMap = buildQueryWhereAsMap(meta, where);
|
|
314
332
|
// An `undefined` value emits nothing, so it must not count towards the terms either: it decides
|
|
315
|
-
//
|
|
316
|
-
const whereKeys = getKeys(
|
|
317
|
-
|
|
333
|
+
// whether the keys below render as operands of an `AND`.
|
|
334
|
+
const whereKeys = getKeys(whereMap).filter((key) => whereMap[key] !== undefined);
|
|
335
|
+
// Each key is an operand of the `AND` joining them; a lone key emits this fragment verbatim, so
|
|
336
|
+
// it inherits this one's position instead.
|
|
337
|
+
const childOperand = whereKeys.length > 1 || opts.operand || clause === 'AND';
|
|
338
|
+
const childOpts = opts.operand === childOperand ? opts : { ...opts, operand: childOperand };
|
|
339
|
+
const parts = this.renderOperands(ctx, whereKeys, (fragmentCtx, key) => this.compare(fragmentCtx, entity, key, whereMap[key], childOpts));
|
|
340
|
+
if (!parts.length) {
|
|
318
341
|
return;
|
|
319
342
|
}
|
|
320
343
|
if (clause) {
|
|
321
344
|
ctx.append(` ${clause} `);
|
|
322
345
|
}
|
|
323
|
-
const multipleKeys = whereKeys.length > 1;
|
|
324
346
|
// This fragment joins its own keys with `AND`, so appending it after one (a JOIN's `ON`) needs no
|
|
325
347
|
// parentheses - but anything nested in it is still an operand, since that may be an `OR`.
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
ctx.append('(');
|
|
329
|
-
}
|
|
330
|
-
// Each key is an operand of the `AND` joining them; a lone key emits this fragment verbatim, so
|
|
331
|
-
// it inherits this one's position instead.
|
|
332
|
-
const childOperand = multipleKeys || opts.operand || clause === 'AND';
|
|
333
|
-
const childOpts = opts.operand === childOperand ? opts : { ...opts, operand: childOperand };
|
|
334
|
-
whereKeys.forEach((key, index) => {
|
|
335
|
-
if (index > 0) {
|
|
336
|
-
ctx.append(' AND ');
|
|
337
|
-
}
|
|
338
|
-
this.compare(ctx, entity, key, where[key], childOpts);
|
|
339
|
-
});
|
|
340
|
-
if (parenthesize) {
|
|
341
|
-
ctx.append(')');
|
|
342
|
-
}
|
|
348
|
+
const body = parts.join(' AND ');
|
|
349
|
+
ctx.append(parts.length > 1 && opts.operand ? `(${body})` : body);
|
|
343
350
|
}
|
|
344
351
|
compare(ctx, entity, key, val, opts = {}) {
|
|
345
352
|
const meta = getMeta(entity);
|
|
@@ -366,7 +373,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
366
373
|
this.appendTextSearch(ctx, entity, meta, val);
|
|
367
374
|
return;
|
|
368
375
|
}
|
|
369
|
-
if (key
|
|
376
|
+
if (AbstractSqlDialect.isGroupOp(key)) {
|
|
370
377
|
this.compareLogicalOperator(ctx, entity, key, val, opts);
|
|
371
378
|
return;
|
|
372
379
|
}
|
|
@@ -405,43 +412,29 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
405
412
|
}
|
|
406
413
|
}
|
|
407
414
|
compareLogicalOperator(ctx, entity, key, val, opts) {
|
|
408
|
-
const
|
|
409
|
-
const
|
|
410
|
-
if (val !== undefined && !Array.isArray(val)) {
|
|
411
|
-
// Not covered by the types: `/http` casts client JSON straight to `Query`, so this arrives untyped.
|
|
412
|
-
throw TypeError(`${key} expects an array, got ${val === null ? 'null' : typeof val}`);
|
|
413
|
-
}
|
|
414
|
-
const items = val ?? [];
|
|
415
|
+
const { join, negate } = AbstractSqlDialect.GROUP_OPS[key];
|
|
416
|
+
const items = AbstractSqlDialect.groupClauses(key, val);
|
|
415
417
|
// With more than one item each is an operand of the operator joining them, so a compound item
|
|
416
418
|
// parenthesizes itself and precedence never applies; a lone item is this group verbatim, so it
|
|
417
419
|
// inherits the group's own position. A negation always makes its subject an operand.
|
|
418
420
|
const childOperand = items.length > 1 || negate || opts.operand;
|
|
419
|
-
|
|
420
|
-
// `undefined` entry) must leave no dangling separator behind, and how many terms this fragment
|
|
421
|
-
// really emits is what decides whether it needs parentheses.
|
|
422
|
-
const parts = items
|
|
423
|
-
.map((entry) => this.buildFragment(ctx, (fragmentCtx) => {
|
|
421
|
+
const parts = this.renderOperands(ctx, items, (fragmentCtx, entry) => {
|
|
424
422
|
if (entry instanceof QueryRaw) {
|
|
425
423
|
this.getRawValue(fragmentCtx, { value: entry });
|
|
426
424
|
}
|
|
427
425
|
else if (entry) {
|
|
428
426
|
this.renderWhere(fragmentCtx, entity, entry, { prefix: opts.prefix, operand: childOperand, clause: false });
|
|
429
427
|
}
|
|
430
|
-
})
|
|
431
|
-
.filter((part) => part !== '');
|
|
428
|
+
});
|
|
432
429
|
if (!parts.length) {
|
|
433
430
|
return;
|
|
434
431
|
}
|
|
435
|
-
const body = parts.join(
|
|
432
|
+
const body = parts.join(join === '$or' ? ' OR ' : ' AND ');
|
|
436
433
|
const parenthesize = parts.length > 1 && (opts.operand || negate);
|
|
437
434
|
ctx.append((negate ? 'NOT ' : '') + (parenthesize ? `(${body})` : body));
|
|
438
435
|
}
|
|
439
436
|
/** Memoizes {@link escapedColumnName}; see there for why it is per dialect instance. */
|
|
440
437
|
escapedColumns = new WeakMap();
|
|
441
|
-
static NEGATE_OP_MAP = new Map([
|
|
442
|
-
['$not', '$and'],
|
|
443
|
-
['$nor', '$or'],
|
|
444
|
-
]);
|
|
445
438
|
static COMPARE_OP_MAP = new Map([
|
|
446
439
|
['$gt', ' > '],
|
|
447
440
|
['$gte', ' >= '],
|
|
@@ -508,13 +501,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
508
501
|
return this.escapeId(prefix, true, true) + this.escapedColumnOf(key, field);
|
|
509
502
|
}
|
|
510
503
|
/**
|
|
511
|
-
* The SQL a field comparison reads its left-hand side from.
|
|
504
|
+
* The SQL a field comparison reads its left-hand side from. An inlined field builds its expression
|
|
512
505
|
* as text rather than appending it, so every operator gets a real operand to wrap - `LOWER(...)`,
|
|
513
506
|
* `NOT (... <=> ...)` - instead of having to fall back to a form that takes none.
|
|
514
507
|
*/
|
|
515
508
|
resolveOperandField(ctx, entity, key, opts) {
|
|
516
|
-
const
|
|
517
|
-
|
|
509
|
+
const meta = getMeta(entity);
|
|
510
|
+
const field = meta.fields[key];
|
|
511
|
+
return (this.inlinedOperand(ctx, field, opts.prefix ?? this.resolveTableAlias(meta)) ??
|
|
512
|
+
this.columnWithPrefix(key, field, opts.prefix));
|
|
518
513
|
}
|
|
519
514
|
/**
|
|
520
515
|
* The expression an inlined computed field stands for, or nothing when the field is a real column.
|
|
@@ -814,7 +809,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
814
809
|
sortColumn(ctx, meta, key, prefix) {
|
|
815
810
|
const field = meta.fields[key];
|
|
816
811
|
if (field) {
|
|
817
|
-
return this.inlinedOperand(ctx, field, prefix
|
|
812
|
+
return (this.inlinedOperand(ctx, field, prefix ?? this.resolveTableAlias(meta)) ??
|
|
813
|
+
this.columnWithPrefix(key, field, prefix));
|
|
818
814
|
}
|
|
819
815
|
const json = this.resolveJsonDotPath(meta, key, prefix);
|
|
820
816
|
return json ? this.jsonPathExpr(json.column, json.jsonPath, 'text') : this.escapeId(key);
|
|
@@ -80,6 +80,8 @@ export declare const BeforeInsert: () => <This>(_value: unknown, context: ClassM
|
|
|
80
80
|
export declare const AfterInsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
81
81
|
export declare const BeforeUpdate: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
82
82
|
export declare const AfterUpdate: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
83
|
+
export declare const BeforeUpsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
84
|
+
export declare const AfterUpsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
83
85
|
export declare const BeforeDelete: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
84
86
|
export declare const AfterDelete: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
85
87
|
export declare const AfterLoad: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
|
|
@@ -55,6 +55,8 @@ export const BeforeInsert = hook('beforeInsert');
|
|
|
55
55
|
export const AfterInsert = hook('afterInsert');
|
|
56
56
|
export const BeforeUpdate = hook('beforeUpdate');
|
|
57
57
|
export const AfterUpdate = hook('afterUpdate');
|
|
58
|
+
export const BeforeUpsert = hook('beforeUpsert');
|
|
59
|
+
export const AfterUpsert = hook('afterUpsert');
|
|
58
60
|
export const BeforeDelete = hook('beforeDelete');
|
|
59
61
|
export const AfterDelete = hook('afterDelete');
|
|
60
62
|
export const AfterLoad = hook('afterLoad');
|
package/dist/entity/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export * from './decorator/entity.js';
|
|
2
2
|
export * from './decorator/members.js';
|
|
3
|
-
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, getEntities, getMeta, removeEntity, assertSoleId, idOf, soleIdOf, } from './metadata/definition.js';
|
|
3
|
+
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, getEntities, getMeta, removeEntity, assertSoleId, idOf, namesKey, soleIdOf, } from './metadata/definition.js';
|
package/dist/entity/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export * from './decorator/entity.js';
|
|
2
2
|
export * from './decorator/members.js';
|
|
3
|
-
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, getEntities, getMeta, removeEntity, assertSoleId, idOf, soleIdOf, } from './metadata/definition.js';
|
|
3
|
+
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, getEntities, getMeta, removeEntity, assertSoleId, idOf, namesKey, soleIdOf, } from './metadata/definition.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityId, EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldKey, FieldOptions, FilterOptions, HookEvent, IdKey, RelationOptions, Type } from '../../type/index.js';
|
|
1
|
+
import type { EntityData, EntityId, EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldKey, FieldOptions, FilterOptions, HookEvent, IdKey, RelationOptions, Type } from '../../type/index.js';
|
|
2
2
|
export declare function defineField<E>(entity: Type<E>, key: string, opts?: FieldOptions): EntityMeta<E>;
|
|
3
3
|
export declare function defineId<E>(entity: Type<E>, key: string, opts: FieldOptions): EntityMeta<E>;
|
|
4
4
|
export declare function defineRelation<E>(entity: Type<E>, key: string, opts: RelationOptions): EntityMeta<E>;
|
|
@@ -30,6 +30,15 @@ export declare function defineEntity<E>(entity: Type<E>, opts?: EntityOptions<E>
|
|
|
30
30
|
export declare function assertSoleId<E>(meta: EntityMeta<E>, what: string): void;
|
|
31
31
|
/** The entity's one primary key, for a path that cannot express a composite. See {@link assertSoleId}. */
|
|
32
32
|
export declare function soleIdOf<E>(meta: EntityMeta<E>, what: string): IdKey<E>;
|
|
33
|
+
/**
|
|
34
|
+
* Whether the caller named every column of the row's primary key, so {@link idOf} can name the row.
|
|
35
|
+
*
|
|
36
|
+
* `!= null` rather than falsiness: `0` and an empty string are ids a row can legitimately carry, and
|
|
37
|
+
* reading them as "no id" is how a write of that row turned into a second insert. Distinct from
|
|
38
|
+
* "does the row carry this column", which an insert asks of `undefined` alone because that is what
|
|
39
|
+
* decides whether the column appears in its `VALUES` list at all.
|
|
40
|
+
*/
|
|
41
|
+
export declare function namesKey<E>(meta: EntityMeta<E>, row: EntityData<E>): boolean;
|
|
33
42
|
/**
|
|
34
43
|
* A row's primary key in the shape a `$where` takes: the value itself for a single key, an object
|
|
35
44
|
* carrying every key for a composite - which is exactly {@link EntityId}.
|
|
@@ -37,7 +46,7 @@ export declare function soleIdOf<E>(meta: EntityMeta<E>, what: string): IdKey<E>
|
|
|
37
46
|
* What a settled write names its rows by, and what an insert hands back. Naming a composite row by
|
|
38
47
|
* one of its columns would address every row agreeing on that one.
|
|
39
48
|
*/
|
|
40
|
-
export declare function idOf<E>(meta: EntityMeta<E>, row: E): EntityId<E>;
|
|
49
|
+
export declare function idOf<E>(meta: EntityMeta<E>, row: EntityData<E>): EntityId<E>;
|
|
41
50
|
/**
|
|
42
51
|
* Forgets an entity, and reports whether there was one - for a registry that grows at runtime, where a
|
|
43
52
|
* deleted content type would otherwise keep its metadata for the life of the process. Nothing rewrites
|
|
@@ -223,6 +223,17 @@ export function soleIdOf(meta, what) {
|
|
|
223
223
|
assertSoleId(meta, what);
|
|
224
224
|
return meta.ids[0];
|
|
225
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* Whether the caller named every column of the row's primary key, so {@link idOf} can name the row.
|
|
228
|
+
*
|
|
229
|
+
* `!= null` rather than falsiness: `0` and an empty string are ids a row can legitimately carry, and
|
|
230
|
+
* reading them as "no id" is how a write of that row turned into a second insert. Distinct from
|
|
231
|
+
* "does the row carry this column", which an insert asks of `undefined` alone because that is what
|
|
232
|
+
* decides whether the column appears in its `VALUES` list at all.
|
|
233
|
+
*/
|
|
234
|
+
export function namesKey(meta, row) {
|
|
235
|
+
return meta.ids.every((key) => row[key] != null);
|
|
236
|
+
}
|
|
226
237
|
/**
|
|
227
238
|
* A row's primary key in the shape a `$where` takes: the value itself for a single key, an object
|
|
228
239
|
* carrying every key for a composite - which is exactly {@link EntityId}.
|