dsqlbase 0.2.1 → 0.3.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/CHANGELOG.md +32 -0
- package/README.md +41 -60
- package/dist/client/clients/base.d.ts +20 -0
- package/dist/client/clients/base.d.ts.map +1 -0
- package/dist/client/clients/base.js +52 -0
- package/dist/client/clients/base.js.map +1 -0
- package/dist/client/clients/dsql.d.ts +24 -0
- package/dist/client/clients/dsql.d.ts.map +1 -0
- package/dist/client/clients/dsql.js +31 -0
- package/dist/client/clients/dsql.js.map +1 -0
- package/dist/client/clients/index.d.ts +6 -0
- package/dist/client/clients/index.d.ts.map +1 -0
- package/dist/client/clients/index.js +6 -0
- package/dist/client/clients/index.js.map +1 -0
- package/dist/client/clients/model.d.ts +169 -0
- package/dist/client/clients/model.d.ts.map +1 -0
- package/dist/client/{model/client.js → clients/model.js} +82 -53
- package/dist/client/clients/model.js.map +1 -0
- package/dist/client/clients/transaction.d.ts +9 -0
- package/dist/client/clients/transaction.d.ts.map +1 -0
- package/dist/client/{transaction/transaction-client.js → clients/transaction.js} +7 -7
- package/dist/client/clients/transaction.js.map +1 -0
- package/dist/client/clients/union.d.ts +39 -0
- package/dist/client/clients/union.d.ts.map +1 -0
- package/dist/client/clients/union.js +54 -0
- package/dist/client/clients/union.js.map +1 -0
- package/dist/client/create.d.ts +15 -18
- package/dist/client/create.d.ts.map +1 -1
- package/dist/client/create.js +10 -27
- package/dist/client/create.js.map +1 -1
- package/dist/client/index.d.ts +4 -8
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -6
- package/dist/client/index.js.map +1 -1
- package/dist/client/normalizers/base.d.ts +467 -0
- package/dist/client/normalizers/base.d.ts.map +1 -0
- package/dist/client/normalizers/base.js.map +1 -0
- package/dist/client/normalizers/context.d.ts +14 -0
- package/dist/client/normalizers/context.d.ts.map +1 -0
- package/dist/client/normalizers/context.js +16 -0
- package/dist/client/normalizers/context.js.map +1 -0
- package/dist/client/normalizers/index.d.ts +8 -0
- package/dist/client/normalizers/index.d.ts.map +1 -0
- package/dist/client/normalizers/index.js +8 -0
- package/dist/client/normalizers/index.js.map +1 -0
- package/dist/client/normalizers/pagination.d.ts +87 -0
- package/dist/client/normalizers/pagination.d.ts.map +1 -0
- package/dist/client/normalizers/pagination.js +245 -0
- package/dist/client/normalizers/pagination.js.map +1 -0
- package/dist/client/normalizers/request.d.ts +41 -0
- package/dist/client/normalizers/request.d.ts.map +1 -0
- package/dist/client/normalizers/request.js +346 -0
- package/dist/client/normalizers/request.js.map +1 -0
- package/dist/client/normalizers/rules.d.ts +132 -0
- package/dist/client/normalizers/rules.d.ts.map +1 -0
- package/dist/client/normalizers/rules.js +82 -0
- package/dist/client/normalizers/rules.js.map +1 -0
- package/dist/client/normalizers/utils.d.ts +6 -0
- package/dist/client/normalizers/utils.d.ts.map +1 -0
- package/dist/client/normalizers/utils.js +18 -0
- package/dist/client/normalizers/utils.js.map +1 -0
- package/dist/client/normalizers/where.d.ts +39 -0
- package/dist/client/normalizers/where.d.ts.map +1 -0
- package/dist/client/normalizers/where.js +230 -0
- package/dist/client/normalizers/where.js.map +1 -0
- package/dist/client/utils/occ-retry.d.ts.map +1 -0
- package/dist/client/utils/occ-retry.js.map +1 -0
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -3
- package/dist/index.js.map +1 -1
- package/dist/schema/columns/guid.d.ts +21 -21
- package/dist/schema/columns/guid.d.ts.map +1 -1
- package/dist/schema/columns/guid.js +24 -25
- package/dist/schema/columns/guid.js.map +1 -1
- package/dist/schema/index.d.ts +0 -2
- package/dist/schema/index.d.ts.map +1 -1
- package/dist/schema/index.js +0 -2
- package/dist/schema/index.js.map +1 -1
- package/dist/schema/relations.d.ts +22 -13
- package/dist/schema/relations.d.ts.map +1 -1
- package/dist/schema/relations.js +9 -1
- package/dist/schema/relations.js.map +1 -1
- package/dist/schema/table.d.ts +2 -2
- package/dist/schema/table.d.ts.map +1 -1
- package/dist/schema/table.js.map +1 -1
- package/dist/schema/union.d.ts +13 -8
- package/dist/schema/union.d.ts.map +1 -1
- package/dist/schema/union.js +14 -9
- package/dist/schema/union.js.map +1 -1
- package/dist/schema/utils/global-id.d.ts +3 -3
- package/dist/schema/utils/global-id.js +3 -3
- package/dist/schema/utils/global-id.js.map +1 -1
- package/dist/schema/utils/guid-hooks.d.ts +49 -0
- package/dist/schema/utils/guid-hooks.d.ts.map +1 -0
- package/dist/schema/utils/guid-hooks.js +155 -0
- package/dist/schema/utils/guid-hooks.js.map +1 -0
- package/package.json +8 -6
- package/dist/client/database/base.d.ts +0 -99
- package/dist/client/database/base.d.ts.map +0 -1
- package/dist/client/database/base.js +0 -216
- package/dist/client/database/base.js.map +0 -1
- package/dist/client/database/client.d.ts +0 -26
- package/dist/client/database/client.d.ts.map +0 -1
- package/dist/client/database/client.js +0 -47
- package/dist/client/database/client.js.map +0 -1
- package/dist/client/database/index.d.ts +0 -65
- package/dist/client/database/index.d.ts.map +0 -1
- package/dist/client/database/index.js +0 -3
- package/dist/client/database/index.js.map +0 -1
- package/dist/client/model/base.d.ts +0 -747
- package/dist/client/model/base.d.ts.map +0 -1
- package/dist/client/model/base.js.map +0 -1
- package/dist/client/model/client.d.ts +0 -139
- package/dist/client/model/client.d.ts.map +0 -1
- package/dist/client/model/client.js.map +0 -1
- package/dist/client/model/filters.d.ts +0 -276
- package/dist/client/model/filters.d.ts.map +0 -1
- package/dist/client/model/filters.js +0 -470
- package/dist/client/model/filters.js.map +0 -1
- package/dist/client/model/normalizer.d.ts +0 -143
- package/dist/client/model/normalizer.d.ts.map +0 -1
- package/dist/client/model/normalizer.js +0 -641
- package/dist/client/model/normalizer.js.map +0 -1
- package/dist/client/nodes.d.ts +0 -62
- package/dist/client/nodes.d.ts.map +0 -1
- package/dist/client/nodes.js +0 -378
- package/dist/client/nodes.js.map +0 -1
- package/dist/client/pagination/cursor.d.ts +0 -40
- package/dist/client/pagination/cursor.d.ts.map +0 -1
- package/dist/client/pagination/cursor.js +0 -79
- package/dist/client/pagination/cursor.js.map +0 -1
- package/dist/client/pagination/page.d.ts +0 -23
- package/dist/client/pagination/page.d.ts.map +0 -1
- package/dist/client/pagination/page.js +0 -37
- package/dist/client/pagination/page.js.map +0 -1
- package/dist/client/transaction/index.d.ts +0 -2
- package/dist/client/transaction/index.d.ts.map +0 -1
- package/dist/client/transaction/index.js +0 -2
- package/dist/client/transaction/index.js.map +0 -1
- package/dist/client/transaction/occ-retry.d.ts.map +0 -1
- package/dist/client/transaction/occ-retry.js.map +0 -1
- package/dist/client/transaction/transaction-client.d.ts +0 -9
- package/dist/client/transaction/transaction-client.d.ts.map +0 -1
- package/dist/client/transaction/transaction-client.js.map +0 -1
- package/dist/client/union/client.d.ts +0 -55
- package/dist/client/union/client.d.ts.map +0 -1
- package/dist/client/union/client.js +0 -74
- package/dist/client/union/client.js.map +0 -1
- package/dist/schema/embedded.d.ts +0 -31
- package/dist/schema/embedded.d.ts.map +0 -1
- package/dist/schema/embedded.js +0 -33
- package/dist/schema/embedded.js.map +0 -1
- package/dist/schema/tenant.d.ts +0 -31
- package/dist/schema/tenant.d.ts.map +0 -1
- package/dist/schema/tenant.js +0 -33
- package/dist/schema/tenant.js.map +0 -1
- /package/dist/client/{model → normalizers}/base.js +0 -0
- /package/dist/client/{transaction → utils}/occ-retry.d.ts +0 -0
- /package/dist/client/{transaction → utils}/occ-retry.js +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsqlbase",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Query client and schema definition for distributed SQL databases",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"type": "module",
|
|
@@ -61,18 +61,20 @@
|
|
|
61
61
|
}
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
|
-
"prebuild": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true})
|
|
65
|
-
"build": "tsc -
|
|
64
|
+
"prebuild": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true})\"",
|
|
65
|
+
"build": "tsc -p tsconfig.build.json",
|
|
66
|
+
"dev": "tsc -p tsconfig.build.json --watch",
|
|
66
67
|
"test": "vitest run",
|
|
68
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
67
69
|
"lint": "eslint src --ext .ts",
|
|
68
70
|
"prepack": "node -e \"require('fs').copyFileSync('../../LICENSE','LICENSE')\""
|
|
69
71
|
},
|
|
70
72
|
"dependencies": {
|
|
71
|
-
"@dsqlbase/core": "^0.
|
|
73
|
+
"@dsqlbase/core": "^0.3.0"
|
|
72
74
|
},
|
|
73
75
|
"peerDependencies": {
|
|
74
|
-
"@electric-sql/pglite": "
|
|
75
|
-
"pg": "
|
|
76
|
+
"@electric-sql/pglite": ">=0.4.6",
|
|
77
|
+
"pg": ">=8.20.0"
|
|
76
78
|
},
|
|
77
79
|
"peerDependenciesMeta": {
|
|
78
80
|
"pg": {
|
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { AnyTable, DefinitionSchema, ExecutableQuery, ExecutionContext, Schema, SQLQuery, SQLStatement } from "@dsqlbase/core";
|
|
2
|
-
import { ModelClient } from "../model/client.js";
|
|
3
|
-
import { GlobalIdListResultOf, GlobalIdOptionsOf, GlobalIdResultOf } from "../model/base.js";
|
|
4
|
-
export declare abstract class BaseClient<T extends DefinitionSchema> {
|
|
5
|
-
protected readonly _ctx: ExecutionContext<T>;
|
|
6
|
-
/** One model per table, keyed by schema alias. Populated by {@link attachModels}. */
|
|
7
|
-
protected readonly _models: Map<string, ModelClient<AnyTable, T>>;
|
|
8
|
-
constructor(ctx: ExecutionContext<T>);
|
|
9
|
-
/**
|
|
10
|
-
* Raw SQL bypasses every seam the operations factory applies, the tenant predicate included,
|
|
11
|
-
* so a scoped client does not carry it. The types remove it; this is the runtime half, for
|
|
12
|
-
* callers reaching it through a widened type.
|
|
13
|
-
*/
|
|
14
|
-
private _assertUnscoped;
|
|
15
|
-
/**
|
|
16
|
-
* Resolves a global id to the node it names, and to how the caller wants it read.
|
|
17
|
-
*
|
|
18
|
-
* Every failure is raised here, before a query is built: an id that does not decode, one
|
|
19
|
-
* naming a table that is not a node, one whose payload is not that node's key, and one the
|
|
20
|
-
* caller's `on` map excluded.
|
|
21
|
-
*/
|
|
22
|
-
private _resolveNode;
|
|
23
|
-
/**
|
|
24
|
-
* A `where` over a field named at runtime.
|
|
25
|
-
*
|
|
26
|
-
* `_models` is keyed by alias and typed over `AnyTable`, so the key field is a `string` the
|
|
27
|
-
* compiler cannot match to a column. The node registry resolved it against the real table
|
|
28
|
-
* when the client was built, which is the check this cast stands on.
|
|
29
|
-
*/
|
|
30
|
-
private _byKey;
|
|
31
|
-
/**
|
|
32
|
-
* The lookup's own key filter, AND-ed with the member's `on.<alias>.where` when it has one. A
|
|
33
|
-
* row that fails the member filter is a miss, exactly as if the id named nothing.
|
|
34
|
-
*/
|
|
35
|
-
private _lookupWhere;
|
|
36
|
-
private _model;
|
|
37
|
-
/**
|
|
38
|
-
* Reads the single row a global id names, or `null` when it no longer exists.
|
|
39
|
-
*
|
|
40
|
-
* The lookup runs through the table's own model client rather than issuing SQL of its own,
|
|
41
|
-
* so every seam a `findOne` passes applies to it — the tenant predicate above all. A node
|
|
42
|
-
* lookup that bypassed it would be a cross-tenant read; going through the model makes that
|
|
43
|
-
* structurally impossible rather than something to remember.
|
|
44
|
-
*
|
|
45
|
-
* The row is tagged with `$$key`, the alias it came from, which is what narrows the union.
|
|
46
|
-
* `$$meta.key` carries the same value but cannot be used for it: TypeScript does not narrow
|
|
47
|
-
* on a nested discriminant.
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* ```ts
|
|
51
|
-
* const record = await dsql.$findByGlobalId({
|
|
52
|
-
* id,
|
|
53
|
-
* on: { users: { select: { id: true, name: true } }, workspaces: true },
|
|
54
|
-
* });
|
|
55
|
-
*
|
|
56
|
-
* if (record?.$$key === "users") record.name;
|
|
57
|
-
* ```
|
|
58
|
-
*
|
|
59
|
-
* @throws GlobalIdError when the id does not decode, names a table that is not a node,
|
|
60
|
-
* carries a payload that is not that node's key, or names a member `on` set to `false`.
|
|
61
|
-
*/
|
|
62
|
-
$findByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {
|
|
63
|
-
id: string;
|
|
64
|
-
on?: TOn;
|
|
65
|
-
}): Promise<GlobalIdResultOf<Schema<T>, TOn>>;
|
|
66
|
-
/** Tags a resolved row with the alias it came from, so a caller can narrow the union. */
|
|
67
|
-
private _tag;
|
|
68
|
-
/**
|
|
69
|
-
* Reads many global ids at once: one query per table rather than one per id, with the
|
|
70
|
-
* results handed back **in the order the ids were given** and `null` wherever a row no
|
|
71
|
-
* longer exists — the shape a batch resolver wants.
|
|
72
|
-
*
|
|
73
|
-
* Unlike {@link $findByGlobalId} this cannot be a single `ExecutableQuery`, because ids
|
|
74
|
-
* from different tables fan out to different queries.
|
|
75
|
-
*
|
|
76
|
-
* The node's key field is always projected, even when `select` leaves it out: matching a
|
|
77
|
-
* row back to the id that asked for it is what the key is for.
|
|
78
|
-
*
|
|
79
|
-
* @throws GlobalIdError on the first id that does not resolve. A missing *row* is a `null`
|
|
80
|
-
* in the result; a malformed id is a caller bug and is not silently dropped.
|
|
81
|
-
*/
|
|
82
|
-
$listByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {
|
|
83
|
-
ids: readonly string[];
|
|
84
|
-
on?: TOn;
|
|
85
|
-
}): Promise<(GlobalIdListResultOf<Schema<T>, TOn> | null)[]>;
|
|
86
|
-
$query<T = unknown>(sql: SQLQuery): ExecutableQuery<T[]>;
|
|
87
|
-
$execute<T = unknown>(query: SQLStatement): Promise<T[]>;
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Attaches one {@link ModelClient} per table to a client, keyed by the table's schema
|
|
91
|
-
* alias, as a non-writable enumerable property. Shared by `createClient` and the
|
|
92
|
-
* transaction client so a derived client is built exactly one way.
|
|
93
|
-
*
|
|
94
|
-
* Tables are taken from `SchemaRegistry.getTableEntries()`, which yields each table once
|
|
95
|
-
* under its alias — `getTables()` holds every table under both its alias and its database
|
|
96
|
-
* name, which would attach two models for an aliased table.
|
|
97
|
-
*/
|
|
98
|
-
export declare function attachModels<T extends DefinitionSchema>(client: BaseClient<T>, ctx: ExecutionContext<T>): void;
|
|
99
|
-
//# sourceMappingURL=base.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/client/database/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EACR,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,MAAM,EACN,QAAQ,EACR,YAAY,EAEb,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAEjB,MAAM,kBAAkB,CAAC;AAY1B,8BAAsB,UAAU,CAAC,CAAC,SAAS,gBAAgB;IACzD,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAE7C,qFAAqF;IACrF,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAA+C;gBAE7D,GAAG,EAAE,gBAAgB,CAAC,CAAC,CAAC;IAIpC;;;;OAIG;IACH,OAAO,CAAC,eAAe;IASvB;;;;;;OAMG;IACH,OAAO,CAAC,YAAY;IAqCpB;;;;;;OAMG;IACH,OAAO,CAAC,MAAM;IAId;;;OAGG;IACH,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,MAAM;IAUd;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACG,eAAe,CAAC,GAAG,SAAS,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,SAAS,EAAE,IAAI,EAAE;QAC5F,EAAE,EAAE,MAAM,CAAC;QACX,EAAE,CAAC,EAAE,GAAG,CAAC;KACV,GAAG,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAa7C,yFAAyF;IACzF,OAAO,CAAC,IAAI;IAIZ;;;;;;;;;;;;;OAaG;IACG,eAAe,CAAC,GAAG,SAAS,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,SAAS,EAAE,IAAI,EAAE;QAC5F,GAAG,EAAE,SAAS,MAAM,EAAE,CAAC;QACvB,EAAE,CAAC,EAAE,GAAG,CAAC;KACV,GAAG,OAAO,CAAC,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;IAwC5D,MAAM,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,QAAQ;IAgB3B,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC;CAa/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,gBAAgB,EACrD,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,EACrB,GAAG,EAAE,gBAAgB,CAAC,CAAC,CAAC,GACvB,IAAI,CAsBN"}
|
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
import { ExecutableQuery, TenancyError, } from "@dsqlbase/core";
|
|
2
|
-
import { ModelClient } from "../model/client.js";
|
|
3
|
-
import { UnionClient } from "../union/client.js";
|
|
4
|
-
import { GlobalIdError, decodeGlobalId } from "../../schema/utils/global-id.js";
|
|
5
|
-
import { getNodes } from "../nodes.js";
|
|
6
|
-
export class BaseClient {
|
|
7
|
-
_ctx;
|
|
8
|
-
/** One model per table, keyed by schema alias. Populated by {@link attachModels}. */
|
|
9
|
-
_models = new Map();
|
|
10
|
-
constructor(ctx) {
|
|
11
|
-
this._ctx = ctx;
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Raw SQL bypasses every seam the operations factory applies, the tenant predicate included,
|
|
15
|
-
* so a scoped client does not carry it. The types remove it; this is the runtime half, for
|
|
16
|
-
* callers reaching it through a widened type.
|
|
17
|
-
*/
|
|
18
|
-
_assertUnscoped(method) {
|
|
19
|
-
if (this._ctx.identity) {
|
|
20
|
-
throw new TenancyError(`${method} is not available on an identity-scoped client: raw SQL is not tenant-safe. ` +
|
|
21
|
-
`Use it on the base client, where that is plain to read.`);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Resolves a global id to the node it names, and to how the caller wants it read.
|
|
26
|
-
*
|
|
27
|
-
* Every failure is raised here, before a query is built: an id that does not decode, one
|
|
28
|
-
* naming a table that is not a node, one whose payload is not that node's key, and one the
|
|
29
|
-
* caller's `on` map excluded.
|
|
30
|
-
*/
|
|
31
|
-
_resolveNode(id, on) {
|
|
32
|
-
const { key, pk } = decodeGlobalId(id);
|
|
33
|
-
const node = getNodes(this._ctx.schema).get(key);
|
|
34
|
-
if (!node) {
|
|
35
|
-
throw new GlobalIdError("unknown_node", `"${key}" is not a node in this schema.`);
|
|
36
|
-
}
|
|
37
|
-
const fields = Object.keys(pk);
|
|
38
|
-
if (fields.length !== 1 || fields[0] !== node.keyField) {
|
|
39
|
-
throw new GlobalIdError("key_mismatch", `Global id for "${key}" carries ${fields.map((field) => `"${field}"`).join(", ")} ` +
|
|
40
|
-
`rather than its key "${node.keyField}".`);
|
|
41
|
-
}
|
|
42
|
-
const option = on?.[node.alias];
|
|
43
|
-
if (option === false) {
|
|
44
|
-
throw new GlobalIdError("unknown_node", `"${node.alias}" was excluded from this lookup by its \`on\` map.`);
|
|
45
|
-
}
|
|
46
|
-
const { select, where, join } = (option && typeof option === "object" ? option : {});
|
|
47
|
-
return { node, value: pk[node.keyField], args: { select, where, join } };
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* A `where` over a field named at runtime.
|
|
51
|
-
*
|
|
52
|
-
* `_models` is keyed by alias and typed over `AnyTable`, so the key field is a `string` the
|
|
53
|
-
* compiler cannot match to a column. The node registry resolved it against the real table
|
|
54
|
-
* when the client was built, which is the check this cast stands on.
|
|
55
|
-
*/
|
|
56
|
-
_byKey(field, condition) {
|
|
57
|
-
return { [field]: condition };
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* The lookup's own key filter, AND-ed with the member's `on.<alias>.where` when it has one. A
|
|
61
|
-
* row that fails the member filter is a miss, exactly as if the id named nothing.
|
|
62
|
-
*/
|
|
63
|
-
_lookupWhere(field, condition, where) {
|
|
64
|
-
const key = this._byKey(field, condition);
|
|
65
|
-
return where ? { and: [key, where] } : key;
|
|
66
|
-
}
|
|
67
|
-
_model(alias) {
|
|
68
|
-
const model = this._models.get(alias);
|
|
69
|
-
if (!model) {
|
|
70
|
-
throw new Error(`No model is attached for "${alias}".`);
|
|
71
|
-
}
|
|
72
|
-
return model;
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Reads the single row a global id names, or `null` when it no longer exists.
|
|
76
|
-
*
|
|
77
|
-
* The lookup runs through the table's own model client rather than issuing SQL of its own,
|
|
78
|
-
* so every seam a `findOne` passes applies to it — the tenant predicate above all. A node
|
|
79
|
-
* lookup that bypassed it would be a cross-tenant read; going through the model makes that
|
|
80
|
-
* structurally impossible rather than something to remember.
|
|
81
|
-
*
|
|
82
|
-
* The row is tagged with `$$key`, the alias it came from, which is what narrows the union.
|
|
83
|
-
* `$$meta.key` carries the same value but cannot be used for it: TypeScript does not narrow
|
|
84
|
-
* on a nested discriminant.
|
|
85
|
-
*
|
|
86
|
-
* @example
|
|
87
|
-
* ```ts
|
|
88
|
-
* const record = await dsql.$findByGlobalId({
|
|
89
|
-
* id,
|
|
90
|
-
* on: { users: { select: { id: true, name: true } }, workspaces: true },
|
|
91
|
-
* });
|
|
92
|
-
*
|
|
93
|
-
* if (record?.$$key === "users") record.name;
|
|
94
|
-
* ```
|
|
95
|
-
*
|
|
96
|
-
* @throws GlobalIdError when the id does not decode, names a table that is not a node,
|
|
97
|
-
* carries a payload that is not that node's key, or names a member `on` set to `false`.
|
|
98
|
-
*/
|
|
99
|
-
async $findByGlobalId(args) {
|
|
100
|
-
const { node, value, args: nodeArgs } = this._resolveNode(args.id, args.on);
|
|
101
|
-
const { select, where, join } = nodeArgs;
|
|
102
|
-
const row = (await this._model(node.alias).findOne({
|
|
103
|
-
where: this._lookupWhere(node.keyField, { eq: value }, where),
|
|
104
|
-
...(select ? { select } : {}),
|
|
105
|
-
...(join ? { join } : {}),
|
|
106
|
-
}));
|
|
107
|
-
return (row ? this._tag(row, node) : null);
|
|
108
|
-
}
|
|
109
|
-
/** Tags a resolved row with the alias it came from, so a caller can narrow the union. */
|
|
110
|
-
_tag(row, node) {
|
|
111
|
-
return { ...row, $$key: node.alias };
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Reads many global ids at once: one query per table rather than one per id, with the
|
|
115
|
-
* results handed back **in the order the ids were given** and `null` wherever a row no
|
|
116
|
-
* longer exists — the shape a batch resolver wants.
|
|
117
|
-
*
|
|
118
|
-
* Unlike {@link $findByGlobalId} this cannot be a single `ExecutableQuery`, because ids
|
|
119
|
-
* from different tables fan out to different queries.
|
|
120
|
-
*
|
|
121
|
-
* The node's key field is always projected, even when `select` leaves it out: matching a
|
|
122
|
-
* row back to the id that asked for it is what the key is for.
|
|
123
|
-
*
|
|
124
|
-
* @throws GlobalIdError on the first id that does not resolve. A missing *row* is a `null`
|
|
125
|
-
* in the result; a malformed id is a caller bug and is not silently dropped.
|
|
126
|
-
*/
|
|
127
|
-
async $listByGlobalId(args) {
|
|
128
|
-
const resolved = args.ids.map((id) => this._resolveNode(id, args.on));
|
|
129
|
-
const groups = new Map();
|
|
130
|
-
for (const { node, value, args: nodeArgs } of resolved) {
|
|
131
|
-
const group = groups.get(node.alias) ?? { node, values: new Set(), args: nodeArgs };
|
|
132
|
-
group.values.add(value);
|
|
133
|
-
groups.set(node.alias, group);
|
|
134
|
-
}
|
|
135
|
-
// One query per table, all of them in flight together. Rows are matched back by node and
|
|
136
|
-
// canonical key, not by id text: the database finds a row for any spelling of its uuid.
|
|
137
|
-
const rows = new Map();
|
|
138
|
-
const keyOf = (alias, value) => `${alias}\u0000${canonicalUuid(value)}`;
|
|
139
|
-
await Promise.all([...groups.values()].map(async ({ node, values, args: { select, where, join } }) => {
|
|
140
|
-
const found = (await this._model(node.alias).findMany({
|
|
141
|
-
where: this._lookupWhere(node.keyField, { in: [...values] }, where),
|
|
142
|
-
// The key is always projected: it is the only thing that can put a row back
|
|
143
|
-
// against the id that asked for it.
|
|
144
|
-
...(select ? { select: { ...select, [node.keyField]: true } } : {}),
|
|
145
|
-
...(join ? { join } : {}),
|
|
146
|
-
}));
|
|
147
|
-
for (const row of found) {
|
|
148
|
-
// The key column reads back wrapped as a global id; its payload is the stored uuid.
|
|
149
|
-
const { pk } = decodeGlobalId(String(row[node.keyField]));
|
|
150
|
-
rows.set(keyOf(node.alias, pk[node.keyField] ?? ""), this._tag(row, node));
|
|
151
|
-
}
|
|
152
|
-
}));
|
|
153
|
-
return resolved.map(({ node, value }) => (rows.get(keyOf(node.alias, value)) ?? null));
|
|
154
|
-
}
|
|
155
|
-
$query(sql) {
|
|
156
|
-
this._assertUnscoped("$query");
|
|
157
|
-
return new ExecutableQuery({
|
|
158
|
-
mode: "many",
|
|
159
|
-
name: "anonymous_query",
|
|
160
|
-
type: "select",
|
|
161
|
-
args: {},
|
|
162
|
-
query: sql.toQuery(),
|
|
163
|
-
resolve: (result) => result,
|
|
164
|
-
}, this._ctx.session);
|
|
165
|
-
}
|
|
166
|
-
async $execute(query) {
|
|
167
|
-
this._assertUnscoped("$execute");
|
|
168
|
-
// A `sql` template here is an object with no `text`: the session would run nothing.
|
|
169
|
-
if (typeof query?.text !== "string") {
|
|
170
|
-
throw new TypeError("$execute takes a rendered statement ({ text, params }); pass a sql`…` template to " +
|
|
171
|
-
"$query, or call .toQuery() on it.");
|
|
172
|
-
}
|
|
173
|
-
return this._ctx.session.execute(query);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Attaches one {@link ModelClient} per table to a client, keyed by the table's schema
|
|
178
|
-
* alias, as a non-writable enumerable property. Shared by `createClient` and the
|
|
179
|
-
* transaction client so a derived client is built exactly one way.
|
|
180
|
-
*
|
|
181
|
-
* Tables are taken from `SchemaRegistry.getTableEntries()`, which yields each table once
|
|
182
|
-
* under its alias — `getTables()` holds every table under both its alias and its database
|
|
183
|
-
* name, which would attach two models for an aliased table.
|
|
184
|
-
*/
|
|
185
|
-
export function attachModels(client, ctx) {
|
|
186
|
-
for (const [alias, table] of ctx.schema.getTableEntries()) {
|
|
187
|
-
const model = new ModelClient(ctx, table);
|
|
188
|
-
client["_models"].set(alias, model);
|
|
189
|
-
Object.defineProperty(client, alias, {
|
|
190
|
-
value: model,
|
|
191
|
-
writable: false,
|
|
192
|
-
enumerable: true,
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
// Unions are read under their own alias, next to the tables; the registry already refused a
|
|
196
|
-
// union named like a table, so the two cannot collide.
|
|
197
|
-
for (const [alias, union] of ctx.schema.getUnions()) {
|
|
198
|
-
Object.defineProperty(client, alias, {
|
|
199
|
-
value: new UnionClient(ctx, union),
|
|
200
|
-
writable: false,
|
|
201
|
-
enumerable: true,
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* A uuid as PostgreSQL prints it — lower case, hyphenated 8-4-4-4-12 — from any spelling its
|
|
207
|
-
* input accepts (upper case, braces, hyphens anywhere or none). Anything that is not 32 hex
|
|
208
|
-
* digits is returned as given: the database refuses it.
|
|
209
|
-
*/
|
|
210
|
-
function canonicalUuid(value) {
|
|
211
|
-
const hex = value.replace(/[{}-]/g, "").toLowerCase();
|
|
212
|
-
if (!/^[0-9a-f]{32}$/.test(hex))
|
|
213
|
-
return value;
|
|
214
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
215
|
-
}
|
|
216
|
-
//# sourceMappingURL=base.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/database/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,eAAe,EAKf,YAAY,GACb,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAQjD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAa,QAAQ,EAAE,MAAM,aAAa,CAAC;AASlD,MAAM,OAAgB,UAAU;IACX,IAAI,CAAsB;IAE7C,qFAAqF;IAClE,OAAO,GAAG,IAAI,GAAG,EAAoC,CAAC;IAEzE,YAAY,GAAwB;QAClC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IAClB,CAAC;IAED;;;;OAIG;IACK,eAAe,CAAC,MAAc;QACpC,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,MAAM,IAAI,YAAY,CACpB,GAAG,MAAM,8EAA8E;gBACrF,yDAAyD,CAC5D,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACK,YAAY,CAClB,EAAU,EACV,EAA4B;QAE5B,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,cAAc,CAAC,EAAE,CAAC,CAAC;QACvC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEj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,UAAU,EAAE,IAAI;SACjB,CAAC,CAAC;IACL,CAAC;IAED,4FAA4F;IAC5F,uDAAuD;IACvD,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;QACpD,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE;YACnC,KAAK,EAAE,IAAI,WAAW,CAAqB,GAAG,EAAE,KAAK,CAAC;YACtD,QAAQ,EAAE,KAAK;YACf,UAAU,EAAE,IAAI;SACjB,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACtD,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;AAC7G,CAAC","sourcesContent":["import {\n AnySchema,\n AnyTable,\n DefinitionSchema,\n ExecutableQuery,\n ExecutionContext,\n Schema,\n SQLQuery,\n SQLStatement,\n TenancyError,\n} from \"@dsqlbase/core\";\nimport { AnyUnionMembers } from \"@dsqlbase/core/definition\";\nimport { ModelClient } from \"../model/client.js\";\nimport { UnionClient } from \"../union/client.js\";\nimport {\n GlobalIdListResultOf,\n GlobalIdOptionsOf,\n GlobalIdResultOf,\n JoinExpressionOf,\n} from \"../model/base.js\";\nimport { WhereExpressionOf } from \"../model/filters.js\";\nimport { GlobalIdError, decodeGlobalId } from \"../../schema/utils/global-id.js\";\nimport { NodeTable, getNodes } from \"../nodes.js\";\n\n/** The member arguments an `on` entry carries into a global-id lookup. */\ntype NodeArgs = {\n select?: Record<string, boolean>;\n where?: WhereExpressionOf<AnyTable>;\n join?: JoinExpressionOf<AnyTable, AnySchema>;\n};\n\nexport abstract class BaseClient<T extends DefinitionSchema> {\n protected readonly _ctx: ExecutionContext<T>;\n\n /** One model per table, keyed by schema alias. Populated by {@link attachModels}. */\n protected readonly _models = new Map<string, ModelClient<AnyTable, T>>();\n\n constructor(ctx: ExecutionContext<T>) {\n this._ctx = ctx;\n }\n\n /**\n * Raw SQL bypasses every seam the operations factory applies, the tenant predicate included,\n * so a scoped client does not carry it. The types remove it; this is the runtime half, for\n * callers reaching it through a widened type.\n */\n private _assertUnscoped(method: string): void {\n if (this._ctx.identity) {\n throw new TenancyError(\n `${method} is not available on an identity-scoped client: raw SQL is not tenant-safe. ` +\n `Use it on the base client, where that is plain to read.`\n );\n }\n }\n\n /**\n * Resolves a global id to the node it names, and to how the caller wants it read.\n *\n * Every failure is raised here, before a query is built: an id that does not decode, one\n * naming a table that is not a node, one whose payload is not that node's key, and one the\n * caller's `on` map excluded.\n */\n private _resolveNode(\n id: string,\n on?: Record<string, unknown>\n ): { node: NodeTable; value: string; args: NodeArgs } {\n const { key, pk } = decodeGlobalId(id);\n const node = getNodes(this._ctx.schema).get(key);\n\n if (!node) {\n throw new GlobalIdError(\"unknown_node\", `\"${key}\" is not a node in this schema.`);\n }\n\n const fields = Object.keys(pk);\n\n if (fields.length !== 1 || fields[0] !== node.keyField) {\n throw new GlobalIdError(\n \"key_mismatch\",\n `Global id for \"${key}\" carries ${fields.map((field) => `\"${field}\"`).join(\", \")} ` +\n `rather than its key \"${node.keyField}\".`\n );\n }\n\n const option = on?.[node.alias];\n\n if (option === false) {\n throw new GlobalIdError(\n \"unknown_node\",\n `\"${node.alias}\" was excluded from this lookup by its \\`on\\` map.`\n );\n }\n\n const { select, where, join } = (\n option && typeof option === \"object\" ? option : {}\n ) as NodeArgs;\n\n return { node, value: pk[node.keyField], args: { select, where, join } };\n }\n\n /**\n * A `where` over a field named at runtime.\n *\n * `_models` is keyed by alias and typed over `AnyTable`, so the key field is a `string` the\n * compiler cannot match to a column. The node registry resolved it against the real table\n * when the client was built, which is the check this cast stands on.\n */\n private _byKey(field: string, condition: object): WhereExpressionOf<AnyTable> {\n return { [field]: condition } as WhereExpressionOf<AnyTable>;\n }\n\n /**\n * The lookup's own key filter, AND-ed with the member's `on.<alias>.where` when it has one. A\n * row that fails the member filter is a miss, exactly as if the id named nothing.\n */\n private _lookupWhere(\n field: string,\n condition: object,\n where: WhereExpressionOf<AnyTable> | undefined\n ): WhereExpressionOf<AnyTable> {\n const key = this._byKey(field, condition);\n\n return where ? ({ and: [key, where] } as WhereExpressionOf<AnyTable>) : key;\n }\n\n private _model(alias: string): ModelClient<AnyTable, T> {\n const model = this._models.get(alias);\n\n if (!model) {\n throw new Error(`No model is attached for \"${alias}\".`);\n }\n\n return model;\n }\n\n /**\n * Reads the single row a global id names, or `null` when it no longer exists.\n *\n * The lookup runs through the table's own model client rather than issuing SQL of its own,\n * so every seam a `findOne` passes applies to it — the tenant predicate above all. A node\n * lookup that bypassed it would be a cross-tenant read; going through the model makes that\n * structurally impossible rather than something to remember.\n *\n * The row is tagged with `$$key`, the alias it came from, which is what narrows the union.\n * `$$meta.key` carries the same value but cannot be used for it: TypeScript does not narrow\n * on a nested discriminant.\n *\n * @example\n * ```ts\n * const record = await dsql.$findByGlobalId({\n * id,\n * on: { users: { select: { id: true, name: true } }, workspaces: true },\n * });\n *\n * if (record?.$$key === \"users\") record.name;\n * ```\n *\n * @throws GlobalIdError when the id does not decode, names a table that is not a node,\n * carries a payload that is not that node's key, or names a member `on` set to `false`.\n */\n async $findByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {\n id: string;\n on?: TOn;\n }): Promise<GlobalIdResultOf<Schema<T>, TOn>> {\n const { node, value, args: nodeArgs } = this._resolveNode(args.id, args.on);\n const { select, where, join } = nodeArgs;\n\n const row = (await this._model(node.alias).findOne({\n where: this._lookupWhere(node.keyField, { eq: value }, where),\n ...(select ? { select } : {}),\n ...(join ? { join } : {}),\n })) as Record<string, unknown> | null;\n\n return (row ? this._tag(row, node) : null) as GlobalIdResultOf<Schema<T>, TOn>;\n }\n\n /** Tags a resolved row with the alias it came from, so a caller can narrow the union. */\n private _tag(row: Record<string, unknown>, node: NodeTable): Record<string, unknown> {\n return { ...row, $$key: node.alias };\n }\n\n /**\n * Reads many global ids at once: one query per table rather than one per id, with the\n * results handed back **in the order the ids were given** and `null` wherever a row no\n * longer exists — the shape a batch resolver wants.\n *\n * Unlike {@link $findByGlobalId} this cannot be a single `ExecutableQuery`, because ids\n * from different tables fan out to different queries.\n *\n * The node's key field is always projected, even when `select` leaves it out: matching a\n * row back to the id that asked for it is what the key is for.\n *\n * @throws GlobalIdError on the first id that does not resolve. A missing *row* is a `null`\n * in the result; a malformed id is a caller bug and is not silently dropped.\n */\n async $listByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {\n ids: readonly string[];\n on?: TOn;\n }): Promise<(GlobalIdListResultOf<Schema<T>, TOn> | null)[]> {\n const resolved = args.ids.map((id) => this._resolveNode(id, args.on));\n const groups = new Map<string, { node: NodeTable; values: Set<string>; args: NodeArgs }>();\n\n for (const { node, value, args: nodeArgs } of resolved) {\n const group = groups.get(node.alias) ?? { node, values: new Set<string>(), args: nodeArgs };\n\n group.values.add(value);\n groups.set(node.alias, group);\n }\n\n // One query per table, all of them in flight together. Rows are matched back by node and\n // canonical key, not by id text: the database finds a row for any spelling of its uuid.\n const rows = new Map<string, Record<string, unknown>>();\n const keyOf = (alias: string, value: string) => `${alias}\\u0000${canonicalUuid(value)}`;\n\n await Promise.all(\n [...groups.values()].map(async ({ node, values, args: { select, where, join } }) => {\n const found = (await this._model(node.alias).findMany({\n where: this._lookupWhere(node.keyField, { in: [...values] }, where),\n // The key is always projected: it is the only thing that can put a row back\n // against the id that asked for it.\n ...(select ? { select: { ...select, [node.keyField]: true } } : {}),\n ...(join ? { join } : {}),\n })) as unknown as Record<string, unknown>[];\n\n for (const row of found) {\n // The key column reads back wrapped as a global id; its payload is the stored uuid.\n const { pk } = decodeGlobalId(String(row[node.keyField]));\n rows.set(keyOf(node.alias, pk[node.keyField] ?? \"\"), this._tag(row, node));\n }\n })\n );\n\n return resolved.map(\n ({ node, value }) =>\n (rows.get(keyOf(node.alias, value)) ?? null) as GlobalIdListResultOf<Schema<T>, TOn> | null\n );\n }\n\n $query<T = unknown>(sql: SQLQuery) {\n this._assertUnscoped(\"$query\");\n\n return new ExecutableQuery<T[]>(\n {\n mode: \"many\",\n name: \"anonymous_query\",\n type: \"select\",\n args: {},\n query: sql.toQuery(),\n resolve: (result) => result,\n },\n this._ctx.session\n );\n }\n\n async $execute<T = unknown>(query: SQLStatement): Promise<T[]> {\n this._assertUnscoped(\"$execute\");\n\n // A `sql` template here is an object with no `text`: the session would run nothing.\n if (typeof (query as Partial<SQLStatement> | null)?.text !== \"string\") {\n throw new TypeError(\n \"$execute takes a rendered statement ({ text, params }); pass a sql`…` template to \" +\n \"$query, or call .toQuery() on it.\"\n );\n }\n\n return this._ctx.session.execute<T>(query);\n }\n}\n\n/**\n * Attaches one {@link ModelClient} per table to a client, keyed by the table's schema\n * alias, as a non-writable enumerable property. Shared by `createClient` and the\n * transaction client so a derived client is built exactly one way.\n *\n * Tables are taken from `SchemaRegistry.getTableEntries()`, which yields each table once\n * under its alias — `getTables()` holds every table under both its alias and its database\n * name, which would attach two models for an aliased table.\n */\nexport function attachModels<T extends DefinitionSchema>(\n client: BaseClient<T>,\n ctx: ExecutionContext<T>\n): void {\n for (const [alias, table] of ctx.schema.getTableEntries()) {\n const model = new ModelClient<AnyTable, T>(ctx, table);\n\n client[\"_models\"].set(alias, model);\n\n Object.defineProperty(client, alias, {\n value: model,\n writable: false,\n enumerable: true,\n });\n }\n\n // Unions are read under their own alias, next to the tables; the registry already refused a\n // union named like a table, so the two cannot collide.\n for (const [alias, union] of ctx.schema.getUnions()) {\n Object.defineProperty(client, alias, {\n value: new UnionClient<AnyUnionMembers, T>(ctx, union),\n writable: false,\n enumerable: true,\n });\n }\n}\n\n/**\n * A uuid as PostgreSQL prints it — lower case, hyphenated 8-4-4-4-12 — from any spelling its\n * input accepts (upper case, braces, hyphens anywhere or none). Anything that is not 32 hex\n * digits is returned as given: the database refuses it.\n */\nfunction canonicalUuid(value: string): string {\n const hex = value.replace(/[{}-]/g, \"\").toLowerCase();\n if (!/^[0-9a-f]{32}$/.test(hex)) return value;\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n"]}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { DefinitionSchema, Executable, Schema } from "@dsqlbase/core";
|
|
2
|
-
import { BaseClient } from "./base.js";
|
|
3
|
-
import { TxClient } from "../transaction/transaction-client.js";
|
|
4
|
-
import { ClaimsOf, IdentityClient } from "./index.js";
|
|
5
|
-
export declare class DatabaseClient<TDefinition extends DefinitionSchema, TClaims = never, TEnforce extends boolean = true> extends BaseClient<TDefinition> {
|
|
6
|
-
/**
|
|
7
|
-
* A client scoped to `claims`, for the life of one request. Scope first, then open a
|
|
8
|
-
* transaction on the result: a transaction client cannot be scoped, so there is one order.
|
|
9
|
-
*
|
|
10
|
-
* The claims are picked from the argument by name, so `{ ...jwt.claims }` may carry anything
|
|
11
|
-
* else it likes; only what the schema declares is kept. A claim the schema declares but the
|
|
12
|
-
* argument leaves out is allowed — the tables needing it simply are not on the result — but a
|
|
13
|
-
* claim given as `null` or `undefined` throws, because that is a mapping bug rather than a
|
|
14
|
-
* narrower scope. A misspelled claim inside a spread is not caught here, since there is
|
|
15
|
-
* nothing to compare it against, and surfaces at the first tenant table it cannot scope.
|
|
16
|
-
*
|
|
17
|
-
* Derives rather than mutates: the client this was called on stays usable, and a query's SQL
|
|
18
|
-
* is fixed by whichever client built it.
|
|
19
|
-
*/
|
|
20
|
-
$identityClaims<TNewClaims extends Partial<ClaimsOf<Schema<TDefinition>>>>(claims: TNewClaims): IdentityClient<TDefinition, TNewClaims>;
|
|
21
|
-
$transaction<const TQueries extends Executable<unknown>[]>(queries: TQueries): Promise<{
|
|
22
|
-
-readonly [K in keyof TQueries]: TQueries[K] extends Executable<infer TResult> ? TResult : never;
|
|
23
|
-
}>;
|
|
24
|
-
$transaction<TReturn = unknown>(callback: (tx: TxClient<TDefinition, TClaims, TEnforce>) => Promise<TReturn>): Promise<TReturn>;
|
|
25
|
-
}
|
|
26
|
-
//# sourceMappingURL=client.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/client/database/client.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,UAAU,EAEV,MAAM,EAEP,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAgB,UAAU,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAA2B,QAAQ,EAAE,MAAM,sCAAsC,CAAC;AACzF,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEtD,qBAAa,cAAc,CACzB,WAAW,SAAS,gBAAgB,EACpC,OAAO,GAAG,KAAK,EACf,QAAQ,SAAS,OAAO,GAAG,IAAI,CAC/B,SAAQ,UAAU,CAAC,WAAW,CAAC;IAC/B;;;;;;;;;;;;;OAaG;IACI,eAAe,CAAC,UAAU,SAAS,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,EAC9E,MAAM,EAAE,UAAU,GACjB,cAAc,CAAC,WAAW,EAAE,UAAU,CAAC;IAsC7B,YAAY,CAAC,KAAK,CAAC,QAAQ,SAAS,UAAU,CAAC,OAAO,CAAC,EAAE,EACpE,OAAO,EAAE,QAAQ,GAChB,OAAO,CAAC;QACT,CAAC,UAAU,CAAC,IAAI,MAAM,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,SAAS,UAAU,CAAC,MAAM,OAAO,CAAC,GAC1E,OAAO,GACP,KAAK;KACV,CAAC;IACW,YAAY,CAAC,OAAO,GAAG,OAAO,EACzC,QAAQ,EAAE,CAAC,EAAE,EAAE,QAAQ,CAAC,WAAW,EAAE,OAAO,EAAE,QAAQ,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,GAC3E,OAAO,CAAC,OAAO,CAAC;CASpB"}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { ExecutionContext, TenancyError, } from "@dsqlbase/core";
|
|
2
|
-
import { attachModels, BaseClient } from "./base.js";
|
|
3
|
-
import { createTransactionRunner } from "../transaction/transaction-client.js";
|
|
4
|
-
export class DatabaseClient extends BaseClient {
|
|
5
|
-
/**
|
|
6
|
-
* A client scoped to `claims`, for the life of one request. Scope first, then open a
|
|
7
|
-
* transaction on the result: a transaction client cannot be scoped, so there is one order.
|
|
8
|
-
*
|
|
9
|
-
* The claims are picked from the argument by name, so `{ ...jwt.claims }` may carry anything
|
|
10
|
-
* else it likes; only what the schema declares is kept. A claim the schema declares but the
|
|
11
|
-
* argument leaves out is allowed — the tables needing it simply are not on the result — but a
|
|
12
|
-
* claim given as `null` or `undefined` throws, because that is a mapping bug rather than a
|
|
13
|
-
* narrower scope. A misspelled claim inside a spread is not caught here, since there is
|
|
14
|
-
* nothing to compare it against, and surfaces at the first tenant table it cannot scope.
|
|
15
|
-
*
|
|
16
|
-
* Derives rather than mutates: the client this was called on stays usable, and a query's SQL
|
|
17
|
-
* is fixed by whichever client built it.
|
|
18
|
-
*/
|
|
19
|
-
$identityClaims(claims) {
|
|
20
|
-
if (this._ctx.identity) {
|
|
21
|
-
throw new TenancyError("This client is already scoped to an identity. Claims are set in exactly one place; " +
|
|
22
|
-
"derive from the base client instead.");
|
|
23
|
-
}
|
|
24
|
-
const identity = {};
|
|
25
|
-
const given = claims;
|
|
26
|
-
for (const claim of this._ctx.schema.claimKeys.keys()) {
|
|
27
|
-
if (!Object.hasOwn(given, claim)) {
|
|
28
|
-
continue;
|
|
29
|
-
}
|
|
30
|
-
const value = given[claim];
|
|
31
|
-
if (value === undefined || value === null) {
|
|
32
|
-
throw new TenancyError(`Claim "${claim}" was given as ${String(value)}. Leave a claim out to narrow what ` +
|
|
33
|
-
`the client can reach; an empty one scopes nothing.`, undefined, claim);
|
|
34
|
-
}
|
|
35
|
-
identity[claim] = value;
|
|
36
|
-
}
|
|
37
|
-
const ctx = new ExecutionContext({ ...this._ctx, identity });
|
|
38
|
-
const client = new DatabaseClient(ctx);
|
|
39
|
-
attachModels(client, ctx);
|
|
40
|
-
return client;
|
|
41
|
-
}
|
|
42
|
-
async $transaction(arg) {
|
|
43
|
-
const runner = await createTransactionRunner(this._ctx);
|
|
44
|
-
return runner(arg);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
//# sourceMappingURL=client.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/client/database/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,gBAAgB,EAEhB,YAAY,GACb,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAY,MAAM,sCAAsC,CAAC;AAGzF,MAAM,OAAO,cAIX,SAAQ,UAAuB;IAC/B;;;;;;;;;;;;;OAaG;IACI,eAAe,CACpB,MAAkB;QAElB,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,MAAM,IAAI,YAAY,CACpB,qFAAqF;gBACnF,sCAAsC,CACzC,CAAC;QACJ,CAAC;QAED,MAAM,QAAQ,GAA4B,EAAE,CAAC;QAC7C,MAAM,KAAK,GAAG,MAAiC,CAAC;QAEhD,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,CAAC;YACtD,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;gBACjC,SAAS;YACX,CAAC;YAED,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YAE3B,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;gBAC1C,MAAM,IAAI,YAAY,CACpB,UAAU,KAAK,kBAAkB,MAAM,CAAC,KAAK,CAAC,qCAAqC;oBACjF,oDAAoD,EACtD,SAAS,EACT,KAAK,CACN,CAAC;YACJ,CAAC;YAED,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;QAC1B,CAAC;QAED,MAAM,GAAG,GAAG,IAAI,gBAAgB,CAAc,EAAE,GAAG,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC1E,MAAM,MAAM,GAAG,IAAI,cAAc,CAAoC,GAAG,CAAC,CAAC;QAE1E,YAAY,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAE1B,OAAO,MAA4D,CAAC;IACtE,CAAC;IAYM,KAAK,CAAC,YAAY,CACvB,GAE4E;QAE5E,MAAM,MAAM,GAAG,MAAM,uBAAuB,CAAiC,IAAI,CAAC,IAAI,CAAC,CAAC;QACxF,OAAO,MAAM,CAAU,GAAG,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["import {\n DefinitionSchema,\n Executable,\n ExecutionContext,\n Schema,\n TenancyError,\n} from \"@dsqlbase/core\";\nimport { attachModels, BaseClient } from \"./base.js\";\nimport { createTransactionRunner, TxClient } from \"../transaction/transaction-client.js\";\nimport { ClaimsOf, IdentityClient } from \"./index.js\";\n\nexport class DatabaseClient<\n TDefinition extends DefinitionSchema,\n TClaims = never,\n TEnforce extends boolean = true,\n> extends BaseClient<TDefinition> {\n /**\n * A client scoped to `claims`, for the life of one request. Scope first, then open a\n * transaction on the result: a transaction client cannot be scoped, so there is one order.\n *\n * The claims are picked from the argument by name, so `{ ...jwt.claims }` may carry anything\n * else it likes; only what the schema declares is kept. A claim the schema declares but the\n * argument leaves out is allowed — the tables needing it simply are not on the result — but a\n * claim given as `null` or `undefined` throws, because that is a mapping bug rather than a\n * narrower scope. A misspelled claim inside a spread is not caught here, since there is\n * nothing to compare it against, and surfaces at the first tenant table it cannot scope.\n *\n * Derives rather than mutates: the client this was called on stays usable, and a query's SQL\n * is fixed by whichever client built it.\n */\n public $identityClaims<TNewClaims extends Partial<ClaimsOf<Schema<TDefinition>>>>(\n claims: TNewClaims\n ): IdentityClient<TDefinition, TNewClaims> {\n if (this._ctx.identity) {\n throw new TenancyError(\n \"This client is already scoped to an identity. Claims are set in exactly one place; \" +\n \"derive from the base client instead.\"\n );\n }\n\n const identity: Record<string, unknown> = {};\n const given = claims as Record<string, unknown>;\n\n for (const claim of this._ctx.schema.claimKeys.keys()) {\n if (!Object.hasOwn(given, claim)) {\n continue;\n }\n\n const value = given[claim];\n\n if (value === undefined || value === null) {\n throw new TenancyError(\n `Claim \"${claim}\" was given as ${String(value)}. Leave a claim out to narrow what ` +\n `the client can reach; an empty one scopes nothing.`,\n undefined,\n claim\n );\n }\n\n identity[claim] = value;\n }\n\n const ctx = new ExecutionContext<TDefinition>({ ...this._ctx, identity });\n const client = new DatabaseClient<TDefinition, TNewClaims, TEnforce>(ctx);\n\n attachModels(client, ctx);\n\n return client as unknown as IdentityClient<TDefinition, TNewClaims>;\n }\n\n public async $transaction<const TQueries extends Executable<unknown>[]>(\n queries: TQueries\n ): Promise<{\n -readonly [K in keyof TQueries]: TQueries[K] extends Executable<infer TResult>\n ? TResult\n : never;\n }>;\n public async $transaction<TReturn = unknown>(\n callback: (tx: TxClient<TDefinition, TClaims, TEnforce>) => Promise<TReturn>\n ): Promise<TReturn>;\n public async $transaction<TReturn = unknown>(\n arg:\n | Executable<unknown>[]\n | ((client: TxClient<TDefinition, TClaims, TEnforce>) => Promise<TReturn>)\n ): Promise<TReturn> {\n const runner = await createTransactionRunner<TDefinition, TClaims, TEnforce>(this._ctx);\n return runner<TReturn>(arg);\n }\n}\n"]}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import { AnyTable, AnySchema, DefinitionSchema, RuntimeTables, Schema } from "@dsqlbase/core";
|
|
2
|
-
import { TableByAlias } from "@dsqlbase/core/runtime";
|
|
3
|
-
import { UnionToIntersection } from "@dsqlbase/core/utils";
|
|
4
|
-
import { ModelClient } from "../model/client.js";
|
|
5
|
-
import { ColumnTypeOf, TenantKeysOf, UnionMembersOf, ValueTypeOf } from "../model/base.js";
|
|
6
|
-
import { UnionClient } from "../union/client.js";
|
|
7
|
-
import { DatabaseClient } from "./client.js";
|
|
8
|
-
/** Every union alias in a schema. */
|
|
9
|
-
export type UnionAliases<T extends DefinitionSchema> = keyof Schema<T>["unions"] & string;
|
|
10
|
-
/**
|
|
11
|
-
* Every alias in a schema the client addresses a model by: each table, and each union.
|
|
12
|
-
*/
|
|
13
|
-
export type Aliases<T extends DefinitionSchema> = keyof RuntimeTables<Schema<T>> | UnionAliases<T>;
|
|
14
|
-
/**
|
|
15
|
-
* The claims a schema declares, as one object.
|
|
16
|
-
*
|
|
17
|
-
* Gathered across tables rather than per table, because that is how an identity is given: one
|
|
18
|
-
* object for the whole client. A claim declared twice with different value types collapses to
|
|
19
|
-
* `never` here, mirroring the registry's data-type check at runtime.
|
|
20
|
-
*/
|
|
21
|
-
export type ClaimsOf<TSchema extends AnySchema> = UnionToIntersection<{
|
|
22
|
-
[A in keyof RuntimeTables<TSchema> & string]: {
|
|
23
|
-
[C in TenantKeysOf<TableByAlias<TSchema, A>>]: ValueTypeOf<ColumnTypeOf<TableByAlias<TSchema, A>, C>>;
|
|
24
|
-
};
|
|
25
|
-
}[keyof RuntimeTables<TSchema> & string]>;
|
|
26
|
-
/**
|
|
27
|
-
* The aliases a client holding `TClaims` may address: every global table, plus every tenant
|
|
28
|
-
* table whose claims the identity carries in full. A table needing a claim that is not there is
|
|
29
|
-
* not hidden to be tidy — it is hidden because reaching it would throw.
|
|
30
|
-
*/
|
|
31
|
-
export type VisibleAliases<TSchema extends AnySchema, TClaims> = VisibleTableAliases<TSchema, TClaims> | VisibleUnionAliases<TSchema, TClaims>;
|
|
32
|
-
type VisibleTableAliases<TSchema extends AnySchema, TClaims> = {
|
|
33
|
-
[A in keyof RuntimeTables<TSchema> & string]: [
|
|
34
|
-
TenantKeysOf<TableByAlias<TSchema, A>>
|
|
35
|
-
] extends [keyof TClaims] ? A : never;
|
|
36
|
-
}[keyof RuntimeTables<TSchema> & string];
|
|
37
|
-
/**
|
|
38
|
-
* A union is visible only when every member is: each read runs a branch per member, and one
|
|
39
|
-
* branch a client cannot reach makes the whole read throw.
|
|
40
|
-
*/
|
|
41
|
-
type VisibleUnionAliases<TSchema extends AnySchema, TClaims> = {
|
|
42
|
-
[U in keyof TSchema["unions"] & string]: [
|
|
43
|
-
Exclude<keyof UnionMembersOf<TSchema["unions"][U]>, VisibleTableAliases<TSchema, TClaims>>
|
|
44
|
-
] extends [never] ? U : never;
|
|
45
|
-
}[keyof TSchema["unions"] & string];
|
|
46
|
-
/**
|
|
47
|
-
* Which aliases a client shows, given its claims and whether it enforces.
|
|
48
|
-
*
|
|
49
|
-
* An unscoped client sees everything when enforcement is off, and only the global tables when
|
|
50
|
-
* it is on — the same rule the runtime applies, so the type never promises a table that would
|
|
51
|
-
* throw.
|
|
52
|
-
*/
|
|
53
|
-
export type VisibleFor<T extends DefinitionSchema, TClaims, TEnforce extends boolean> = [TClaims] extends [never] ? TEnforce extends false ? Aliases<T> : VisibleAliases<Schema<T>, object> : VisibleAliases<Schema<T>, TClaims>;
|
|
54
|
-
export type Models<T extends DefinitionSchema, TVisible extends Aliases<T> = Aliases<T>> = {
|
|
55
|
-
readonly [K in TVisible]: K extends keyof RuntimeTables<Schema<T>> ? RuntimeTables<Schema<T>>[K] extends infer TTable ? TTable extends AnyTable ? ModelClient<TTable, T> : never : never : K extends UnionAliases<T> ? UnionClient<UnionMembersOf<Schema<T>["unions"][K]>, T> : never;
|
|
56
|
-
};
|
|
57
|
-
export type QueryClient<T extends DefinitionSchema, TEnforce extends boolean = true> = DatabaseClient<T, never, TEnforce> & Models<T, VisibleFor<T, never, TEnforce>>;
|
|
58
|
-
/**
|
|
59
|
-
* A client scoped to an identity. It has no raw-SQL methods: `$query` on a scoped client would
|
|
60
|
-
* look tenant-safe and would not be, so it is removed rather than guarded only at runtime. It
|
|
61
|
-
* cannot be re-scoped either — claims are set in exactly one place.
|
|
62
|
-
*/
|
|
63
|
-
export type IdentityClient<T extends DefinitionSchema, TClaims> = Omit<DatabaseClient<T, TClaims>, "$query" | "$execute" | "$identityClaims"> & Models<T, VisibleFor<T, TClaims, true>>;
|
|
64
|
-
export { DatabaseClient };
|
|
65
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/database/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC3F,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,qCAAqC;AACrC,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,gBAAgB,IAAI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C,SAAS,gBAAgB,EAC1B,QAAQ,SAAS,OAAO,GAAG,IAAI,IAC7B,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC;AAEnF;;;;GAIG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,gBAAgB,EAAE,OAAO,IAAI,IAAI,CACpE,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,EAC1B,QAAQ,GAAG,UAAU,GAAG,iBAAiB,CAC1C,GACC,MAAM,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;AAE1C,OAAO,EAAE,cAAc,EAAE,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/database/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAwG7C,OAAO,EAAE,cAAc,EAAE,CAAC","sourcesContent":["import { AnyTable, AnySchema, DefinitionSchema, RuntimeTables, Schema } from \"@dsqlbase/core\";\nimport { TableByAlias } from \"@dsqlbase/core/runtime\";\nimport { UnionToIntersection } from \"@dsqlbase/core/utils\";\nimport { ModelClient } from \"../model/client.js\";\nimport { ColumnTypeOf, TenantKeysOf, UnionMembersOf, ValueTypeOf } from \"../model/base.js\";\nimport { UnionClient } from \"../union/client.js\";\nimport { DatabaseClient } from \"./client.js\";\n\n/** Every union alias in a schema. */\nexport type UnionAliases<T extends DefinitionSchema> = keyof Schema<T>[\"unions\"] & string;\n\n/**\n * Every alias in a schema the client addresses a model by: each table, and each union.\n */\nexport type Aliases<T extends DefinitionSchema> = keyof RuntimeTables<Schema<T>> | UnionAliases<T>;\n\n/**\n * The claims a schema declares, as one object.\n *\n * Gathered across tables rather than per table, because that is how an identity is given: one\n * object for the whole client. A claim declared twice with different value types collapses to\n * `never` here, mirroring the registry's data-type check at runtime.\n */\nexport type ClaimsOf<TSchema extends AnySchema> = UnionToIntersection<\n {\n [A in keyof RuntimeTables<TSchema> & string]: {\n [C in TenantKeysOf<TableByAlias<TSchema, A>>]: ValueTypeOf<\n ColumnTypeOf<TableByAlias<TSchema, A>, C>\n >;\n };\n }[keyof RuntimeTables<TSchema> & string]\n>;\n\n/**\n * The aliases a client holding `TClaims` may address: every global table, plus every tenant\n * table whose claims the identity carries in full. A table needing a claim that is not there is\n * not hidden to be tidy — it is hidden because reaching it would throw.\n */\nexport type VisibleAliases<TSchema extends AnySchema, TClaims> =\n | VisibleTableAliases<TSchema, TClaims>\n | VisibleUnionAliases<TSchema, TClaims>;\n\ntype VisibleTableAliases<TSchema extends AnySchema, TClaims> = {\n [A in keyof RuntimeTables<TSchema> & string]: [\n TenantKeysOf<TableByAlias<TSchema, A>>,\n ] extends [keyof TClaims]\n ? A\n : never;\n}[keyof RuntimeTables<TSchema> & string];\n\n/**\n * A union is visible only when every member is: each read runs a branch per member, and one\n * branch a client cannot reach makes the whole read throw.\n */\ntype VisibleUnionAliases<TSchema extends AnySchema, TClaims> = {\n [U in keyof TSchema[\"unions\"] & string]: [\n Exclude<keyof UnionMembersOf<TSchema[\"unions\"][U]>, VisibleTableAliases<TSchema, TClaims>>,\n ] extends [never]\n ? U\n : never;\n}[keyof TSchema[\"unions\"] & string];\n\n/**\n * Which aliases a client shows, given its claims and whether it enforces.\n *\n * An unscoped client sees everything when enforcement is off, and only the global tables when\n * it is on — the same rule the runtime applies, so the type never promises a table that would\n * throw.\n */\nexport type VisibleFor<\n T extends DefinitionSchema,\n TClaims,\n TEnforce extends boolean,\n> = [TClaims] extends [never]\n ? TEnforce extends false\n ? Aliases<T>\n : VisibleAliases<Schema<T>, object>\n : VisibleAliases<Schema<T>, TClaims>;\n\nexport type Models<\n T extends DefinitionSchema,\n TVisible extends Aliases<T> = Aliases<T>,\n> = {\n readonly [K in TVisible]: K extends keyof RuntimeTables<Schema<T>>\n ? RuntimeTables<Schema<T>>[K] extends infer TTable\n ? TTable extends AnyTable\n ? ModelClient<TTable, T>\n : never\n : never\n : K extends UnionAliases<T>\n ? UnionClient<UnionMembersOf<Schema<T>[\"unions\"][K]>, T>\n : never;\n};\n\nexport type QueryClient<\n T extends DefinitionSchema,\n TEnforce extends boolean = true,\n> = DatabaseClient<T, never, TEnforce> & Models<T, VisibleFor<T, never, TEnforce>>;\n\n/**\n * A client scoped to an identity. It has no raw-SQL methods: `$query` on a scoped client would\n * look tenant-safe and would not be, so it is removed rather than guarded only at runtime. It\n * cannot be re-scoped either — claims are set in exactly one place.\n */\nexport type IdentityClient<T extends DefinitionSchema, TClaims> = Omit<\n DatabaseClient<T, TClaims>,\n \"$query\" | \"$execute\" | \"$identityClaims\"\n> &\n Models<T, VisibleFor<T, TClaims, true>>;\n\nexport { DatabaseClient };\n"]}
|