uql-orm 0.113.0 → 0.114.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/README.md +2 -2
- package/dist/entity/columnOptionsBuilder.d.ts +2 -1
- package/dist/entity/columnOptionsBuilder.js +3 -0
- package/dist/entity/metadata/definition.js +3 -0
- package/dist/http/api.d.ts +2 -2
- package/dist/http/api.js +24 -20
- package/dist/http/apiCall.d.ts +2 -2
- package/dist/http/exposure.d.ts +19 -35
- package/dist/http/exposure.js +44 -58
- package/dist/http/index.d.ts +1 -1
- package/dist/migrate/codegen/entityCodeGenerator.js +2 -2
- package/dist/type/column.d.ts +9 -4
- package/dist/type/definedEntity.d.ts +3 -0
- package/dist/type/entity.d.ts +14 -4
- package/dist/type/query.d.ts +6 -0
- package/dist/type/universalQuerier.d.ts +1 -2
- package/dist/util/dialect.util.d.ts +1 -1
- package/dist/util/dialect.util.js +2 -2
- package/dist/util/field.util.d.ts +3 -0
- package/dist/util/field.util.js +4 -0
- package/dist/util/fieldOption.util.js +2 -0
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +30 -4
package/README.md
CHANGED
|
@@ -143,14 +143,14 @@ const posts = await pool.findMany(Post, {
|
|
|
143
143
|
|
|
144
144
|
The result is typed to what the query selected: `posts[0].author?.email` compiles, `posts[0].likes` does not.
|
|
145
145
|
|
|
146
|
-
The same queries run from the browser too: [serve them over
|
|
146
|
+
The same queries run from the browser too: [serve them over HTTP, tRPC or oRPC](https://uql-orm.dev/http), each field exposed as you declare, scoped to the signed-in user by [filters no `$where` can widen](https://uql-orm.dev/multi-tenancy).
|
|
147
147
|
|
|
148
148
|
## Why UQL?
|
|
149
149
|
|
|
150
150
|
- **One API, everywhere it runs.** PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, MSSQL, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun's native SQL, and even MongoDB. The same code on Node 22.18+, Bun, [Cloudflare Workers](https://uql-orm.dev/cloudflare-d1), [AWS Lambda and Vercel](https://uql-orm.dev/serverless), and [the browser](https://uql-orm.dev/browser), with no native binaries on the `fetch`-based drivers.
|
|
151
151
|
- **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
|
|
152
152
|
- **Decorators or plain data, your call.** An entity is a class with [standard TC39 decorators](https://uql-orm.dev/entities/basic), or plain data via [`defineEntity`](https://uql-orm.dev/entities/define-entity), its row type derived. Both are typed the same, mix in one project, and need no compiler flags or `reflect-metadata`.
|
|
153
|
-
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about
|
|
153
|
+
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 49 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
|
|
154
154
|
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [multi-tenant filters you cannot bypass by accident](https://uql-orm.dev/multi-tenancy), [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming), and [drift checks](https://uql-orm.dev/migrations) that catch a database that no longer matches.
|
|
155
155
|
- **SQL when you need it.** [`sql()`](https://uql-orm.dev/querying/raw-sql) fits anywhere a value or a field goes, [computed fields](https://uql-orm.dev/entities/computed-fields) are SQL you can filter and sort on, and a migration can be plain SQL.
|
|
156
156
|
- **The fastest ORM.** On a full PostgreSQL round trip it adds the least over hand-written driver code of any ORM in our open-source [benchmark](https://github.com/rogerpadilla/ts-orm-benchmark), on Bun and Node alike. The same benchmark [scores the types](https://github.com/rogerpadilla/ts-orm-benchmark#type-safety) by compiling ordinary mistakes in each ORM's API: UQL is the only one that catches them all.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ForeignKeyAction } from '../schema/types.js';
|
|
2
|
-
import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance } from '../type/index.js';
|
|
2
|
+
import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type OnFieldCallback, type QuerySql, type StampEvent, type StandardSchemaV1, type Type, type VectorDistance, type Wire } from '../type/index.js';
|
|
3
3
|
/**
|
|
4
4
|
* Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
|
|
5
5
|
* `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
|
|
@@ -20,6 +20,7 @@ export declare class ColumnOptionsBuilder {
|
|
|
20
20
|
name(name: string): ColumnOptionsBuilder;
|
|
21
21
|
comment(comment: string): ColumnOptionsBuilder;
|
|
22
22
|
eager(eager: false): ColumnOptionsBuilder;
|
|
23
|
+
wire(wire: Wire): ColumnOptionsBuilder;
|
|
23
24
|
columnType(columnType: ColumnType): ColumnOptionsBuilder;
|
|
24
25
|
columnType(columnType: QuerySql): ColumnOptionsBuilder;
|
|
25
26
|
references(references: () => Type<object>): ColumnOptionsBuilder;
|
|
@@ -220,6 +220,7 @@ function settleEntity(entity) {
|
|
|
220
220
|
name: options.table,
|
|
221
221
|
schema: options.schema,
|
|
222
222
|
abstract: options.abstract,
|
|
223
|
+
wire: options.wire,
|
|
223
224
|
indexes: sections.indexes,
|
|
224
225
|
checks: sections.checks,
|
|
225
226
|
triggers: sections.triggers,
|
|
@@ -327,6 +328,7 @@ export function registerEntity(entity, opts = {}, members) {
|
|
|
327
328
|
meta.derivedName = opts.name === undefined;
|
|
328
329
|
meta.schema = opts.schema;
|
|
329
330
|
meta.abstract = opts.abstract;
|
|
331
|
+
meta.wire = opts.wire;
|
|
330
332
|
inheritFrom(meta, parentOf(entity));
|
|
331
333
|
if (!hasKeys(meta.fields)) {
|
|
332
334
|
throw new UqlUsageError(`'${entity.name}' must have fields`);
|
|
@@ -782,6 +784,7 @@ function extendMeta(target, source) {
|
|
|
782
784
|
}
|
|
783
785
|
}
|
|
784
786
|
target.fields = { ...sourceFields, ...target.fields };
|
|
787
|
+
target.wire ??= source.wire;
|
|
785
788
|
// Inherit user-defined filters from the parent (child overrides by name). The built-in soft-delete
|
|
786
789
|
// filter + `meta.softDelete` are (re)derived from the merged fields at registration.
|
|
787
790
|
if (source.filters) {
|
package/dist/http/api.d.ts
CHANGED
|
@@ -5,8 +5,8 @@ import { type ApiOp, type EntityPathOptions } from './wireCall.js';
|
|
|
5
5
|
export type ApiOptions<Ctx = unknown> = EntityPathOptions & {
|
|
6
6
|
/**
|
|
7
7
|
* The entities served, and the only ones a call reaches, through a relation too: nothing is served by being
|
|
8
|
-
* defined, so an entity holding secrets (a session's token) stays off the wire unless named.
|
|
9
|
-
*
|
|
8
|
+
* defined, so an entity holding secrets (a session's token) stays off the wire unless named. Each entity's `wire`
|
|
9
|
+
* says what a client may do to it; `serve(User, { use })` runs middleware of its own.
|
|
10
10
|
*/
|
|
11
11
|
include: readonly (Type<object> | Served<object, Ctx>)[];
|
|
12
12
|
/** Run around every call, first to last, before an entity's own. */
|
package/dist/http/api.js
CHANGED
|
@@ -4,7 +4,7 @@ import { assertPageable } from '../querier/keyset.js';
|
|
|
4
4
|
import { whereWith } from '../util/query.util.js';
|
|
5
5
|
import { UqlError, UqlRequestError, UqlUsageError } from '../util/uqlError.js';
|
|
6
6
|
import { callOf, chain, isCallOf } from './apiCall.js';
|
|
7
|
-
import {
|
|
7
|
+
import { exposedQuery, servedEntry } from './exposure.js';
|
|
8
8
|
import { API_OPS, entityPathOf, isApiOp, parseWireCall, } from './wireCall.js';
|
|
9
9
|
import { parseWireQuery } from './wireQuery.js';
|
|
10
10
|
import { readWirePayload, readWireQuery, writeWireData } from './wireRow.js';
|
|
@@ -20,9 +20,13 @@ export function createApi(opts) {
|
|
|
20
20
|
if (!include?.length) {
|
|
21
21
|
throw new UqlUsageError("name the entities the API serves in 'include': it serves those alone");
|
|
22
22
|
}
|
|
23
|
-
const
|
|
24
|
-
const entities =
|
|
25
|
-
const
|
|
23
|
+
const entries = include.map(servedEntry);
|
|
24
|
+
const entities = entries.map(([entity]) => entity);
|
|
25
|
+
const served = new Map(entries);
|
|
26
|
+
const unwired = entities.filter((entity) => getMeta(entity).wire === false);
|
|
27
|
+
if (unwired.length) {
|
|
28
|
+
throw new UqlUsageError(`'wire: false' keeps ${unwired.map((entity) => `'${entity.name}'`).join(', ')} off every API: remove from 'include'`);
|
|
29
|
+
}
|
|
26
30
|
// All of them at once, so fixing the first collision does not just reveal the next.
|
|
27
31
|
const byPath = Map.groupBy(entities, pathOf);
|
|
28
32
|
const collisions = [...byPath].filter(([, clashing]) => clashing.length > 1);
|
|
@@ -36,21 +40,21 @@ export function createApi(opts) {
|
|
|
36
40
|
return {
|
|
37
41
|
serves: (path, op) => entityByPath.has(path) && isApiOp(op),
|
|
38
42
|
call: async (input, context) => {
|
|
39
|
-
const
|
|
40
|
-
const entity = entityByPath.get(
|
|
43
|
+
const sent = parseWireCall(input);
|
|
44
|
+
const entity = entityByPath.get(sent.entity);
|
|
41
45
|
if (!entity) {
|
|
42
46
|
// A 404, as a route that names no entity is: the call is well formed, its entity is not here.
|
|
43
|
-
throw new UqlRequestError(`'${
|
|
47
|
+
throw new UqlRequestError(`'${sent.entity}' is not an entity this API serves`, 404);
|
|
44
48
|
}
|
|
45
|
-
return run(entity,
|
|
49
|
+
return run(entity, sent, context);
|
|
46
50
|
},
|
|
47
51
|
};
|
|
48
|
-
async function run(entity,
|
|
52
|
+
async function run(entity, sent, context) {
|
|
49
53
|
const meta = getMeta(entity);
|
|
50
|
-
const shape = API_OPS[
|
|
51
|
-
const call = decodedCall(entity,
|
|
54
|
+
const shape = API_OPS[sent.op];
|
|
55
|
+
const call = decodedCall(entity, sent, served);
|
|
52
56
|
const appContext = contextOf ? ((await contextOf(context)) ?? {}) : (ambientContext() ?? {});
|
|
53
|
-
const around =
|
|
57
|
+
const around = served.get(entity);
|
|
54
58
|
const answer = () => chain(around ? [...use, around] : use, context, async (reshaped) => {
|
|
55
59
|
if (!isCallOf(entity, reshaped)) {
|
|
56
60
|
throw new UqlUsageError(`a middleware moved a call to '${entity.name}' to another entity`);
|
|
@@ -69,22 +73,22 @@ export function createApi(opts) {
|
|
|
69
73
|
}
|
|
70
74
|
}
|
|
71
75
|
/**
|
|
72
|
-
* The call `
|
|
76
|
+
* The call `sent` asks of `entity` as the querier takes it: its query and payload read back as the entity holds them,
|
|
73
77
|
* checked against what its op takes and what the API exposes. Run on what the client sent, before any middleware, so
|
|
74
78
|
* what a middleware adds is the server's own to add.
|
|
75
79
|
*/
|
|
76
|
-
function decodedCall(entity,
|
|
80
|
+
function decodedCall(entity, sent, served) {
|
|
77
81
|
const meta = getMeta(entity);
|
|
78
|
-
const { op } =
|
|
79
|
-
const query = readWireQuery(meta, parseWireQuery(
|
|
80
|
-
const payload = readWirePayload(meta,
|
|
82
|
+
const { op } = sent;
|
|
83
|
+
const query = readWireQuery(meta, parseWireQuery(sent.query));
|
|
84
|
+
const payload = readWirePayload(meta, sent.payload);
|
|
81
85
|
return callOf({
|
|
82
86
|
entity,
|
|
83
87
|
op,
|
|
84
|
-
id:
|
|
85
|
-
query: exposedQuery(meta, op, query, payload,
|
|
88
|
+
id: sent.id,
|
|
89
|
+
query: exposedQuery(meta, op, query, payload, served),
|
|
86
90
|
payload,
|
|
87
|
-
hardDelete:
|
|
91
|
+
hardDelete: sent.hardDelete ?? false,
|
|
88
92
|
});
|
|
89
93
|
}
|
|
90
94
|
/** A querier's refusal names its place within the query it refused: within the call, that is under `query`. */
|
package/dist/http/apiCall.d.ts
CHANGED
|
@@ -36,8 +36,8 @@ export type ApiCall<E, Op extends ApiOp = ApiOp> = Op extends ApiOp ? CallOf<E,
|
|
|
36
36
|
/** What a middleware hands on to: the next middleware, the querier last. */
|
|
37
37
|
export type ApiNext<E> = (call: ApiCall<E>) => Promise<unknown>;
|
|
38
38
|
/**
|
|
39
|
-
* Runs around each call to one entity: reshape it before `next`, abort by throwing (a
|
|
40
|
-
*
|
|
39
|
+
* Runs around each call to one entity: reshape it before `next`, abort by throwing (a `UqlRequestError` answers its
|
|
40
|
+
* status), or reshape what `next` resolves to, the result as the entity holds it. `context` is the transport's.
|
|
41
41
|
*/
|
|
42
42
|
export type EntityMiddleware<E, Ctx = unknown> = (call: ApiCall<E>, context: Ctx, next: ApiNext<E>) => Promise<unknown>;
|
|
43
43
|
/** A middleware run around a call to any entity, for what reads no entity's members: logging, timing, a refusal. */
|
package/dist/http/exposure.d.ts
CHANGED
|
@@ -1,54 +1,38 @@
|
|
|
1
|
-
import type { AbstractType,
|
|
1
|
+
import type { AbstractType, EntityMeta, Type } from '../type/index.js';
|
|
2
2
|
import { type EntityMiddleware } from './apiCall.js';
|
|
3
3
|
import { type ApiOp } from './wireCall.js';
|
|
4
|
-
/**
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
export type Exposure<E, F extends keyof E = FieldKey<E> | RelationKey<E>> = {
|
|
9
|
-
readonly ops?: readonly EntityAccess[];
|
|
10
|
-
readonly members?: {
|
|
11
|
-
readonly [K in F]?: false | readonly FieldAccess[];
|
|
12
|
-
};
|
|
4
|
+
/** How an API serves an entity beyond what its definition's `wire` states: middleware of its own. */
|
|
5
|
+
export type ServeOptions<E, Ctx = unknown> = {
|
|
6
|
+
readonly use: readonly EntityMiddleware<E, Ctx>[];
|
|
13
7
|
};
|
|
14
|
-
/** An entity an API serves
|
|
8
|
+
/** An entity an API serves with {@link ServeOptions}, as `include` lists it beside an entity served as it is. */
|
|
15
9
|
export type Served<E, Ctx = unknown> = {
|
|
16
10
|
readonly entity: Type<E>;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
readonly around?: EntityMiddleware<object, Ctx>;
|
|
11
|
+
/** Its middleware, run on its own calls alone, after the API's. */
|
|
12
|
+
readonly around: EntityMiddleware<object, Ctx>;
|
|
20
13
|
};
|
|
21
14
|
/**
|
|
22
|
-
* Serve `entity`
|
|
23
|
-
*
|
|
15
|
+
* Serve `entity` in an API's `include` with middleware of its own in `use`: typed by the entity, so it reads and
|
|
16
|
+
* writes its members, and run on the entity's own calls alone.
|
|
24
17
|
*/
|
|
25
|
-
export declare function serve<E extends object, Ctx = unknown>(entity: Type<E>, { use
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
/** An
|
|
29
|
-
|
|
30
|
-
readonly ops: ReadonlySet<EntityAccess>;
|
|
31
|
-
readonly members: ReadonlyMap<string, ReadonlySet<FieldAccess>>;
|
|
32
|
-
};
|
|
33
|
-
export type Exposures = ReadonlyMap<AbstractType<object>, Policy>;
|
|
34
|
-
/** The entity an `include` item serves. */
|
|
35
|
-
export declare function entityOf<Ctx>(item: Type<object> | Served<object, Ctx>): Type<object>;
|
|
36
|
-
/** Each entity `include` lists, by its class, with what it takes. */
|
|
37
|
-
export declare function exposuresOf<Ctx>(include: readonly (Type<object> | Served<object, Ctx>)[]): Exposures;
|
|
18
|
+
export declare function serve<E extends object, Ctx = unknown>(entity: Type<E>, { use }: ServeOptions<E, Ctx>): Served<E, Ctx>;
|
|
19
|
+
/** The entities an API serves, each to its middleware. */
|
|
20
|
+
export type ServedEntities = ReadonlyMap<AbstractType<object>, unknown>;
|
|
21
|
+
/** An `include` item as the entity it serves and that entity's middleware. */
|
|
22
|
+
export declare function servedEntry<Ctx>(item: Type<object> | Served<object, Ctx>): [Type<object>, EntityMiddleware<object, Ctx> | undefined];
|
|
38
23
|
/**
|
|
39
24
|
* Refuses what a client's call reaches that the API does not expose: the op on its entity, a relation to an entity
|
|
40
25
|
* it does not serve, and a member at any depth of the query (read) or the rows it writes. Every `$` clause holds
|
|
41
26
|
* keys of the entity it sits on.
|
|
42
27
|
*/
|
|
43
|
-
export declare function assertExposed<E extends object>(meta: EntityMeta<E>, op: ApiOp, query: object, payload: unknown,
|
|
28
|
+
export declare function assertExposed<E extends object>(meta: EntityMeta<E>, op: ApiOp, query: object, payload: unknown, served: ServedEntities): void;
|
|
44
29
|
/**
|
|
45
|
-
* `query` reading
|
|
46
|
-
* {@link assertExposed} took, which names none of
|
|
30
|
+
* `query` reading no field whose `wire` keeps it from being read, at every depth its `$populate` reaches. Run on a
|
|
31
|
+
* call {@link assertExposed} took, which names none of them: a projection naming the fields it reads stays as it is.
|
|
47
32
|
*/
|
|
48
|
-
export declare function hideUnreadable<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, query: Q
|
|
33
|
+
export declare function hideUnreadable<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, query: Q): Q;
|
|
49
34
|
/**
|
|
50
35
|
* The query a client's call runs with: refused where it reaches what the API does not expose, and, on a read
|
|
51
36
|
* answering rows, leaving out what it may not read.
|
|
52
37
|
*/
|
|
53
|
-
export declare function exposedQuery<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, op: ApiOp, query: Q, payload: unknown,
|
|
54
|
-
export {};
|
|
38
|
+
export declare function exposedQuery<E extends object, Q extends Readonly<Record<string, unknown>>>(meta: EntityMeta<E>, op: ApiOp, query: Q, payload: unknown, served: ServedEntities): Q;
|
package/dist/http/exposure.js
CHANGED
|
@@ -1,37 +1,23 @@
|
|
|
1
1
|
import { getMeta } from '../entity/metadata/definition.js';
|
|
2
2
|
import { isCascadable } from '../util/dialect.util.js';
|
|
3
|
-
import { isFieldKey } from '../util/field.util.js';
|
|
3
|
+
import { fieldKeys, isFieldKey, isWrittenOn } from '../util/field.util.js';
|
|
4
4
|
import { isPlainObject, isRecord } from '../util/object.util.js';
|
|
5
5
|
import { UqlSecurityError } from '../util/uqlError.js';
|
|
6
6
|
import { chain, isCallOf } from './apiCall.js';
|
|
7
7
|
import { API_OPS } from './wireCall.js';
|
|
8
8
|
/**
|
|
9
|
-
* Serve `entity`
|
|
10
|
-
*
|
|
9
|
+
* Serve `entity` in an API's `include` with middleware of its own in `use`: typed by the entity, so it reads and
|
|
10
|
+
* writes its members, and run on the entity's own calls alone.
|
|
11
11
|
*/
|
|
12
|
-
export function serve(entity, { use
|
|
13
|
-
if (!use.length) {
|
|
14
|
-
return { entity, exposure };
|
|
15
|
-
}
|
|
12
|
+
export function serve(entity, { use }) {
|
|
16
13
|
return {
|
|
17
14
|
entity,
|
|
18
|
-
exposure,
|
|
19
15
|
around: (call, context, next) => (isCallOf(entity, call) ? chain(use, context, next)(call) : next(call)),
|
|
20
16
|
};
|
|
21
17
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
return typeof item === 'function' ? item : item.entity;
|
|
26
|
-
}
|
|
27
|
-
/** Each entity `include` lists, by its class, with what it takes. */
|
|
28
|
-
export function exposuresOf(include) {
|
|
29
|
-
return new Map(include.map((item) => {
|
|
30
|
-
const entity = entityOf(item);
|
|
31
|
-
const exposure = typeof item === 'function' ? {} : item.exposure;
|
|
32
|
-
const members = Object.entries(exposure.members ?? {}).map(([key, takes]) => [key, new Set(takes || [])]);
|
|
33
|
-
return [entity, { ops: exposure.ops ? new Set(exposure.ops) : EVERY_OP, members: new Map(members) }];
|
|
34
|
-
}));
|
|
18
|
+
/** An `include` item as the entity it serves and that entity's middleware. */
|
|
19
|
+
export function servedEntry(item) {
|
|
20
|
+
return typeof item === 'function' ? [item, undefined] : [item.entity, item.around];
|
|
35
21
|
}
|
|
36
22
|
const PAST = {
|
|
37
23
|
read: 'read',
|
|
@@ -56,20 +42,15 @@ function relationAt(meta, key) {
|
|
|
56
42
|
* it does not serve, and a member at any depth of the query (read) or the rows it writes. Every `$` clause holds
|
|
57
43
|
* keys of the entity it sits on.
|
|
58
44
|
*/
|
|
59
|
-
export function assertExposed(meta, op, query, payload,
|
|
45
|
+
export function assertExposed(meta, op, query, payload, served) {
|
|
60
46
|
const { access } = API_OPS[op];
|
|
61
47
|
const writes = writesOf(op);
|
|
62
|
-
assertOps(meta, access === 'save' ? writes : [access],
|
|
63
|
-
walk(meta, query, ['read'],
|
|
64
|
-
walk(meta, payload, writes,
|
|
65
|
-
}
|
|
66
|
-
/** An entity the API does not serve takes nothing. */
|
|
67
|
-
const DENIED = { ops: new Set(), members: new Map() };
|
|
68
|
-
function policyOf(meta, exposures) {
|
|
69
|
-
return exposures.get(meta.entity) ?? DENIED;
|
|
48
|
+
assertOps(meta, access === 'save' ? writes : [access], served);
|
|
49
|
+
walk(meta, query, ['read'], served, ['query']);
|
|
50
|
+
walk(meta, payload, writes, served, ['payload']);
|
|
70
51
|
}
|
|
71
|
-
function assertOps(meta, needs,
|
|
72
|
-
const missing = needs.find((need) => !
|
|
52
|
+
function assertOps(meta, needs, served, path) {
|
|
53
|
+
const missing = needs.find((need) => !served.has(meta.entity) || !takes(meta.wire, need));
|
|
73
54
|
if (missing) {
|
|
74
55
|
throw new UqlSecurityError(`'${meta.entity.name}' cannot be ${PAST[missing]} through this API`, { path });
|
|
75
56
|
}
|
|
@@ -81,79 +62,84 @@ function membersOf(path) {
|
|
|
81
62
|
.filter((key) => typeof key === 'string' && !key.startsWith('$'))
|
|
82
63
|
.join('.');
|
|
83
64
|
}
|
|
84
|
-
function walk(meta, sent, needs,
|
|
65
|
+
function walk(meta, sent, needs, served, path) {
|
|
85
66
|
if (Array.isArray(sent)) {
|
|
86
|
-
sent.forEach((item, index) => walk(meta, item, needs,
|
|
67
|
+
sent.forEach((item, index) => walk(meta, item, needs, served, [...path, index]));
|
|
87
68
|
return;
|
|
88
69
|
}
|
|
89
70
|
if (!isRecord(sent)) {
|
|
90
71
|
return;
|
|
91
72
|
}
|
|
92
|
-
const { members } = policyOf(meta, exposures);
|
|
93
73
|
const writing = !needs.includes('read');
|
|
94
74
|
for (const [key, value] of Object.entries(sent)) {
|
|
95
75
|
if (key.startsWith('$')) {
|
|
96
|
-
walk(meta, value, needs,
|
|
76
|
+
walk(meta, value, needs, served, [...path, key]);
|
|
97
77
|
continue;
|
|
98
78
|
}
|
|
99
79
|
// A JSON path (`kind.plan`) reads the member it starts at.
|
|
100
80
|
const [member] = key.split('.');
|
|
101
81
|
const relation = relationAt(meta, member);
|
|
102
|
-
|
|
82
|
+
const field = !relation && isFieldKey(meta, member) ? meta.fields[member] : undefined;
|
|
83
|
+
const declared = relation ?? field;
|
|
84
|
+
if (!declared) {
|
|
103
85
|
continue;
|
|
104
86
|
}
|
|
105
87
|
const at = [...path, key];
|
|
106
|
-
const
|
|
107
|
-
const missing = takes && needs.find((need) => !takes.has(need));
|
|
88
|
+
const missing = needs.find((need) => !takes(declared.wire, need)) ?? (field && dropped(field, needs));
|
|
108
89
|
if (missing) {
|
|
109
90
|
throw new UqlSecurityError(`'${membersOf(at)}' cannot be ${PAST[missing]} through this API`, { path: at });
|
|
110
91
|
}
|
|
111
92
|
// The querier writes a relation a payload names only where it cascades, saving its rows whatever the op.
|
|
112
93
|
if (relation && (!writing || isCascadable('persist', relation.cascade))) {
|
|
113
94
|
const target = getMeta(relation.entity());
|
|
114
|
-
if (!
|
|
95
|
+
if (!served.has(target.entity)) {
|
|
115
96
|
throw new UqlSecurityError(`'${membersOf(at)}' reaches '${target.entity.name}', which this API does not serve`, { path: at });
|
|
116
97
|
}
|
|
117
98
|
const nested = writing ? SAVED : needs;
|
|
118
99
|
// An update of a to-many replaces its rows: those it stops listing are deleted.
|
|
119
100
|
const replaces = relation.cardinality === '1m' && needs.includes('update');
|
|
120
|
-
assertOps(target, replaces ? [...nested, 'delete'] : nested,
|
|
121
|
-
walk(target, value, nested,
|
|
101
|
+
assertOps(target, replaces ? [...nested, 'delete'] : nested, served, at);
|
|
102
|
+
walk(target, value, nested, served, at);
|
|
122
103
|
}
|
|
123
104
|
}
|
|
124
105
|
}
|
|
125
|
-
/**
|
|
126
|
-
function
|
|
127
|
-
|
|
128
|
-
|
|
106
|
+
/** Whether a `wire` lets a client do `need`: everything where it states none. */
|
|
107
|
+
function takes(wire, need) {
|
|
108
|
+
return wire === undefined || (wire !== false && wire.includes(need));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* What a write is refused for where the querier would write `field` on none of `needs`, rather than drop it unseen: a
|
|
112
|
+
* computed value, or an `updatable(false)` one in an update. A save or a cascade may insert, which writes the latter.
|
|
113
|
+
*/
|
|
114
|
+
function dropped(field, needs) {
|
|
115
|
+
const writes = (need) => need === 'read' || isWrittenOn(field, need === 'insert' ? 'onInsert' : 'onUpdate');
|
|
116
|
+
return needs.some(writes) ? undefined : needs[0];
|
|
129
117
|
}
|
|
130
118
|
/**
|
|
131
|
-
* `query` reading
|
|
132
|
-
* {@link assertExposed} took, which names none of
|
|
119
|
+
* `query` reading no field whose `wire` keeps it from being read, at every depth its `$populate` reaches. Run on a
|
|
120
|
+
* call {@link assertExposed} took, which names none of them: a projection naming the fields it reads stays as it is.
|
|
133
121
|
*/
|
|
134
|
-
export function hideUnreadable(meta, query
|
|
135
|
-
const hidden =
|
|
122
|
+
export function hideUnreadable(meta, query) {
|
|
123
|
+
const hidden = fieldKeys(meta, (field) => !takes(field.wire, 'read'));
|
|
136
124
|
const select = query['$select'];
|
|
137
125
|
const leavesOut = select === undefined || (isPlainObject(select) && Object.values(select).every((value) => !value));
|
|
138
126
|
const $select = hidden.length && leavesOut
|
|
139
127
|
? { ...(isPlainObject(select) && select), ...Object.fromEntries(hidden.map((key) => [key, false])) }
|
|
140
128
|
: select;
|
|
141
|
-
const $populate = isPlainObject(query['$populate'])
|
|
142
|
-
? populateOf(meta, query['$populate'], exposures)
|
|
143
|
-
: query['$populate'];
|
|
129
|
+
const $populate = isPlainObject(query['$populate']) ? populateOf(meta, query['$populate']) : query['$populate'];
|
|
144
130
|
if ($select === select && $populate === query['$populate']) {
|
|
145
131
|
return query;
|
|
146
132
|
}
|
|
147
133
|
return { ...query, ...($select !== undefined && { $select }), ...($populate !== undefined && { $populate }) };
|
|
148
134
|
}
|
|
149
|
-
function populateOf(meta, populate
|
|
135
|
+
function populateOf(meta, populate) {
|
|
150
136
|
let changed = false;
|
|
151
137
|
const entries = Object.entries(populate).map(([key, nested]) => {
|
|
152
138
|
const relation = relationAt(meta, key);
|
|
153
139
|
if (!relation || !nested) {
|
|
154
140
|
return [key, nested];
|
|
155
141
|
}
|
|
156
|
-
const read = hideUnreadable(getMeta(relation.entity()), isPlainObject(nested) ? nested : {}
|
|
142
|
+
const read = hideUnreadable(getMeta(relation.entity()), isPlainObject(nested) ? nested : {});
|
|
157
143
|
const hid = isPlainObject(nested) ? read !== nested : Object.keys(read).length > 0;
|
|
158
144
|
changed ||= hid;
|
|
159
145
|
return [key, hid ? read : nested];
|
|
@@ -164,8 +150,8 @@ function populateOf(meta, populate, exposures) {
|
|
|
164
150
|
* The query a client's call runs with: refused where it reaches what the API does not expose, and, on a read
|
|
165
151
|
* answering rows, leaving out what it may not read.
|
|
166
152
|
*/
|
|
167
|
-
export function exposedQuery(meta, op, query, payload,
|
|
168
|
-
assertExposed(meta, op, query, payload,
|
|
153
|
+
export function exposedQuery(meta, op, query, payload, served) {
|
|
154
|
+
assertExposed(meta, op, query, payload, served);
|
|
169
155
|
const { access, answers } = API_OPS[op];
|
|
170
|
-
return access === 'read' && answers !== 'count' ? hideUnreadable(meta, query
|
|
156
|
+
return access === 'read' && answers !== 'count' ? hideUnreadable(meta, query) : query;
|
|
171
157
|
}
|
package/dist/http/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export * from './api.js';
|
|
|
2
2
|
export type { ApiCall, ApiMiddleware, ApiNext, EntityMiddleware } from './apiCall.js';
|
|
3
3
|
export { API_OPS, type ApiOp, entityPath, type EntityPathOptions, parseWireCall, type WireAnswer, type WireCall, } from './wireCall.js';
|
|
4
4
|
export { type HandlerResponse, type RequestErrorResponse, type RequestFailure, toErrorResponse } from './errors.js';
|
|
5
|
-
export { type
|
|
5
|
+
export { type Served, type ServeOptions, serve } from './exposure.js';
|
|
6
6
|
export type { WireCursors } from './wireQuery.js';
|
|
7
7
|
export { decodeRequest, encodeCall, type HttpCall, type HttpRequest, type ReadMethod } from './route.js';
|
|
8
8
|
export { type HandlerRequest, type RequestHandler, toFetchHandler, toRequestHandler } from './handler.js';
|
|
@@ -238,8 +238,8 @@ function formatTypeDescription(type) {
|
|
|
238
238
|
}
|
|
239
239
|
/**
|
|
240
240
|
* A column's property as source, declared the way every read and insert types it: present (`!`) where
|
|
241
|
-
* the column is NOT NULL, left out of an insert (`?`) where a default fills it
|
|
242
|
-
*
|
|
241
|
+
* the column is NOT NULL, left out of an insert (`?`) where a default or an auto-increment fills it, a key
|
|
242
|
+
* included, `| null` where it holds NULL, `readonly` where the database computes it.
|
|
243
243
|
*/
|
|
244
244
|
function propertySource(col, propertyName) {
|
|
245
245
|
const type = col.type.category === 'json' ? 'Json' : canonicalToTypeScript(col.type);
|
package/dist/type/column.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ForeignKeyAction } from '../schema/types.js';
|
|
2
2
|
import type { TYPE_BOUNDS, VALUE_DECIDERS } from '../util/fieldOption.util.js';
|
|
3
3
|
import type { ColumnType, DdlDefault, FamilyOf, FieldOptions, HasCompositeKey, IdValue, JsonColumnType, OnFieldCallback, StampEvent, TsTypeOf } from './entity.js';
|
|
4
|
+
import type { Wire } from './query.js';
|
|
4
5
|
import type { QuerySql } from './querySql.js';
|
|
5
6
|
import type { StandardSchemaV1 } from './standardSchema.js';
|
|
6
7
|
import type { Type, Json, JsonDocument, JsonScalar, AbstractType } from './utility.js';
|
|
@@ -111,13 +112,15 @@ export interface ColumnBuilder<in out O, in out V, F extends Family> extends Col
|
|
|
111
112
|
comment(text: string): With<O, V, {
|
|
112
113
|
readonly comment: string;
|
|
113
114
|
}, F>;
|
|
114
|
-
/**
|
|
115
|
-
* Leaves the column out of a read naming no fields. A read naming it still gets it, so it keeps no secret from a
|
|
116
|
-
* client: an API's `serve(Entity, { members: { field: false } })` does.
|
|
117
|
-
*/
|
|
115
|
+
/** Leaves the column out of a read naming no fields. A read naming it still gets it, so it keeps no secret: `wire(false)` does. */
|
|
118
116
|
eager(eager: false): With<O, V, {
|
|
119
117
|
readonly eager: false;
|
|
120
118
|
}, F>;
|
|
119
|
+
/**
|
|
120
|
+
* What a client may do to it over an API that serves its entity (none does by default): `false` hides it,
|
|
121
|
+
* `['read']` makes it read-only, and unset it takes everything.
|
|
122
|
+
*/
|
|
123
|
+
wire(wire: Wire): With<O, V, unknown, F>;
|
|
121
124
|
/** The SQL type where it differs from the one the builder implies; an engine's own, `sql`citext``, verbatim. */
|
|
122
125
|
columnType(type: ColumnType): With<O, V, {
|
|
123
126
|
readonly columnType: ColumnType;
|
|
@@ -188,6 +191,8 @@ export interface ComputedColumn<in out O, in out V> extends Column<O, V> {
|
|
|
188
191
|
stored(events?: readonly StampEvent[]): ComputedColumn<O & {
|
|
189
192
|
readonly stored: unknown;
|
|
190
193
|
}, V>;
|
|
194
|
+
/** Whether a client may read it over an API: `false` hides it. */
|
|
195
|
+
wire(wire: false | readonly ['read']): ComputedColumn<O, V>;
|
|
191
196
|
}
|
|
192
197
|
/** The version column, an optimistic lock: an update matches the version it read and writes the next. */
|
|
193
198
|
export interface VersionColumn<in out O, in out V> extends Column<O, V> {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Column, ColumnOptionsOf, ColumnValueOf, FilledOptions, NullOf } from './column.js';
|
|
2
2
|
import type { BrandNames, CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, KeyHolding, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
|
|
3
|
+
import type { EntityAccess, Wire } from './query.js';
|
|
3
4
|
import type { QuerySql, RelationAggregate } from './querySql.js';
|
|
4
5
|
import type { Type, AbstractType } from './utility.js';
|
|
5
6
|
/**
|
|
@@ -142,6 +143,8 @@ export type DefineEntityOptions<F extends DefinedFields, B = object, BK = unknow
|
|
|
142
143
|
readonly schema?: string;
|
|
143
144
|
/** A base that is never a table: the entities extending it take what it declares. */
|
|
144
145
|
readonly abstract?: true;
|
|
146
|
+
/** What a client may do over an API: see {@link Wire}. */
|
|
147
|
+
readonly wire?: Wire<EntityAccess>;
|
|
145
148
|
/** The entity it inherits from, which the declared class extends, so its methods and `super` work. */
|
|
146
149
|
readonly extends?: DefinedClass<B, BK, BC, boolean>;
|
|
147
150
|
readonly fields: F;
|
package/dist/type/entity.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { EnumValues, ForeignKeyAction, IndexType } from '../schema/types.js';
|
|
2
2
|
import type { SqlDialectName } from './dialect.js';
|
|
3
3
|
import type { Querier } from './querier.js';
|
|
4
|
-
import type { FilterOptions, RelationQuery } from './query.js';
|
|
4
|
+
import type { EntityAccess, FilterOptions, RelationQuery, Wire } from './query.js';
|
|
5
5
|
import type { ColumnRef, JsonPathRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
|
|
6
6
|
import type { QueryWhere } from './queryWhere.js';
|
|
7
7
|
import type { StandardSchemaV1 } from './standardSchema.js';
|
|
@@ -312,6 +312,8 @@ export type FieldOptions<V = unknown> = {
|
|
|
312
312
|
readonly stored?: boolean | readonly StampEvent[];
|
|
313
313
|
readonly updatable?: boolean;
|
|
314
314
|
readonly eager?: boolean;
|
|
315
|
+
/** What a client may do over an API: see {@link Wire}. */
|
|
316
|
+
readonly wire?: Wire;
|
|
315
317
|
readonly onInsert?: OnFieldCallback<V>;
|
|
316
318
|
readonly onUpdate?: OnFieldCallback<V>;
|
|
317
319
|
/**
|
|
@@ -394,10 +396,14 @@ export type RelationOptions<E, O = unknown> = RelationCascade & RelationActions
|
|
|
394
396
|
*/
|
|
395
397
|
references?: (local: KeyMap<O>, foreign: KeyMap<E>) => ForeignKey<O, E> | readonly RelationReference<O, E>[];
|
|
396
398
|
};
|
|
397
|
-
/**
|
|
398
|
-
type RelationCascade = {
|
|
399
|
+
/** What every relation takes: whether writes reach the related rows in the same transaction, and its `wire`; its own type, so an option set takes it without instantiating `RelationOptions`. */
|
|
400
|
+
type RelationCascade = RelationWire & {
|
|
399
401
|
readonly cascade?: boolean | CascadeType;
|
|
400
402
|
};
|
|
403
|
+
/** What a client may do over an API: see {@link Wire}. */
|
|
404
|
+
type RelationWire = {
|
|
405
|
+
readonly wire?: Wire;
|
|
406
|
+
};
|
|
401
407
|
/** The foreign key's actions, read on the owning side; unset, the column's own `onDelete` applies. */
|
|
402
408
|
type RelationActions = {
|
|
403
409
|
readonly onDelete?: ForeignKeyAction;
|
|
@@ -456,7 +462,7 @@ type DecoratedJoins<E, O> = {
|
|
|
456
462
|
* The side holding the foreign key, which the actions attach to. It cascades `'persist'` only: its target may
|
|
457
463
|
* be other rows' too, so a delete cascades from the side owning the rows.
|
|
458
464
|
*/
|
|
459
|
-
type RelationOwnerSide = RelationActions & {
|
|
465
|
+
type RelationOwnerSide = RelationActions & RelationWire & {
|
|
460
466
|
readonly cascade?: 'persist';
|
|
461
467
|
readonly mappedBy?: never;
|
|
462
468
|
readonly through?: never;
|
|
@@ -756,6 +762,8 @@ export type EntityMeta<E> = {
|
|
|
756
762
|
version?: FieldKey<E>;
|
|
757
763
|
/** Named, default-on `$where` filters applied to every query unless bypassed. */
|
|
758
764
|
filters?: Record<string, FilterOptions<E>>;
|
|
765
|
+
/** What a client may do over an API, see {@link Wire}; a subclass declaring none takes its base's. */
|
|
766
|
+
wire?: Wire<EntityAccess>;
|
|
759
767
|
fields: {
|
|
760
768
|
[K in FieldKey<E>]?: FieldMeta;
|
|
761
769
|
} & {
|
|
@@ -924,6 +932,8 @@ export type EntityOptions<E = unknown> = {
|
|
|
924
932
|
readonly abstract?: true;
|
|
925
933
|
/** The schema (a MySQL database) the table lives in; unset follows the pool's. */
|
|
926
934
|
readonly schema?: string;
|
|
935
|
+
/** What a client may do over an API: see {@link Wire}. */
|
|
936
|
+
readonly wire?: Wire<EntityAccess>;
|
|
927
937
|
readonly filters?: FilterSection<E>;
|
|
928
938
|
readonly indexes?: IndexSection<E>;
|
|
929
939
|
/** Table-level `CHECK` constraints. See {@link CheckOptions}. */
|
package/dist/type/query.d.ts
CHANGED
|
@@ -114,6 +114,12 @@ export type FilterOnMissing = 'skip' | 'throw';
|
|
|
114
114
|
export type FieldAccess = 'read' | 'insert' | 'update';
|
|
115
115
|
/** What a statement does to an entity's rows: a field's access, and deleting rows, which no field has a part in. */
|
|
116
116
|
export type EntityAccess = FieldAccess | 'delete';
|
|
117
|
+
/**
|
|
118
|
+
* What a client may do to an entity, or one of its members, over an API: what it lists, nothing for `false`, and
|
|
119
|
+
* everything where unset. Nothing is served by default: an entity reaches the wire only when an API's `include`
|
|
120
|
+
* names it, and `wire` narrows it from there.
|
|
121
|
+
*/
|
|
122
|
+
export type Wire<A extends EntityAccess = FieldAccess> = false | readonly A[];
|
|
117
123
|
/**
|
|
118
124
|
* Authoring shape for `@Entity({ filters })` and `defineEntity`'s `.filters()`.
|
|
119
125
|
*/
|
|
@@ -87,8 +87,7 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
|
|
|
87
87
|
insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted']>;
|
|
88
88
|
/**
|
|
89
89
|
* Insert records in as few statements as the bind limit allows, resolving to their ids in payload order, or
|
|
90
|
-
* the rows `returning` reads back.
|
|
91
|
-
* reports `undefined` rather than a guess for a generated key that is not `AUTO_INCREMENT`.
|
|
90
|
+
* the rows `returning` reads back.
|
|
92
91
|
*/
|
|
93
92
|
insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted'][]>;
|
|
94
93
|
/** Update the record with the given primary key; resolves to the number of affected rows, or the row `returning` reads back. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { IndexType } from '../schema/types.js';
|
|
2
2
|
import { type AggregateCall, type CascadeType, type EntityAccess, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type StatementOptions, type UpdatePayload, type VectorDistance } from '../type/index.js';
|
|
3
|
-
|
|
3
|
+
import { type CallbackKey } from './field.util.js';
|
|
4
4
|
/** The keys of `payload` a write persists as columns. */
|
|
5
5
|
export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
|
|
6
6
|
/**
|
|
@@ -2,7 +2,7 @@ import { getContext } from '../context/context.js';
|
|
|
2
2
|
import { namesKey } from '../entity/metadata/definition.js';
|
|
3
3
|
import { QuerySql, resolveAggregateOp, } from '../type/index.js';
|
|
4
4
|
import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
|
|
5
|
-
import { defaultReadKeys, fieldKeys, isDatabaseWritten, jsonKey, jsonPathKeys } from './field.util.js';
|
|
5
|
+
import { defaultReadKeys, fieldKeys, isDatabaseWritten, isWrittenOn, jsonKey, jsonPathKeys, } from './field.util.js';
|
|
6
6
|
import { withDeleted } from './filters.util.js';
|
|
7
7
|
import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isPlainObject, isRecord, someKey, } from './object.util.js';
|
|
8
8
|
import { assertNoUndefined, whereAnd } from './query.util.js';
|
|
@@ -11,7 +11,7 @@ import { UqlSecurityError, UqlUsageError } from './uqlError.js';
|
|
|
11
11
|
export function filterFieldKeys(meta, payload, callbackKey) {
|
|
12
12
|
return getKeys(payload).filter((key) => {
|
|
13
13
|
const fieldOpts = meta.fields[key];
|
|
14
|
-
return fieldOpts &&
|
|
14
|
+
return fieldOpts && isWrittenOn(fieldOpts, callbackKey);
|
|
15
15
|
});
|
|
16
16
|
}
|
|
17
17
|
/** Whether `key` is a field the caller writes, and `record` provides a defined value for. */
|
|
@@ -38,6 +38,9 @@ export declare function aggregateField(aggregate: RelationAggregate): FieldOptio
|
|
|
38
38
|
* computed column *is* a real column, read like one, but writing to it is an error on every engine.
|
|
39
39
|
*/
|
|
40
40
|
export declare function isDatabaseWritten(field: FieldOptions): boolean;
|
|
41
|
+
export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
|
|
42
|
+
/** Whether a write by `callbackKey` persists `field`: never one the database writes, nor an `updatable(false)` one on update. */
|
|
43
|
+
export declare function isWrittenOn(field: FieldOptions, callbackKey: CallbackKey): boolean;
|
|
41
44
|
/** The column family of a field, from its `columnType` if set, else from its `type`. */
|
|
42
45
|
export declare function fieldFamily(field: FieldOptions): ColumnFamily | undefined;
|
|
43
46
|
/** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
|
package/dist/util/field.util.js
CHANGED
|
@@ -83,6 +83,10 @@ export function aggregateField(aggregate) {
|
|
|
83
83
|
export function isDatabaseWritten(field) {
|
|
84
84
|
return field.computed !== undefined;
|
|
85
85
|
}
|
|
86
|
+
/** Whether a write by `callbackKey` persists `field`: never one the database writes, nor an `updatable(false)` one on update. */
|
|
87
|
+
export function isWrittenOn(field, callbackKey) {
|
|
88
|
+
return !isDatabaseWritten(field) && (callbackKey !== 'onUpdate' || field.updatable !== false);
|
|
89
|
+
}
|
|
86
90
|
/** The column family of a field, from its `columnType` if set, else from its `type`. */
|
|
87
91
|
export function fieldFamily(field) {
|
|
88
92
|
return columnFamily(field.columnType ?? field.type);
|
|
@@ -21,6 +21,7 @@ const FIELD_OPTION_FAMILY = {
|
|
|
21
21
|
stored: '*',
|
|
22
22
|
updatable: '*',
|
|
23
23
|
eager: '*',
|
|
24
|
+
wire: '*',
|
|
24
25
|
onInsert: '*',
|
|
25
26
|
onUpdate: '*',
|
|
26
27
|
softDelete: '*',
|
|
@@ -49,6 +50,7 @@ const INLINE_READS = [
|
|
|
49
50
|
'stored',
|
|
50
51
|
'enum',
|
|
51
52
|
'eager',
|
|
53
|
+
'wire',
|
|
52
54
|
'distance',
|
|
53
55
|
'nullable',
|
|
54
56
|
];
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"homepage": "https://uql-orm.dev",
|
|
4
4
|
"description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.114.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -5,7 +5,8 @@ description: >
|
|
|
5
5
|
on PostgreSQL, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, MongoDB, Turso, Neon, D1 and PGlite.
|
|
6
6
|
Use when a project imports uql-orm, or when defining entities (@Entity, defineEntity), triggers or filters
|
|
7
7
|
(soft delete, multi-tenancy), querying ($where, $populate, findMany, aggregate), writing (insertMany, upsertOne,
|
|
8
|
-
updateMany, returning), transactions, raw SQL (sql, refs)
|
|
8
|
+
updateMany, returning), transactions, raw SQL (sql, refs), migrations (uql-migrate), or serving queries to a client
|
|
9
|
+
(createApi, serve, createClientQuerier, createQueryOptions) with it. UQL is not Prisma,
|
|
9
10
|
Drizzle, TypeORM or MikroORM: their APIs do not carry over.
|
|
10
11
|
---
|
|
11
12
|
|
|
@@ -91,8 +92,6 @@ export class Post {
|
|
|
91
92
|
- A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `insertOne`, `insertMany`, `saveOne` and `saveMany` resolve to a defined key, so no `!`; an upsert's may be `undefined`. On SQL engines an insert leaving out a key nothing declared fills throws before writing. `defineEntity` works all of this out.
|
|
92
93
|
- `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
|
|
93
94
|
- `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
|
|
94
|
-
- Serve entities to a client with `createApi({ pool, include, contextOf, use })` from `uql-orm/http`, mounted under a versioned base as `toFetchHandler(api)` on a catch-all, `app.use('/api/v1', toExpress(api))` (`uql-orm/express`) or `toRequestHandler(api)`; the wire is `{base}/:entity/:op` (`GET ?q=` or a JSON `POST` for reads, a JSON `POST` for writes) and a failure answers `{ error: { message, status, kind, path } }`, or called inside a tRPC or oRPC procedure as `api.call(input, ctx.req)`, which checks the call itself. `include` is required and fences relations too; `serve(User, { ops: ['read', 'update'], members: { passwordHash: false, role: ['read'], password: ['insert'] }, use: [...] })` narrows one, where a member's `read` covers select, filter, sort and aggregate and an unlisted member keeps every op. A middleware is `(call, context, next) => next(call)`: the API's `use` runs on every call, a `serve`'s on its entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). `.eager(false)` only leaves a field out of a read naming no fields, so a client's `$select` still reads it: hide a secret (`password`, a token) with `members: { password: false }`. Scope tenants with a `security` filter and `contextOf`, never a middleware; without `contextOf` a call keeps its caller's context.
|
|
95
|
-
- The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport; it answers what the pool answers (rows, not `{ data }`) and reads rows back by the entity it is handed, which must be registered (importing its class does it): a `Date` field is a `Date` and a `bigint` exact, so its rows are not plain JSON and a cache persisting them needs a serializer. For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.
|
|
96
95
|
- A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
|
|
97
96
|
- A relation decorator takes its target first, then its options, as `rel.*` does. `mappedBy` and `references` may be left out where only one member fits, and then the options too: `@OneToMany(() => Post)`. `@ManyToMany(() => Tag, { through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
|
|
98
97
|
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
|
|
@@ -196,7 +195,7 @@ const users = await pool.findMany(User, {
|
|
|
196
195
|
});
|
|
197
196
|
```
|
|
198
197
|
|
|
199
|
-
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Signatures: https://uql-orm.dev/querying/methods.md
|
|
198
|
+
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `estimatedCount`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Signatures: https://uql-orm.dev/querying/methods.md
|
|
200
199
|
- Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`, `$lock`. `$select: { password: false }` reads every field but `password`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
|
|
201
200
|
- Results are narrowed to what the query selected and populated, at every depth. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing typed `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`.
|
|
202
201
|
- `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
|
|
@@ -267,6 +266,33 @@ await pool.transaction(async (querier) => {
|
|
|
267
266
|
- A transaction opened in one place and ended in another uses `beginTransaction`, `commitTransaction` and `rollbackTransaction`. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
268
267
|
- A `findManyStream` holds its querier until the loop ends, refusing other statements meanwhile: run them after the loop, or on another connection.
|
|
269
268
|
|
|
269
|
+
## Serving to a client
|
|
270
|
+
|
|
271
|
+
A query is JSON, so a browser sends it as it is and the server checks it against what each entity exposes.
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { createApi, toFetchHandler } from 'uql-orm/http';
|
|
275
|
+
|
|
276
|
+
const api = createApi<Request>({
|
|
277
|
+
pool,
|
|
278
|
+
include: [Post, User],
|
|
279
|
+
contextOf: async (req) => ({ tenantId: (await getSession(req))?.tenantId }), // a verified session or JWT
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
export const handler = toFetchHandler(api); // on a catch-all under /api/v1
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
- Nothing is exposed by default: defining an entity serves nothing, and `include` is required, its entities the only ones a call reaches, through a relation too. Mount the API under a versioned base: `toFetchHandler(api)` for any fetch runtime (Hono, Next.js, Bun, Workers), `app.use('/api/v1', toExpress(api))` from `uql-orm/express`, or `toRequestHandler(api)` for any other framework. Inside a tRPC or oRPC procedure call `api.call(input, ctx)`, which checks the call itself; `.input(parseWireCall)` types it.
|
|
286
|
+
- The wire is `{base}/:entity/:op` (`/api/v1/user/findMany`), the entity's kebab-cased class name and a client method: a read is `GET ?q=<call as JSON>` (or a JSON body by `POST` or `QUERY`: `httpTransport(url, { readMethod: 'POST' })`), a write a JSON `POST`. A success answers `{ data }`, a failure `{ error: { message, status, kind, path } }`.
|
|
287
|
+
- What a client may do is the definition's `wire`, every operation where unset. An entity's (`@Entity({ wire: ['read', 'update'] })`, `defineEntity({ wire })`) lists what it takes of `'read'`, `'insert'`, `'update'`, `'delete'`, a subclass declaring none taking its base's; `wire: false` keeps it off every API, and `createApi` refuses one in `include`. A member's: `f.string().wire(false)` hides a field, `.wire(['read'])` makes it read-only, `.wire(['insert'])` write-once; a relation takes `wire` in its options (`rel.oneToMany(Session, { mappedBy, wire: false })`, `@OneToMany(() => Session, { mappedBy, wire: false })`). It holds wherever the entity is reached, through any relation. A write the querier would drop, to a computed field or an update of an `updatable(false)` one, is refused instead; a save may insert, so it takes the latter.
|
|
288
|
+
- `read` covers every clause naming the member (`$select`, `$where`, `$sort`, `$count`, `$populate`), and a read with no `$select` leaves out what it may not read. `.eager(false)` is no guard, since a client's `$select` still reads it: hide a secret with `.wire(false)`.
|
|
289
|
+
- A middleware is `(call, context, next) => next(call)`, run after the call is checked: reshape the call before `next`, or what `next` resolves to after it. The API's `use` runs on every call, and `serve(Entity, { use })` in `include` on that entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). Refuse a client with `throw new UqlRequestError('unauthorized', 401)` from `uql-orm`; any other error answers generically by its kind, or `500`.
|
|
290
|
+
- Scope tenants with a `security` filter and `contextOf`, never with a middleware adding to `$where`. Without `contextOf` a call keeps its caller's context. On NestJS, `UqlModule.forRoot({ pool, contextOf })` does the same for your own routes.
|
|
291
|
+
- The API serves one entity per call: no `aggregate`, upsert, stream or transaction. Write your own routes for those beside it; `toFetchHandler` answers `404` and `toExpress` falls through to `next()` on paths it does not serve.
|
|
292
|
+
- The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport. It has the pool's find, `count`, `exists`, insert, save, update and delete methods and answers what they answer (rows, not `{ data }`), reading each row back by its entity, which must be registered (importing it does): a `Date` field is a `Date` and a `bigint` exact, so a cache persisting rows needs a serializer. `httpTransport` rejects with a `RequestError` carrying `status`, `kind` and `path`.
|
|
293
|
+
- For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.
|
|
294
|
+
- A server bundle that minifies class names must keep them, or pass the same `entityPath` to `createApi` and `createClientQuerier`.
|
|
295
|
+
|
|
270
296
|
## Migrations
|
|
271
297
|
|
|
272
298
|
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|