uql-orm 0.41.1 → 0.42.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/querier/httpQuerier.d.ts +7 -7
- package/dist/browser/querier/httpQuerier.js +21 -6
- package/dist/browser/type/clientQuerier.d.ts +3 -3
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +4 -4
- package/dist/dialect/abstractSqlDialect.d.ts +32 -3
- package/dist/dialect/abstractSqlDialect.js +58 -22
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +3 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +5 -3
- package/dist/dialect/pgLikeSqlDialect.d.ts +1 -1
- package/dist/dialect/pgLikeSqlDialect.js +2 -1
- package/dist/entity/decorator/entity.d.ts +1 -1
- package/dist/entity/decorator/entity.js +1 -1
- package/dist/entity/decorator/members.d.ts +10 -2
- package/dist/entity/index.d.ts +1 -1
- package/dist/entity/index.js +1 -1
- package/dist/entity/metadata/definition.d.ts +18 -1
- package/dist/entity/metadata/definition.js +91 -36
- package/dist/http/handler.js +4 -4
- package/dist/maria/mariaDialect.d.ts +2 -2
- package/dist/maria/mariaDialect.js +3 -2
- package/dist/migrate/builder/tableBuilder.js +5 -4
- package/dist/migrate/drift/driftDetector.js +16 -0
- package/dist/migrate/generator/mongoSchemaGenerator.d.ts +7 -0
- package/dist/migrate/generator/mongoSchemaGenerator.js +24 -28
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +9 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
- package/dist/migrate/introspection/baseSqlIntrospector.js +6 -3
- package/dist/migrate/introspection/postgresIntrospector.js +1 -1
- package/dist/migrate/introspection/sqliteIntrospector.js +7 -3
- package/dist/migrate/migrator.js +6 -0
- package/dist/migrate/schemaGenerator.d.ts +44 -34
- package/dist/migrate/schemaGenerator.js +158 -141
- package/dist/mongo/mongoDialect.js +39 -14
- package/dist/mongo/mongodbQuerier.js +6 -3
- package/dist/postgres/postgresDialect.js +1 -1
- package/dist/querier/abstractQuerier.d.ts +16 -12
- package/dist/querier/abstractQuerier.js +88 -40
- package/dist/querier/abstractQuerierPool.d.ts +8 -8
- package/dist/querier/abstractSqlQuerier.d.ts +1 -1
- package/dist/querier/abstractSqlQuerier.js +12 -7
- package/dist/querier/relationCount.js +44 -33
- package/dist/schema/indexDifferences.d.ts +28 -0
- package/dist/schema/indexDifferences.js +46 -0
- package/dist/schema/schemaASTBuilder.js +38 -31
- package/dist/schema/schemaASTDiffer.d.ts +27 -1
- package/dist/schema/schemaASTDiffer.js +54 -18
- package/dist/schema/types.d.ts +46 -7
- package/dist/sqlite/sqliteDialect.d.ts +2 -1
- package/dist/sqlite/sqliteDialect.js +4 -1
- package/dist/type/dialect.d.ts +6 -0
- package/dist/type/entity.d.ts +57 -14
- package/dist/type/migration.d.ts +19 -0
- package/dist/type/queryWhere.d.ts +7 -2
- package/dist/type/universalQuerier.d.ts +8 -8
- package/dist/util/dialect.util.js +15 -14
- package/dist/util/field.util.d.ts +11 -1
- package/dist/util/field.util.js +12 -0
- package/dist/util/index.d.ts +1 -0
- package/dist/util/index.js +1 -0
- package/dist/util/object.util.d.ts +6 -0
- package/dist/util/object.util.js +18 -0
- package/dist/util/relationQuery.util.d.ts +48 -7
- package/dist/util/relationQuery.util.js +70 -9
- package/dist/util/rowKey.util.d.ts +9 -0
- package/dist/util/rowKey.util.js +24 -0
- package/dist/util/sql.util.d.ts +24 -7
- package/dist/util/sql.util.js +75 -10
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type HttpMethod } from '../../http/contract.js';
|
|
2
|
-
import type { EntityData, FieldKey, IdValue, QueryFilter, QueryFindResult, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, RelationKey, RequestCountedSuccessResponse, RequestSuccessResponse, Type, UpdatePayload } from '../../type/index.js';
|
|
2
|
+
import type { EntityData, EntityId, FieldKey, IdValue, QueryFilter, QueryFindResult, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, RelationKey, RequestCountedSuccessResponse, RequestSuccessResponse, Type, UpdatePayload } from '../../type/index.js';
|
|
3
3
|
import type { ClientQuerier, RequestFindOptions, RequestOptions } from '../type/index.js';
|
|
4
4
|
export type HttpQuerierDefaults = {
|
|
5
5
|
/**
|
|
@@ -18,7 +18,7 @@ export declare class HttpQuerier implements ClientQuerier {
|
|
|
18
18
|
readonly basePath: string;
|
|
19
19
|
readonly defaults: HttpQuerierDefaults;
|
|
20
20
|
constructor(basePath: string, defaults?: HttpQuerierDefaults);
|
|
21
|
-
findOneById<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, id:
|
|
21
|
+
findOneById<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, id: EntityId<E>, q?: QueryOneProjected<E, S, V, X, P, C>, opts?: RequestOptions): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>>;
|
|
22
22
|
findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryOneProjected<E, S, V, X, P, C>, opts?: RequestOptions): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C> | undefined>>;
|
|
23
23
|
findMany<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: RequestFindOptions): Promise<RequestSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>>;
|
|
24
24
|
findManyAndCount<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: RequestFindOptions): Promise<RequestCountedSuccessResponse<QueryFindResult<E, S, V, X, P, C>[]>>;
|
|
@@ -29,12 +29,12 @@ export declare class HttpQuerier implements ClientQuerier {
|
|
|
29
29
|
data: boolean;
|
|
30
30
|
}>;
|
|
31
31
|
insertOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<IdValue<E> | undefined>>;
|
|
32
|
-
insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<IdValue<E>[]>>;
|
|
33
|
-
updateOneById<E extends object>(entity: Type<E>, id:
|
|
32
|
+
insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<(IdValue<E> | undefined)[]>>;
|
|
33
|
+
updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdatePayload<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
34
34
|
updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
35
|
-
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<IdValue<E
|
|
36
|
-
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<IdValue<E>[]>>;
|
|
37
|
-
deleteOneById<E extends object>(entity: Type<E>, id:
|
|
35
|
+
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): Promise<RequestSuccessResponse<IdValue<E> | undefined>>;
|
|
36
|
+
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): Promise<RequestSuccessResponse<(IdValue<E> | undefined)[]>>;
|
|
37
|
+
deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
38
38
|
deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & RequestOptions): Promise<RequestSuccessResponse<number>>;
|
|
39
39
|
getBasePath<E>(entity: Type<E>): string;
|
|
40
40
|
protected read<T>(path: string, q: Record<string, unknown> | undefined, opts?: RequestOptions): Promise<RequestSuccessResponse<T>>;
|
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import { CRUD_ROUTES, entityPath } from '../../http/contract.js';
|
|
2
2
|
import { stringifyQuery } from '../../http/query.js';
|
|
3
|
+
import { isScalarId } from '../../util/object.util.js';
|
|
3
4
|
import { get, query as httpQuery, patch, post, put, remove } from '../http/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* The id as one path segment.
|
|
7
|
+
*
|
|
8
|
+
* A composite key has no spelling here yet - the route is `/:id`, and how several columns share one
|
|
9
|
+
* segment is a serialization to invent rather than copy. Refused rather than interpolated, which
|
|
10
|
+
* would have sent `[object Object]` for the server to reject. Its callers are `async` so this
|
|
11
|
+
* surfaces as a rejection, like every other failure they can hand back.
|
|
12
|
+
*/
|
|
13
|
+
function idSegment(entity, id) {
|
|
14
|
+
if (!isScalarId(id)) {
|
|
15
|
+
throw new TypeError(`'${entity.name}' was addressed by an id object, which the HTTP route cannot carry.`);
|
|
16
|
+
}
|
|
17
|
+
return String(id);
|
|
18
|
+
}
|
|
4
19
|
export class HttpQuerier {
|
|
5
20
|
basePath;
|
|
6
21
|
defaults;
|
|
@@ -8,10 +23,10 @@ export class HttpQuerier {
|
|
|
8
23
|
this.basePath = basePath;
|
|
9
24
|
this.defaults = defaults;
|
|
10
25
|
}
|
|
11
|
-
findOneById(entity, id, q, opts) {
|
|
26
|
+
async findOneById(entity, id, q, opts) {
|
|
12
27
|
const basePath = this.getBasePath(entity);
|
|
13
28
|
const qs = stringifyQuery(q);
|
|
14
|
-
return get(`${basePath}/${id}${qs}`, this.buildOptions(opts));
|
|
29
|
+
return get(`${basePath}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));
|
|
15
30
|
}
|
|
16
31
|
findOne(entity, q, opts) {
|
|
17
32
|
return this.read(`${this.getBasePath(entity)}${CRUD_ROUTES.findOne.path}`, q, opts);
|
|
@@ -46,9 +61,9 @@ export class HttpQuerier {
|
|
|
46
61
|
const basePath = this.getBasePath(entity);
|
|
47
62
|
return post(`${basePath}${CRUD_ROUTES.insertMany.path}`, payload, this.buildOptions(opts));
|
|
48
63
|
}
|
|
49
|
-
updateOneById(entity, id, payload, opts) {
|
|
64
|
+
async updateOneById(entity, id, payload, opts) {
|
|
50
65
|
const basePath = this.getBasePath(entity);
|
|
51
|
-
return patch(`${basePath}/${id}`, payload, this.buildOptions(opts));
|
|
66
|
+
return patch(`${basePath}/${idSegment(entity, id)}`, payload, this.buildOptions(opts));
|
|
52
67
|
}
|
|
53
68
|
updateMany(entity, q, payload, opts) {
|
|
54
69
|
const basePath = this.getBasePath(entity);
|
|
@@ -63,10 +78,10 @@ export class HttpQuerier {
|
|
|
63
78
|
const basePath = this.getBasePath(entity);
|
|
64
79
|
return put(`${basePath}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts));
|
|
65
80
|
}
|
|
66
|
-
deleteOneById(entity, id, opts = {}) {
|
|
81
|
+
async deleteOneById(entity, id, opts = {}) {
|
|
67
82
|
const basePath = this.getBasePath(entity);
|
|
68
83
|
const qs = opts.hardDelete ? stringifyQuery({ hardDelete: opts.hardDelete }) : '';
|
|
69
|
-
return remove(`${basePath}/${id}${qs}`, this.buildOptions(opts));
|
|
84
|
+
return remove(`${basePath}/${idSegment(entity, id)}${qs}`, this.buildOptions(opts));
|
|
70
85
|
}
|
|
71
86
|
deleteMany(entity, q, opts = {}) {
|
|
72
87
|
const basePath = this.getBasePath(entity);
|
|
@@ -8,7 +8,7 @@ import type { RequestOptions } from './request.js';
|
|
|
8
8
|
*/
|
|
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
|
-
insertMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): QuerierResult<'client', IdValue<E>[]>;
|
|
12
|
-
saveOne<E extends object>(entity: Type<E>, payload: EntityData<E>, opts?: RequestOptions): QuerierResult<'client', IdValue<E
|
|
13
|
-
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): QuerierResult<'client', IdValue<E>[]>;
|
|
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', IdValue<E> | undefined>;
|
|
13
|
+
saveMany<E extends object>(entity: Type<E>, payload: EntityData<E>[], opts?: RequestOptions): QuerierResult<'client', (IdValue<E> | undefined)[]>;
|
|
14
14
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=[];function a(e){for(let t of d)t(e)}function q(e){d.push(e);let t=d.length-1;return()=>{d.splice(t,1)}}class g extends Error{status;constructor(e,t){super(e);this.status=t;this.name="RequestError"}}function l(e,t){return i(e,{method:"get"},t)}function E(e,t,n){let r=JSON.stringify(t);return i(e,{method:"post",body:r},n)}function f(e,t,n){let r=JSON.stringify(t);return i(e,{method:"patch",body:r},n)}function h(e,t,n){let r=JSON.stringify(t);return i(e,{method:"put",body:r},n)}function x(e,t){return i(e,{method:"delete"},t)}function m(e,t,n){let r=JSON.stringify(t);return i(e,{method:"QUERY",body:r},n)}function i(e,t,n){if(a({phase:"start",opts:n}),t.headers={accept:"application/json","content-type":"application/json",...n?.headers},n?.signal)t.signal=n.signal;return fetch(e,t).then((r)=>r.json().then((o)=>{if(r.status>=200&&r.status<300)return a({phase:"success",opts:n}),o;let P=o,c={message:P?.error?.message??r.statusText,code:P?.error?.code??r.status};throw a({phase:"error",error:c,opts:n}),new g(c.message,c.code)})).finally(()=>{a({phase:"complete",opts:n})})}function p(e){return e?Object.keys(e):[]}function S(e){if(typeof e!=="object"||e===null)return!0;if(Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null}function O(e){let t=e.charAt(0).toLowerCase();for(let n=1;n<e.length;++n)t+=e[n]===e[n].toUpperCase()?"-"+e[n].toLowerCase():e[n];return t}var s={findMany:{method:"GET",path:""},findOne:{method:"GET",path:"/one"},count:{method:"GET",path:"/count"},findOneById:{method:"GET",path:"/:id"},insertOne:{method:"POST",path:""},insertMany:{method:"POST",path:"/many"},saveOne:{method:"PUT",path:""},saveMany:{method:"PUT",path:"/many"},updateMany:{method:"PATCH",path:""},updateOneById:{method:"PATCH",path:"/:id"},deleteOneById:{method:"DELETE",path:"/:id"},deleteMany:{method:"DELETE",path:""}},j=p(s),A=new Map(j.filter((e)=>s[e].method==="GET"&&s[e].path!=="/:id").map((e)=>[s[e].path,e]));function K(e){return O(e.name)}var T=["$select","$populate","$exclude","$where","$sort"],C=["$count"],b=["$skip","$limit"],k=["$candidates"],U=["$distinct"];var W=new Set([...T,...C,...b,...k,...U,"hardDelete","count"]);function u(e){if(!e)return"";let t=new URLSearchParams;for(let r of p(e)){let o=e[r];if(o===void 0)continue;t.append(r,typeof o==="object"&&o!==null?JSON.stringify(o):String(o))}let n=t.toString();return n?`?${n}`:""}function R(e,t){if(!S(t))throw TypeError(`'${e.name}' was addressed by an id object, which the HTTP route cannot carry.`);return String(t)}class Q{basePath;defaults;constructor(e,t={}){this.basePath=e;this.defaults=t}async findOneById(e,t,n,r){let o=this.getBasePath(e),y=u(n);return l(`${o}/${R(e,t)}${y}`,this.buildOptions(r))}findOne(e,t,n){return this.read(`${this.getBasePath(e)}${s.findOne.path}`,t,n)}findMany(e,t,n){let r={...t};if(n?.count)r.count=!0;return this.read(this.getBasePath(e),r,n)}async findManyAndCount(e,t,n){let r=await this.findMany(e,t,{...n,count:!0});if(typeof r.count!=="number")throw TypeError("findManyAndCount response has an invalid count");return{...r,count:r.count}}count(e,t,n){return this.read(`${this.getBasePath(e)}${s.count.path}`,t,n)}async exists(e,t,n){let r=await this.count(e,{...t,$limit:1},n);return{...r,data:r.data>0}}insertOne(e,t,n){let r=this.getBasePath(e);return E(r,t,this.buildOptions(n))}insertMany(e,t,n){let r=this.getBasePath(e);return E(`${r}${s.insertMany.path}`,t,this.buildOptions(n))}async updateOneById(e,t,n,r){let o=this.getBasePath(e);return f(`${o}/${R(e,t)}`,n,this.buildOptions(r))}updateMany(e,t,n,r){let o=this.getBasePath(e),y=u(t);return f(`${o}${y}`,n,this.buildOptions(r))}saveOne(e,t,n){let r=this.getBasePath(e);return h(r,t,this.buildOptions(n))}saveMany(e,t,n){let r=this.getBasePath(e);return h(`${r}${s.saveMany.path}`,t,this.buildOptions(n))}async deleteOneById(e,t,n={}){let r=this.getBasePath(e),o=n.hardDelete?u({hardDelete:n.hardDelete}):"";return x(`${r}/${R(e,t)}${o}`,this.buildOptions(n))}deleteMany(e,t,n={}){let r=this.getBasePath(e),o=u(n.hardDelete?{...t,hardDelete:n.hardDelete}:t);return x(`${r}${o}`,this.buildOptions(n))}getBasePath(e){return`${this.basePath}/${K(e)}`}read(e,t,n){if(this.defaults.readMethod==="QUERY")return m(e,t??{},this.buildOptions(n));return l(`${e}${u(t)}`,this.buildOptions(n))}buildOptions(e){if(!this.defaults.headers&&!e?.headers)return e;return{...e,headers:{...this.defaults.headers,...e?.headers}}}}var w={getQuerier:()=>new Q("/api")};function ne(e){w=e}function F(){return w}function re(){return F().getQuerier()}export{Q as HttpQuerier,g as RequestError,l as get,re as getQuerier,F as getQuerierPool,a as notify,q as on,f as patch,E as post,h as put,m as query,x as remove,ne as setQuerierPool};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=88C1152805BB669764756E2164756E21
|
|
4
4
|
//# sourceMappingURL=uql-browser.min.js.map
|
|
@@ -4,15 +4,15 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { RequestCallback, RequestNotification } from '../type/index.js';\n\nconst subscriptors: RequestCallback[] = [];\n\nexport function notify(notification: RequestNotification): void {\n for (const subscriptor of subscriptors) {\n subscriptor(notification);\n }\n}\n\nexport function on(cb: RequestCallback): () => void {\n subscriptors.push(cb);\n const index = subscriptors.length - 1;\n return (): void => {\n subscriptors.splice(index, 1);\n };\n}\n",
|
|
6
6
|
"import type { RequestErrorResponse } from '../../http/contract.js';\nimport type { RequestSuccessResponse } from '../../type/index.js';\nimport type { RequestOptions } from '../type/index.js';\nimport { notify } from './bus.js';\n\n/**\n * Error thrown for non-2xx responses. Carries the HTTP status so callers can key\n * behavior on it (401 redirects, 402 payment flows, error-boundary routing).\n */\nexport class RequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n this.name = 'RequestError';\n }\n}\n\nexport function get<T>(url: string, opts?: RequestOptions) {\n return request<T>(url, { method: 'get' }, opts);\n}\n\nexport function post<T>(url: string, payload: unknown, opts?: RequestOptions) {\n const body = JSON.stringify(payload);\n return request<T>(url, { method: 'post', body }, opts);\n}\n\nexport function patch<T>(url: string, payload: unknown, opts?: RequestOptions) {\n const body = JSON.stringify(payload);\n return request<T>(url, { method: 'patch', body }, opts);\n}\n\nexport function put<T>(url: string, payload: unknown, opts?: RequestOptions) {\n const body = JSON.stringify(payload);\n return request<T>(url, { method: 'put', body }, opts);\n}\n\nexport function remove<T>(url: string, opts?: RequestOptions) {\n return request<T>(url, { method: 'delete' }, opts);\n}\n\n/**\n * HTTP QUERY (RFC 10008): a safe, idempotent read whose JSON query travels in the\n * request body, avoiding URL-length limits. Method name must stay uppercase\n * (fetch only normalizes the classic verbs).\n */\nexport function query<T>(url: string, payload: unknown, opts?: RequestOptions) {\n const body = JSON.stringify(payload);\n return request<T>(url, { method: 'QUERY', body }, opts);\n}\n\nfunction request<T>(url: string, init: RequestInit, opts?: RequestOptions) {\n notify({ phase: 'start', opts });\n\n init.headers = {\n accept: 'application/json',\n 'content-type': 'application/json',\n ...opts?.headers,\n };\n if (opts?.signal) {\n init.signal = opts.signal;\n }\n\n return fetch(url, init)\n .then((rawResp) =>\n rawResp.json().then((resp: unknown) => {\n const isSuccess = rawResp.status >= 200 && rawResp.status < 300;\n if (isSuccess) {\n notify({ phase: 'success', opts });\n return resp as RequestSuccessResponse<T>;\n }\n const errorResp = resp as Partial<RequestErrorResponse> | undefined;\n const error = {\n message: errorResp?.error?.message ?? rawResp.statusText,\n code: errorResp?.error?.code ?? rawResp.status,\n };\n notify({ phase: 'error', error, opts });\n throw new RequestError(error.message, error.code);\n }),\n )\n .finally(() => {\n notify({ phase: 'complete', opts });\n });\n}\n",
|
|
7
|
-
"import type { EntityMeta, FieldKey, FieldOptions } from '../type/index.js';\n\nexport function throwPendingTransaction(): never {\n throw TypeError('pending transaction');\n}\n\nexport function throwNoPendingTransaction(): never {\n throw TypeError('not a pending transaction');\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether any enumerable value of `obj` satisfies `pred`, short-circuiting like {@link someKey}. */\nexport function someValue(obj: object, pred: (value: unknown) => boolean): boolean {\n return someKey(obj, (key) => pred((obj as Record<string, unknown>)[key]));\n}\n\nconst isOperatorKey = (key: string) => key.startsWith('$');\n\n/**\n * Whether `value` is a non-empty object whose keys are query/update operators (`$eq`, `$push`, ...).\n * The single source of this test: the SQL dialects, the MongoDB dialect and the `$elemMatch` walker\n * all classify operator objects with it, and they used to disagree about `{}`.\n */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return hasKeys(value) && !Array.isArray(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether every key of the non-empty object `value` is an operator (no plain field names mixed in). */\nexport function isOperatorOnlyObject(value: unknown): value is Record<string, unknown> {\n return hasKeys(value) && !Array.isArray(value) && !someKey(value, (key) => !isOperatorKey(key));\n}\n\nexport function getKeys<T extends object>(obj: T): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/**\n * The entity's own name for a message to carry, declared or its class's. `defineEntity` always sets\n * one, so the fallback is for a meta a decorator is still building - which is why the sites spelling\n * this 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\nexport function getFieldKeys<E>(fields: {\n [K in FieldKey<E>]?: FieldOptions;\n}): FieldKey<E>[] {\n return getKeys(fields).filter((field) => fields[field]!.eager ?? true);\n}\n",
|
|
7
|
+
"import type { EntityMeta, FieldKey, FieldOptions } from '../type/index.js';\n\nexport function throwPendingTransaction(): never {\n throw TypeError('pending transaction');\n}\n\nexport function throwNoPendingTransaction(): never {\n throw TypeError('not a pending transaction');\n}\n\nexport function clone<T>(value: T): T {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((it) => clone(it)) as T;\n }\n return { ...value };\n}\n\n/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */\nexport function hasKeys<T>(obj: T): obj is NonNullable<T> {\n if (typeof obj !== 'object' || obj === null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\n/**\n * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match\n * without materializing a key array (unlike `Object.keys(obj).some(pred)`).\n */\nexport function someKey<T extends object>(obj: T, pred: (key: keyof T & string) => boolean): boolean {\n for (const key in obj) {\n if (pred(key)) return true;\n }\n return false;\n}\n\n/** Whether any enumerable value of `obj` satisfies `pred`, short-circuiting like {@link someKey}. */\nexport function someValue(obj: object, pred: (value: unknown) => boolean): boolean {\n return someKey(obj, (key) => pred((obj as Record<string, unknown>)[key]));\n}\n\nconst isOperatorKey = (key: string) => key.startsWith('$');\n\n/**\n * Whether `value` is a non-empty object whose keys are query/update operators (`$eq`, `$push`, ...).\n * The single source of this test: the SQL dialects, the MongoDB dialect and the `$elemMatch` walker\n * all classify operator objects with it, and they used to disagree about `{}`.\n */\nexport function isOperatorObject(value: unknown): value is Record<string, unknown> {\n return hasKeys(value) && !Array.isArray(value) && someKey(value, isOperatorKey);\n}\n\n/** Whether every key of the non-empty object `value` is an operator (no plain field names mixed in). */\nexport function isOperatorOnlyObject(value: unknown): value is Record<string, unknown> {\n return hasKeys(value) && !Array.isArray(value) && !someKey(value, (key) => !isOperatorKey(key));\n}\n\nexport function getKeys<T extends object>(obj: T): (keyof T & string)[] {\n return obj ? (Object.keys(obj) as (keyof T & string)[]) : [];\n}\n\n/**\n * The entity's own name for a message to carry, declared or its class's. `defineEntity` always sets\n * one, so the fallback is for a meta a decorator is still building - which is why the sites spelling\n * this 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\nexport function getFieldKeys<E>(fields: {\n [K in FieldKey<E>]?: FieldOptions;\n}): FieldKey<E>[] {\n return getKeys(fields).filter((field) => fields[field]!.eager ?? true);\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",
|
|
8
8
|
"export function kebabCase(val: string): string {\n let resp = val.charAt(0).toLowerCase();\n for (let i = 1; i < val.length; ++i) {\n resp += val[i] === val[i].toUpperCase() ? '-' + val[i].toLowerCase() : val[i];\n }\n return resp;\n}\n\nexport function upperFirst(text: string): string {\n if (!text) return text;\n return text[0].toUpperCase() + text.slice(1);\n}\n\nexport function lowerFirst(text: string): string {\n if (!text) return text;\n return text[0].toLowerCase() + text.slice(1);\n}\n\nexport function snakeCase(val: string): string {\n if (val === null || val === undefined) return val as string;\n if (!val) return '';\n let resp = val.charAt(0).toLowerCase();\n for (let i = 1; i < val.length; ++i) {\n const char = val[i];\n const charLower = char.toLowerCase();\n if (char !== charLower && char === char.toUpperCase()) {\n resp += '_' + charLower;\n } else {\n resp += char;\n }\n }\n return resp;\n}\n\n/**\n * Convert a string to PascalCase (UpperCamelCase).\n * @example 'user_profile' -> 'UserProfile'\n * @example 'some-text' -> 'SomeText'\n */\nexport function pascalCase(str: string): string {\n if (!str) return '';\n return str\n .split(/[_\\s-]+/)\n .map((word) => {\n // Lower-casing the rest is only right for a word that carries no case of its own: it turns\n // `USER_ID` into `UserId`, but it also turns `tenantId` into `Tenantid`.\n const rest = word === word.toUpperCase() ? word.slice(1).toLowerCase() : word.slice(1);\n return word.charAt(0).toUpperCase() + rest;\n })\n .join('');\n}\n\n/**\n * Convert a string to camelCase.\n * @example 'user_profile' -> 'userProfile'\n * @example 'SomeText' -> 'someText'\n */\nexport function camelCase(str: string): string {\n const pascal = pascalCase(str);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\n/**\n * Simple singularize function for English words.\n * @example 'users' -> 'user'\n * @example 'categories' -> 'category'\n */\nexport function singularize(name: string): string {\n if (!name) return '';\n if (name.endsWith('ies')) {\n return name.slice(0, -3) + 'y';\n }\n if (name.endsWith('ses') || name.endsWith('xes') || name.endsWith('zes')) {\n return name.slice(0, -2);\n }\n if (name.endsWith('s') && !name.endsWith('ss')) {\n return name.slice(0, -1);\n }\n return name;\n}\n\n/**\n * Simple pluralize function for English words.\n * @example 'user' -> 'users'\n * @example 'category' -> 'categories'\n */\nexport function pluralize(name: string): string {\n if (!name) return '';\n if (name.endsWith('y') && name.length > 1 && !/[aeiou]/.test(name[name.length - 2])) {\n return name.slice(0, -1) + 'ies';\n }\n if (name.endsWith('s') || name.endsWith('x') || name.endsWith('z') || name.endsWith('ch') || name.endsWith('sh')) {\n return name + 'es';\n }\n return name + 's';\n}\n",
|
|
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 ? { [K in keyof E as K extends ProjectedKeys<E, S, V, X, P, C> ? K : never]: E[K] }\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 {\n [K in keyof E as K extends Exclude<ProjectedKeys<E, S, V, X, P, C>, PopulatedToMany<E, P>> ? K : never]: E[K];\n } & {\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 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 { 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\nexport class HttpQuerier implements ClientQuerier {\n constructor(\n readonly basePath: string,\n readonly defaults: HttpQuerierDefaults = {},\n ) {}\n\n 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:
|
|
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\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<IdValue<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<(IdValue<E> | undefined)[]>(`${basePath}${CRUD_ROUTES.saveMany.path}`, payload, this.buildOptions(opts));\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}/${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,EAAa,OAAS,EACpC,MAAO,IAAY,CACjB,EAAa,OAAO,EAAO,CAAC,GCLzB,MAAM,UAAqB,KAAM,CAG3B,OAFX,WAAW,CACT,EACS,EACT,CACA,MAAM,CAAO,EAFJ,cAGT,KAAK,KAAO,eAEhB,CAEO,SAAS,CAAM,CAAC,EAAa,EAAuB,CACzD,OAAO,EAAW,EAAK,CAAE,OAAQ,KAAM,EAAG,CAAI,EAGzC,SAAS,CAAO,CAAC,EAAa,EAAkB,EAAuB,CAC5E,IAAM,EAAO,KAAK,UAAU,CAAO,EACnC,OAAO,EAAW,EAAK,CAAE,OAAQ,OAAQ,MAAK,EAAG,CAAI,EAGhD,SAAS,CAAQ,CAAC,EAAa,EAAkB,EAAuB,CAC7E,IAAM,EAAO,KAAK,UAAU,CAAO,EACnC,OAAO,EAAW,EAAK,CAAE,OAAQ,QAAS,MAAK,EAAG,CAAI,EAGjD,SAAS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AAO,EAAe,GAAG,IAAW,IAAM,KAAK,aAAa,CAAI,CAAC,EAGnE,WAAc,CAAC,EAAiB,CAC9B,MAAO,GAAG,KAAK,YAAY,EAAW,CAAM,IAGpC,IAAO,CAAC,EAAc,EAAwC,EAAuB,CAC7F,GAAI,KAAK,SAAS,aAAe,QAC/B,OAAO,EAAa,EAAM,GAAK,CAAC,EAAG,KAAK,aAAa,CAAI,CAAC,EAE5D,OAAO,EAAO,GAAG,IAAO,EAAe,CAAC,IAAK,KAAK,aAAa,CAAI,CAAC,EAG5D,YAAY,CAAC,EAAmD,CACxE,GAAI,CAAC,KAAK,SAAS,SAAW,CAAC,GAAM,QACnC,OAAO,EAET,MAAO,IAAK,EAAM,QAAS,IAAK,KAAK,SAAS,WAAY,GAAM,OAAQ,CAAE,EAE9E,CCtNA,IAAI,EAAiC,CACnC,WAAY,IAAM,IAAI,EAAY,MAAM,CAC1C,EAEO,SAAS,EAA2C,CAAC,EAAS,CACnE,EAAc,EAGT,SAAS,CAAc,EAAsB,CAClD,OAAO,EAGF,SAAS,EAAU,EAAkB,CAC1C,OAAO,EAAe,EAAE,WAAW",
|
|
16
|
+
"debugId": "88C1152805BB669764756E2164756E21",
|
|
17
17
|
"names": []
|
|
18
18
|
}
|
|
@@ -11,7 +11,19 @@ export type { HydrateKind };
|
|
|
11
11
|
export declare abstract class AbstractSqlDialect extends VectorSqlDialect implements QueryDialect, SqlQueryDialect {
|
|
12
12
|
abstract readonly dialectName: SqlDialectName;
|
|
13
13
|
abstract readonly escapeIdChar: '"' | '`';
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The column type of a database-generated key: only the type, never the key itself, which the table
|
|
16
|
+
* declares over its columns as one named constraint. SQLite is the exception - see
|
|
17
|
+
* {@link serialDeclaresPrimaryKey}.
|
|
18
|
+
*/
|
|
19
|
+
abstract readonly serialType: string;
|
|
20
|
+
/**
|
|
21
|
+
* Whether {@link serialType} states `PRIMARY KEY` itself, so the table must not state it again.
|
|
22
|
+
*
|
|
23
|
+
* True on SQLite alone, where `AUTOINCREMENT` is legal only in the exact phrase
|
|
24
|
+
* `INTEGER PRIMARY KEY AUTOINCREMENT` - the key cannot be lifted out of the column there.
|
|
25
|
+
*/
|
|
26
|
+
readonly serialDeclaresPrimaryKey: boolean;
|
|
15
27
|
abstract readonly tableOptions: string;
|
|
16
28
|
abstract readonly beginTransactionCommand: string;
|
|
17
29
|
abstract readonly commitTransactionCommand: string;
|
|
@@ -26,6 +38,11 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
26
38
|
readonly alterColumnStrategy: 'separate-clauses' | 'single-statement';
|
|
27
39
|
readonly alterColumnSyntax: 'ALTER COLUMN' | 'MODIFY COLUMN' | 'none';
|
|
28
40
|
readonly dropForeignKeySyntax: 'DROP CONSTRAINT' | 'DROP FOREIGN KEY';
|
|
41
|
+
/**
|
|
42
|
+
* `DROP CONSTRAINT <name>` where a primary key is a named constraint like any other; MySQL spells
|
|
43
|
+
* it `DROP PRIMARY KEY` and takes no name, since a table's key is always called `PRIMARY` there.
|
|
44
|
+
*/
|
|
45
|
+
readonly dropPrimaryKeySyntax: 'DROP CONSTRAINT' | 'DROP PRIMARY KEY';
|
|
29
46
|
readonly dropIndexSyntax: 'on-table' | 'standalone';
|
|
30
47
|
readonly renameTableSyntax: 'rename-table' | 'alter-table';
|
|
31
48
|
readonly booleanLiteral: 'native' | 'integer';
|
|
@@ -59,7 +76,17 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
59
76
|
*/
|
|
60
77
|
normalizeValues(values: unknown[] | undefined): unknown[] | undefined;
|
|
61
78
|
placeholder(_index: number): string;
|
|
62
|
-
|
|
79
|
+
/**
|
|
80
|
+
* `RETURNING <id column> AS id`, or nothing at all for a composite key.
|
|
81
|
+
*
|
|
82
|
+
* The alias names one column, and every column of a composite came from the caller, so there is no
|
|
83
|
+
* id the statement could report that the payload does not already carry - the same "no id to give"
|
|
84
|
+
* a `firstId` dialect already answers with. Empty rather than a refusal, so an insert and an upsert
|
|
85
|
+
* of a composite row both run; `idOf(meta, row)` names such a row.
|
|
86
|
+
*/
|
|
87
|
+
returningId<E>(meta: EntityMeta<E>): string;
|
|
88
|
+
/** `<id column> AS id` on its own, for a statement composing a `RETURNING` list of several items. */
|
|
89
|
+
protected returningIdExpression<E>(meta: EntityMeta<E>): string;
|
|
63
90
|
search<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: QueryOptions, joins?: QueryJoins): void;
|
|
64
91
|
selectFields<E>(ctx: QueryContext, entity: Type<E>, select: QuerySelectValue<E> | undefined, opts?: QuerySelectOptions, exclude?: QueryExclude<E>): void;
|
|
65
92
|
/**
|
|
@@ -322,7 +349,9 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
322
349
|
* {@link PgLikeSqlDialect} overrides this: `$N` placeholders make array order irrelevant, so it can
|
|
323
350
|
* bind into the main context and skip the second one.
|
|
324
351
|
*/
|
|
325
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
352
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
353
|
+
/** One more `RETURNING` item, as a bare expression: this joins the list and adds the keyword. */
|
|
354
|
+
extraReturning?: string): void;
|
|
326
355
|
/**
|
|
327
356
|
* Whether the upsert's update assignments can bind straight into the statement's own context.
|
|
328
357
|
*
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { getMeta } from '../entity/index.js';
|
|
1
|
+
import { getMeta, soleIdOf } from '../entity/index.js';
|
|
2
2
|
import { parseQueryLock, QueryRaw, RAW_ALIAS, RAW_VALUE, VECTOR_QUERY_KEYS, } from '../type/index.js';
|
|
3
|
-
import { asSelectMap, assertNonNegativeInteger, buildQueryWhereAsMap, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getSoftDeleteValue, hasKeys, isBooleanType, isJsonType, isJsonUpdateOp, isNumericType, isOperatorMap, isOperatorObject, isOperatorOnlyObject, isVectorSearch, normalizeScalarFieldSelection, parseGroupMap, parseRelationSize, parseSortByCount, populatesRelations, raw, someValue, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
|
|
3
|
+
import { asSelectMap, assertNonNegativeInteger, buildQueryWhereAsMap, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getSoftDeleteValue, hasKeys, isBooleanType, isJsonType, isJsonUpdateOp, isNumericType, isOperatorMap, isOperatorObject, isOperatorOnlyObject, isVectorSearch, normalizeScalarFieldSelection, parentJoins, targetKeyColumns, parseGroupMap, parseRelationSize, parseSortByCount, populatesRelations, raw, someValue, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
|
|
4
4
|
import { escapeAnsiSqlLiteral, escapeSingleQuotes } from '../util/sqlLiteral.js';
|
|
5
5
|
import { COUNT_ALIAS, DISTINCT_DERIVED_ALIAS, JSON_ELEM_ALIAS_PREFIX } from './aliases.js';
|
|
6
6
|
import { buildElemMatchConditions } from './jsonArrayElemMatchUtils.js';
|
|
@@ -10,6 +10,13 @@ import { NO_JOINS, resolveQueryJoins, resolveSortableJoin, } from './queryJoins.
|
|
|
10
10
|
import { isVectorFieldType, resolveVectorCast } from './vectorCast.js';
|
|
11
11
|
import { VectorSqlDialect } from './vectorSqlDialect.js';
|
|
12
12
|
export class AbstractSqlDialect extends VectorSqlDialect {
|
|
13
|
+
/**
|
|
14
|
+
* Whether {@link serialType} states `PRIMARY KEY` itself, so the table must not state it again.
|
|
15
|
+
*
|
|
16
|
+
* True on SQLite alone, where `AUTOINCREMENT` is legal only in the exact phrase
|
|
17
|
+
* `INTEGER PRIMARY KEY AUTOINCREMENT` - the key cannot be lifted out of the column there.
|
|
18
|
+
*/
|
|
19
|
+
serialDeclaresPrimaryKey = false;
|
|
13
20
|
/**
|
|
14
21
|
* How this engine declares a namespace, so a generated migration creates the schemas its tables
|
|
15
22
|
* need before creating them. Only reached where {@link DialectFeatures.schemas} is on. MySQL and
|
|
@@ -22,6 +29,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
22
29
|
alterColumnStrategy = 'single-statement';
|
|
23
30
|
alterColumnSyntax = 'ALTER COLUMN';
|
|
24
31
|
dropForeignKeySyntax = 'DROP CONSTRAINT';
|
|
32
|
+
/**
|
|
33
|
+
* `DROP CONSTRAINT <name>` where a primary key is a named constraint like any other; MySQL spells
|
|
34
|
+
* it `DROP PRIMARY KEY` and takes no name, since a table's key is always called `PRIMARY` there.
|
|
35
|
+
*/
|
|
36
|
+
dropPrimaryKeySyntax = 'DROP CONSTRAINT';
|
|
25
37
|
dropIndexSyntax = 'standalone';
|
|
26
38
|
renameTableSyntax = 'alter-table';
|
|
27
39
|
booleanLiteral = 'native';
|
|
@@ -90,10 +102,22 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
90
102
|
placeholder(_index) {
|
|
91
103
|
return '?';
|
|
92
104
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
105
|
+
/**
|
|
106
|
+
* `RETURNING <id column> AS id`, or nothing at all for a composite key.
|
|
107
|
+
*
|
|
108
|
+
* The alias names one column, and every column of a composite came from the caller, so there is no
|
|
109
|
+
* id the statement could report that the payload does not already carry - the same "no id to give"
|
|
110
|
+
* a `firstId` dialect already answers with. Empty rather than a refusal, so an insert and an upsert
|
|
111
|
+
* of a composite row both run; `idOf(meta, row)` names such a row.
|
|
112
|
+
*/
|
|
113
|
+
returningId(meta) {
|
|
114
|
+
const expression = this.returningIdExpression(meta);
|
|
115
|
+
return expression ? `RETURNING ${expression}` : '';
|
|
116
|
+
}
|
|
117
|
+
/** `<id column> AS id` on its own, for a statement composing a `RETURNING` list of several items. */
|
|
118
|
+
returningIdExpression(meta) {
|
|
119
|
+
const [idKey] = meta.ids;
|
|
120
|
+
return meta.ids.length === 1 ? `${this.escapeId(this.columnOf(meta, idKey))} ${this.escapeId('id')}` : '';
|
|
97
121
|
}
|
|
98
122
|
search(ctx, entity, q = {}, opts = {}, joins = NO_JOINS) {
|
|
99
123
|
const meta = getMeta(entity);
|
|
@@ -114,8 +138,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
114
138
|
: normalizeScalarFieldSelection(meta, asSelectMap(select), exclude);
|
|
115
139
|
// A prefix means relations are in play: rows arrive keyed by the id and `fillToManyRelations`
|
|
116
140
|
// groups children by it, so it outlives any subtraction - `$exclude` or falsy `$select` alike.
|
|
117
|
-
|
|
118
|
-
const
|
|
141
|
+
// Every key of a composite, since grouping by part of one would gather the wrong rows together.
|
|
142
|
+
const missingIds = opts.prefix ? meta.ids.filter((key) => !scalars.includes(key)) : [];
|
|
143
|
+
const selectArr = missingIds.length ? [...missingIds, ...scalars] : scalars;
|
|
119
144
|
if (!selectArr.length) {
|
|
120
145
|
ctx.append(escapedPrefix + '*');
|
|
121
146
|
return;
|
|
@@ -965,9 +990,13 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
965
990
|
insert(ctx, entity, payload, opts) {
|
|
966
991
|
this.appendInsertValues(ctx, entity, payload);
|
|
967
992
|
// Every engine whose ids come back from the statement itself wants the same clause, so it is
|
|
968
|
-
// appended once here instead of in an identical `insert` override per dialect.
|
|
993
|
+
// appended once here instead of in an identical `insert` override per dialect. `returningId` is
|
|
994
|
+
// empty on a composite key, which has no id to ask for.
|
|
969
995
|
if (this.insertIdSource === 'returning') {
|
|
970
|
-
|
|
996
|
+
const returning = this.returningId(getMeta(entity));
|
|
997
|
+
if (returning) {
|
|
998
|
+
ctx.append(` ${returning}`);
|
|
999
|
+
}
|
|
971
1000
|
}
|
|
972
1001
|
}
|
|
973
1002
|
/**
|
|
@@ -1060,14 +1089,19 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1060
1089
|
* {@link PgLikeSqlDialect} overrides this: `$N` placeholders make array order irrelevant, so it can
|
|
1061
1090
|
* bind into the main context and skip the second one.
|
|
1062
1091
|
*/
|
|
1063
|
-
upsert(ctx, entity, conflictPaths, payload,
|
|
1092
|
+
upsert(ctx, entity, conflictPaths, payload,
|
|
1093
|
+
/** One more `RETURNING` item, as a bare expression: this joins the list and adds the keyword. */
|
|
1094
|
+
extraReturning = '') {
|
|
1064
1095
|
const meta = getMeta(entity);
|
|
1065
1096
|
const updateCtx = this.upsertUpdateBindsInPlace ? ctx : this.createContext();
|
|
1066
1097
|
const update = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, this.upsertExcluded);
|
|
1067
1098
|
const keys = this.getUpsertConflictPathsStr(meta, conflictPaths);
|
|
1068
1099
|
const onConflict = update ? `DO UPDATE SET ${update}` : 'DO NOTHING';
|
|
1100
|
+
// Composed rather than concatenated: a composite key contributes no id item, and a dialect's own
|
|
1101
|
+
// item (Postgres's `_created`) still has to be the *first* thing after the keyword when it is.
|
|
1102
|
+
const returning = [this.returningIdExpression(meta), extraReturning].filter(Boolean).join(', ');
|
|
1069
1103
|
this.appendInsertValues(ctx, entity, payload);
|
|
1070
|
-
ctx.append(` ON CONFLICT (${keys}) ${onConflict}
|
|
1104
|
+
ctx.append(` ON CONFLICT (${keys}) ${onConflict}${returning ? ` RETURNING ${returning}` : ''}`);
|
|
1071
1105
|
if (updateCtx !== ctx) {
|
|
1072
1106
|
ctx.pushValue(...updateCtx.values);
|
|
1073
1107
|
}
|
|
@@ -1461,36 +1495,38 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1461
1495
|
appendRelationSubquery(ctx, meta, rel, opts, projection, val) {
|
|
1462
1496
|
// Aliases, not paths, everywhere a column is prefixed; `tableRef` declares them in the FROM.
|
|
1463
1497
|
const parentAlias = this.resolveTableAlias(meta);
|
|
1464
|
-
const references = rel.references;
|
|
1465
|
-
const escapedParentId = this.escapedParentColumn(parentAlias, meta, opts, meta.id);
|
|
1466
1498
|
const relatedEntity = rel.entity();
|
|
1467
1499
|
const relatedMeta = getMeta(relatedEntity);
|
|
1468
1500
|
const { alias: relatedAlias, ref: relatedRef } = this.tableRef(relatedMeta);
|
|
1469
1501
|
// Resolved before any SQL is emitted: it also decides whether the mm form reaches the target.
|
|
1470
1502
|
const targetWhere = this.scopedWhereMap(relatedMeta, val);
|
|
1471
1503
|
ctx.append(`(SELECT ${projection} FROM `);
|
|
1504
|
+
// One equality per key of the parent, anded: a composite correlates on every column, and matching
|
|
1505
|
+
// on part of one would find the rows of a different parent. `parentJoins` is what keeps the two
|
|
1506
|
+
// ends the right way round, whether the join lands on the junction or on the target.
|
|
1507
|
+
const correlation = (alias, joinedMeta) => parentJoins(rel, meta.ids.length)
|
|
1508
|
+
.map(({ parent, joined }) => `${this.escapedColumn(alias, joinedMeta, joined)} = ${this.escapedParentColumn(parentAlias, meta, opts, parent)}`)
|
|
1509
|
+
.join(' AND ');
|
|
1472
1510
|
if (rel.cardinality === 'mm' && rel.through) {
|
|
1473
1511
|
const throughEntity = rel.through();
|
|
1474
1512
|
const throughMeta = getMeta(throughEntity);
|
|
1475
1513
|
const { alias: throughAlias, ref: throughRef } = this.tableRef(throughMeta);
|
|
1476
1514
|
ctx.append(throughRef);
|
|
1477
|
-
ctx.append(` WHERE ${
|
|
1515
|
+
ctx.append(` WHERE ${correlation(throughAlias, throughMeta)}`);
|
|
1478
1516
|
// The junction is a row being read too: a soft-deleted link is not a link.
|
|
1479
1517
|
this.where(ctx, throughEntity, {}, { prefix: throughAlias, clause: 'AND' });
|
|
1480
1518
|
if (hasKeys(targetWhere)) {
|
|
1481
|
-
|
|
1482
|
-
|
|
1519
|
+
const targetKey = soleIdOf(relatedMeta, 'a many-to-many target');
|
|
1520
|
+
const [targetColumn] = targetKeyColumns(rel, meta.ids.length);
|
|
1521
|
+
ctx.append(` AND ${this.escapedColumn(throughAlias, throughMeta, targetColumn)} IN (`);
|
|
1522
|
+
ctx.append(`SELECT ${this.escapedColumn(relatedAlias, relatedMeta, targetKey)} FROM ${relatedRef}`);
|
|
1483
1523
|
this.renderWhere(ctx, relatedEntity, targetWhere, { prefix: relatedAlias, clause: 'WHERE' });
|
|
1484
1524
|
ctx.append(')');
|
|
1485
1525
|
}
|
|
1486
1526
|
}
|
|
1487
1527
|
else {
|
|
1488
|
-
const joinLeft = this.escapedColumn(relatedAlias, relatedMeta, references[0].foreign);
|
|
1489
|
-
const joinRight = rel.cardinality === '1m'
|
|
1490
|
-
? escapedParentId
|
|
1491
|
-
: this.escapedParentColumn(parentAlias, meta, opts, references[0].local);
|
|
1492
1528
|
ctx.append(relatedRef);
|
|
1493
|
-
ctx.append(` WHERE ${
|
|
1529
|
+
ctx.append(` WHERE ${correlation(relatedAlias, relatedMeta)}`);
|
|
1494
1530
|
this.renderWhere(ctx, relatedEntity, targetWhere, { prefix: relatedAlias, clause: 'AND' });
|
|
1495
1531
|
}
|
|
1496
1532
|
ctx.append(')');
|
|
@@ -24,7 +24,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
24
24
|
estimatedCount<E>(ctx: QueryContext, entity: Type<E>): void;
|
|
25
25
|
/** `OFFSET` is only legal after a `LIMIT` here, so a bare `$skip` needs one. */
|
|
26
26
|
pager(ctx: QueryContext, opts: QueryPager): void;
|
|
27
|
-
readonly
|
|
27
|
+
readonly serialType = "BIGINT UNSIGNED AUTO_INCREMENT";
|
|
28
28
|
readonly escapeIdChar = "`";
|
|
29
29
|
readonly tableOptions = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
|
|
30
30
|
readonly beginTransactionCommand = "START TRANSACTION";
|
|
@@ -32,6 +32,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
32
32
|
readonly rollbackTransactionCommand = "ROLLBACK";
|
|
33
33
|
readonly isolationLevelStrategy = "set-before";
|
|
34
34
|
readonly dropForeignKeySyntax = "DROP FOREIGN KEY";
|
|
35
|
+
readonly dropPrimaryKeySyntax = "DROP PRIMARY KEY";
|
|
35
36
|
readonly dropIndexSyntax = "on-table";
|
|
36
37
|
readonly renameTableSyntax = "rename-table";
|
|
37
38
|
readonly alterColumnSyntax = "MODIFY COLUMN";
|
|
@@ -51,7 +52,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
|
|
|
51
52
|
* Appended to both branches above. Empty on MySQL, which has no `INSERT ... RETURNING`; MariaDB
|
|
52
53
|
* 10.5+ has it, and used to restate this whole method just to add it.
|
|
53
54
|
*/
|
|
54
|
-
protected upsertReturning<E>(
|
|
55
|
+
protected upsertReturning<E>(_meta: EntityMeta<E>): string;
|
|
55
56
|
/**
|
|
56
57
|
* The alias the inserted row is given after the values list, and read back by the assignments.
|
|
57
58
|
* Undefined where the dialect has no such syntax - MariaDB, which reads that row through
|