uql-orm 0.105.0 → 0.106.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/querier/httpQuerier.d.ts +3 -3
- package/dist/browser/type/clientQuerier.d.ts +1 -1
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +6 -6
- package/dist/cockroachdb/cockroachDialect.d.ts +2 -2
- package/dist/dialect/abstractDialect.d.ts +3 -3
- package/dist/dialect/abstractSqlDialect.d.ts +35 -35
- package/dist/dialect/mergeSqlDialect.d.ts +2 -2
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +6 -6
- package/dist/dialect/queryJoins.d.ts +2 -2
- package/dist/entity/columnOptionsBuilder.d.ts +3 -3
- package/dist/entity/columnOptionsBuilder.js +3 -5
- package/dist/entity/decorator/bag.d.ts +2 -2
- package/dist/entity/decorator/entity.d.ts +2 -2
- package/dist/entity/decorator/members.d.ts +1 -1
- package/dist/entity/metadata/definition.d.ts +12 -7
- package/dist/entity/metadata/definition.js +84 -87
- package/dist/entity/metadata/schemaFixture/animal.d.ts +17 -5
- package/dist/entity/metadata/schemaFixture/author.d.ts +12 -12
- package/dist/entity/metadata/schemaFixture/author.js +3 -3
- package/dist/entity/metadata/schemaFixture/book.d.ts +20 -20
- package/dist/entity/metadata/schemaFixture/book.js +2 -1
- package/dist/http/contract.d.ts +2 -2
- package/dist/http/handler.d.ts +2 -2
- package/dist/mariadb/mariaDialect.d.ts +2 -2
- package/dist/migrate/cli.js +13 -13
- package/dist/migrate/codegen/entityTypes.d.ts +2 -2
- package/dist/migrate/migrator.d.ts +2 -2
- package/dist/migrate/schemaGenerator.d.ts +5 -5
- package/dist/mongodb/mongoDialect.d.ts +12 -12
- package/dist/mongodb/mongoSchemaGenerator.d.ts +4 -4
- package/dist/mssql/mssqlDialect.d.ts +4 -4
- package/dist/pglite/pgliteQuerierPool.d.ts +2 -2
- package/dist/postgres/postgresDialect.d.ts +2 -2
- package/dist/querier/abstractSqlQuerier.d.ts +1 -1
- package/dist/schema/schemaASTBuilder.d.ts +4 -4
- package/dist/sqlite/localSqliteQuerierPool.d.ts +3 -2
- package/dist/type/column.d.ts +23 -22
- package/dist/type/config.d.ts +2 -2
- package/dist/type/dialect.d.ts +13 -13
- package/dist/type/entity.d.ts +22 -39
- package/dist/type/index.d.ts +1 -0
- package/dist/type/index.js +1 -0
- package/dist/type/migration.d.ts +7 -7
- package/dist/type/querier.d.ts +2 -2
- package/dist/type/query.d.ts +1 -1
- package/dist/type/querySql.d.ts +2 -2
- package/dist/type/schemaEntity.d.ts +59 -58
- package/dist/type/standardSchema.d.ts +28 -0
- package/dist/type/standardSchema.js +1 -0
- package/dist/type/utility.d.ts +25 -33
- package/dist/util/fieldOption.util.js +1 -1
- package/dist/util/hook.util.d.ts +2 -2
- package/dist/util/sql.d.ts +4 -6
- package/dist/util/sql.js +0 -4
- package/dist/util/triggerWrite.d.ts +5 -5
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +26 -11
package/dist/type/index.js
CHANGED
|
@@ -14,6 +14,7 @@ export * from './querySql.js';
|
|
|
14
14
|
export * from './schemaEntity.js';
|
|
15
15
|
export * from './queryWhere.js';
|
|
16
16
|
export * from './universalQuerier.js';
|
|
17
|
+
export * from './standardSchema.js';
|
|
17
18
|
export * from './utility.js';
|
|
18
19
|
export * from './vector.js';
|
|
19
20
|
export * from './wire.js';
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { AnyMigrationOperation } from '../migrate/builder/types.js';
|
|
|
2
2
|
import type { SchemaAST } from '../schema/schemaAST.js';
|
|
3
3
|
import type { DiffOptions } from '../schema/schemaASTDiffer.js';
|
|
4
4
|
import type { CheckSchema, ColumnNode, ForeignKeyAction, IndexType, TableNode, TriggerSchema } from '../schema/types.js';
|
|
5
|
-
import type { Except, IndexEntry, IndexedVectorField, LoggingOptions, Querier, SqlQuerier,
|
|
5
|
+
import type { Except, IndexEntry, IndexedVectorField, LoggingOptions, Querier, SqlQuerier, AbstractType, VectorIndexOptions } from './index.js';
|
|
6
6
|
/**
|
|
7
7
|
* Defines a migration using a simple object literal. `Q` is `MongoQuerier` for a MongoDB migration.
|
|
8
8
|
*/
|
|
@@ -59,7 +59,7 @@ export interface MigratorOptions {
|
|
|
59
59
|
/**
|
|
60
60
|
* Entities to use for schema generation
|
|
61
61
|
*/
|
|
62
|
-
readonly entities?:
|
|
62
|
+
readonly entities?: AbstractType<object>[];
|
|
63
63
|
/**
|
|
64
64
|
* Default action for foreign key ON DELETE and ON UPDATE clauses.
|
|
65
65
|
*/
|
|
@@ -225,7 +225,7 @@ export interface SyncOptions {
|
|
|
225
225
|
readonly drop?: boolean;
|
|
226
226
|
readonly logging?: boolean;
|
|
227
227
|
/** One entity instead of every registered one, for a schema that grows while the process runs. */
|
|
228
|
-
readonly entity?:
|
|
228
|
+
readonly entity?: AbstractType<object>;
|
|
229
229
|
/** Drop every table and recreate it. Development only: it is the one option that loses data. */
|
|
230
230
|
readonly force?: boolean;
|
|
231
231
|
}
|
|
@@ -250,13 +250,13 @@ export interface DropSchemaOptions {
|
|
|
250
250
|
*/
|
|
251
251
|
export interface SchemaGenerator {
|
|
252
252
|
/** The whole schema for `entities`, tables then the foreign keys between them, which need every entity at once. */
|
|
253
|
-
generateCreateSchema(entities: readonly
|
|
253
|
+
generateCreateSchema(entities: readonly AbstractType<object>[], options?: CreateSchemaOptions): string[];
|
|
254
254
|
/**
|
|
255
255
|
* Every `DROP TABLE` for `entities`, dependents first. The inverse of {@link generateCreateSchema},
|
|
256
256
|
* and the reason it takes the whole set: dropping in any order that ignores the relation graph is
|
|
257
257
|
* rejected once the foreign keys are really there.
|
|
258
258
|
*/
|
|
259
|
-
generateDropSchema(entities: readonly
|
|
259
|
+
generateDropSchema(entities: readonly AbstractType<object>[], options?: DropSchemaOptions): string[];
|
|
260
260
|
/** The statements taking a table through `diff`; its rollback is `rollbackDiff(diff)`. */
|
|
261
261
|
generateAlterTable(diff: SchemaDiff): string[];
|
|
262
262
|
/**
|
|
@@ -269,9 +269,9 @@ export interface SchemaGenerator {
|
|
|
269
269
|
* a foreign key here points at, or those keys read as matching.
|
|
270
270
|
* `renamedColumns` are columns `currentTable` already holds under their new names.
|
|
271
271
|
*/
|
|
272
|
-
diffSchema(entity:
|
|
272
|
+
diffSchema(entity: AbstractType<object>, currentTable: TableNode | undefined, desiredAst?: SchemaAST, renamedColumns?: readonly Rename[]): SchemaDiff | undefined;
|
|
273
273
|
/** The entities as one AST, built once per run for every {@link diffSchema}. Absent on MongoDB, which diffs only indexes and a validator. */
|
|
274
|
-
buildAST?(entities: readonly
|
|
274
|
+
buildAST?(entities: readonly AbstractType<object>[]): SchemaAST;
|
|
275
275
|
/** How this engine's diff compares types and defaults. Absent where {@link buildAST} is. */
|
|
276
276
|
diffOptions?(): DiffOptions;
|
|
277
277
|
}
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { NamingStrategy } from './namingStrategy.js';
|
|
|
6
6
|
import type { Captured, QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult, WriteResults, WriteOptions } from './query.js';
|
|
7
7
|
import type { QuerySql, SqlStatement } from './querySql.js';
|
|
8
8
|
import type { EntityRead, ReadResults, ReadQueries, UniversalQuerier } from './universalQuerier.js';
|
|
9
|
-
import type { BooleanLike, RawRow,
|
|
9
|
+
import type { BooleanLike, Type, RawRow, AbstractType } from './utility.js';
|
|
10
10
|
/**
|
|
11
11
|
* Isolation levels for transactions.
|
|
12
12
|
*/
|
|
@@ -136,7 +136,7 @@ export declare function isSqlQuerier(querier: Querier): querier is SqlQuerier;
|
|
|
136
136
|
* Context passed to global querier listeners.
|
|
137
137
|
*/
|
|
138
138
|
export type ListenerContext<E extends object = object> = {
|
|
139
|
-
readonly entity:
|
|
139
|
+
readonly entity: AbstractType<E>;
|
|
140
140
|
readonly querier: Querier;
|
|
141
141
|
readonly payloads: readonly E[];
|
|
142
142
|
readonly event: HookEvent;
|
package/dist/type/query.d.ts
CHANGED
|
@@ -450,7 +450,7 @@ type MaybeFields<E, M> = [MaybeKeys<M>] extends [never] ? unknown : Partial<Pick
|
|
|
450
450
|
/** The entity, less the relations {@link RelatedRows} fills in, so none comes back as declared. */
|
|
451
451
|
type WholeRow<E, Q> = Q extends {
|
|
452
452
|
readonly $populate: infer M;
|
|
453
|
-
} ?
|
|
453
|
+
} ? Except<E, keyof M & keyof E> & MethodMask<E> : DataRow<E>;
|
|
454
454
|
/** The populated relations, and the `_count` a query asked for. */
|
|
455
455
|
type RelatedRows<E, Q> = Q extends {
|
|
456
456
|
readonly $populate: infer M;
|
package/dist/type/querySql.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { QueryContext, RelationAggregateSpec, SqlQueryDialect, TriggerRows } from './dialect.js';
|
|
2
|
-
import type { Scalar,
|
|
2
|
+
import type { Scalar, AbstractType } from './utility.js';
|
|
3
3
|
/** What a `sql` callback receives. See {@link QuerySqlFn}. */
|
|
4
4
|
export type QuerySqlRenderOptions = {
|
|
5
5
|
/** The dialect rendering the SQL. */
|
|
@@ -14,7 +14,7 @@ export type QuerySqlRenderOptions = {
|
|
|
14
14
|
* The entity being rendered, which a ref read off a definition's map resolves its column against: a
|
|
15
15
|
* computed field's own, or the one whose schema is built. Absent where a statement renders SQL.
|
|
16
16
|
*/
|
|
17
|
-
entity?:
|
|
17
|
+
entity?: AbstractType<unknown>;
|
|
18
18
|
/**
|
|
19
19
|
* The rows a set-based trigger's writes read. Absent where the body reads `NEW` and `OLD` bare, and
|
|
20
20
|
* outside a trigger.
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import type { ForeignKeyAction } from '../schema/types.js';
|
|
2
1
|
import type { Column, ColumnOptionsOf, ColumnValueOf, FilledOptions, NullOf } from './column.js';
|
|
3
|
-
import type { CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
|
|
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';
|
|
4
3
|
import type { QuerySql, RelationAggregate } from './querySql.js';
|
|
5
|
-
import type { Type } from './utility.js';
|
|
4
|
+
import type { Type, AbstractType } from './utility.js';
|
|
6
5
|
/**
|
|
7
|
-
* A schema entity's columns, each an `f` builder. A foreign key is
|
|
8
|
-
*
|
|
9
|
-
*
|
|
6
|
+
* A schema entity's columns, each an `f` builder. A foreign key's target is a relation in `.relations()`, read lazily:
|
|
7
|
+
* a column naming its target here would read it while it is still being inferred. A computed column is declared in
|
|
8
|
+
* `.computed()`, where its row is read-only.
|
|
10
9
|
*/
|
|
11
10
|
export type SchemaFields = {
|
|
12
11
|
readonly [key: string]: Column<{
|
|
@@ -22,7 +21,7 @@ export type ReferencedKey<C> = C extends {
|
|
|
22
21
|
readonly key: infer K;
|
|
23
22
|
};
|
|
24
23
|
} ? unknown extends K ? RowKey<C> : K : RowKey<C>;
|
|
25
|
-
type RowKey<C> = C extends
|
|
24
|
+
type RowKey<C> = C extends AbstractType<infer R> ? NonNullable<IdValue<R>> : never;
|
|
26
25
|
/** The keys of `F` whose column is a `C`. */
|
|
27
26
|
type FlagKeys<F, C> = {
|
|
28
27
|
[K in keyof F]-?: F[K] extends C ? K : never;
|
|
@@ -38,10 +37,16 @@ export type ColumnRow<F, Nullable extends keyof F = FlagKeys<F, Column<{
|
|
|
38
37
|
} & {
|
|
39
38
|
-readonly [K in Nullable]?: ColumnValueOf<F[K]> | null;
|
|
40
39
|
};
|
|
41
|
-
/**
|
|
42
|
-
type
|
|
43
|
-
readonly [K in keyof
|
|
40
|
+
/** A map of fields as a row reads them, never written: required, except an `eager(false)` column, which may be absent. */
|
|
41
|
+
type ReadRow<M> = {
|
|
42
|
+
readonly [K in keyof M as IsEager<M[K]> extends true ? K : never]-?: FieldValue<M[K]>;
|
|
43
|
+
} & {
|
|
44
|
+
readonly [K in keyof M as IsEager<M[K]> extends true ? never : K]?: FieldValue<M[K]>;
|
|
44
45
|
};
|
|
46
|
+
type FieldValue<F> = F extends RelationAggregate<infer V> ? V : ColumnValueOf<F> | NullOf<ColumnOptionsOf<F>>;
|
|
47
|
+
type IsEager<F> = F extends RelationAggregate<unknown> ? true : ColumnOptionsOf<F> extends {
|
|
48
|
+
readonly eager: false;
|
|
49
|
+
} ? false : true;
|
|
45
50
|
/** What `.computed()` returns: columns the database computes, `f.string().as(sql`...`)`. */
|
|
46
51
|
type SchemaComputed = {
|
|
47
52
|
readonly [key: string]: Column<{
|
|
@@ -64,27 +69,38 @@ type AggregateRefs<R> = {
|
|
|
64
69
|
readonly columns?: infer Columns;
|
|
65
70
|
} ? RelationRef<Columns> : never;
|
|
66
71
|
};
|
|
67
|
-
/** The aggregates as a row reads them, each a computed column typed by the value it reads, never written. */
|
|
68
|
-
export type AggregateRow<A> = {
|
|
69
|
-
readonly [K in keyof A]?: A[K] extends () => RelationAggregate<infer V> ? V : never;
|
|
70
|
-
};
|
|
71
72
|
type RelationValue<P> = P extends () => SchemaRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
|
|
73
|
+
/** A relation's derived field as its callback declares it: a thunk, so it is read lazily like a relation is. */
|
|
74
|
+
export type DerivedFields = {
|
|
75
|
+
readonly [key: string]: () => RelationAggregate<unknown> | Column<{
|
|
76
|
+
readonly computed: QuerySql;
|
|
77
|
+
}>;
|
|
78
|
+
};
|
|
79
|
+
/** The derived fields a `relations` callback declares, as a row reads them, never written. */
|
|
80
|
+
export type DerivedRow<A> = {
|
|
81
|
+
readonly [K in keyof A]-?: A[K] extends () => infer F ? FieldValue<F> : never;
|
|
82
|
+
};
|
|
72
83
|
/** The relations as a row reads them; exported, as a schema's emitted declaration names it. */
|
|
73
84
|
export type RelationRow<R> = {
|
|
74
85
|
-readonly [K in keyof R]?: RelationValue<R[K]>;
|
|
75
86
|
};
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
readonly [
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
readonly [filledKey]?: Exclude<FlagKeys<F, Column<FilledOptions>>, FlagKeys<F, Column<{
|
|
85
|
-
readonly isId: true;
|
|
86
|
-
}>>>;
|
|
87
|
+
/**
|
|
88
|
+
* The brands the type level reads keys off, derived from the columns rather than written by hand. A subtype's
|
|
89
|
+
* brands add to its base's, since an intersection with them would narrow each to what the subtype declares.
|
|
90
|
+
*/
|
|
91
|
+
export type Brands<F, B = object> = {
|
|
92
|
+
readonly [idKey]?: IdKeyOf<F> | BrandNames<B, typeof idKey>;
|
|
93
|
+
readonly [versionKey]?: VersionKeyOf<F> | BrandNames<B, typeof versionKey>;
|
|
94
|
+
readonly [filledKey]?: FilledKeyOf<F> | BrandNames<B, typeof filledKey>;
|
|
87
95
|
};
|
|
96
|
+
/** The keys of `F` a brand marks, read off its columns: the id, the version, and the fields a default fills. */
|
|
97
|
+
type IdKeyOf<F> = FlagKeys<F, Column<{
|
|
98
|
+
readonly isId: true;
|
|
99
|
+
}>>;
|
|
100
|
+
type VersionKeyOf<F> = FlagKeys<F, Column<{
|
|
101
|
+
readonly version: true;
|
|
102
|
+
}>>;
|
|
103
|
+
type FilledKeyOf<F> = Exclude<FlagKeys<F, Column<FilledOptions>>, IdKeyOf<F>>;
|
|
88
104
|
/** The relation constructors a schema's `relations` receives, typed by the columns of the entity declaring them. */
|
|
89
105
|
export type RelationBuilder<O> = {
|
|
90
106
|
oneToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>> | RelationInverseOptions<T, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, '11'>;
|
|
@@ -120,51 +136,40 @@ export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown
|
|
|
120
136
|
/** A base that is never a table: the entities extending it take what it declares. */
|
|
121
137
|
readonly abstract?: true;
|
|
122
138
|
/** The entity it inherits from, which the declared class extends, so its methods and `super` work. */
|
|
123
|
-
readonly extends?: SchemaClass<B, BK, BC>;
|
|
139
|
+
readonly extends?: SchemaClass<B, BK, BC, boolean>;
|
|
124
140
|
readonly fields: F;
|
|
125
141
|
};
|
|
126
142
|
/** A hook a schema runs on a row; a promise it returns is awaited. */
|
|
127
143
|
type SchemaHook<Row> = (row: Row, ctx: HookContext) => unknown;
|
|
128
|
-
/**
|
|
129
|
-
* Each foreign key column's target, `{ authorId: () => Author }`, or with its delete action. The getter is typed as
|
|
130
|
-
* returning nothing: typing its target would read an entity referencing itself while it is inferred, so the key's
|
|
131
|
-
* kind is checked on first read.
|
|
132
|
-
*/
|
|
133
|
-
type SchemaReferences<Columns> = {
|
|
134
|
-
readonly [K in keyof Columns]?: LazyTarget | {
|
|
135
|
-
readonly entity: LazyTarget;
|
|
136
|
-
readonly onDelete?: ForeignKeyAction;
|
|
137
|
-
};
|
|
138
|
-
};
|
|
139
|
-
/** The entity a foreign key points at, read once every entity exists. */
|
|
140
|
-
type LazyTarget = () => void;
|
|
141
144
|
/**
|
|
142
145
|
* What a schema declares after its columns, each section typed by the columns now fixed, so none is inferred
|
|
143
|
-
* again. `relations` comes last
|
|
146
|
+
* again. `relations` comes last but for `filters`, which reads the row they complete.
|
|
144
147
|
*/
|
|
145
|
-
type SchemaSections<Row, Key, Columns, B> = {
|
|
148
|
+
type SchemaSections<Row, Key, Columns, B, Abstract> = {
|
|
146
149
|
/** Columns the database computes off the stored ones, `(post) => ({ slug: f.string().as(sql`...`) })`. */
|
|
147
|
-
computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row &
|
|
148
|
-
indexes(indexes: IndexSection<Columns>): SchemaEntity<Row, Key, Columns, B>;
|
|
149
|
-
checks(checks: CheckSection<Columns>): SchemaEntity<Row, Key, Columns, B>;
|
|
150
|
-
triggers(triggers: TriggerSection<Columns>): SchemaEntity<Row, Key, Columns, B>;
|
|
151
|
-
filters(filters: FilterSection<Row>): SchemaEntity<Row, Key, Columns, B>;
|
|
150
|
+
computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row & ReadRow<C>, Key, Columns & ReadRow<C>, B, Abstract>;
|
|
151
|
+
indexes(indexes: IndexSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
|
|
152
|
+
checks(checks: CheckSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
|
|
153
|
+
triggers(triggers: TriggerSection<Columns>): SchemaEntity<Row, Key, Columns, B, Abstract>;
|
|
154
|
+
filters(filters: FilterSection<Row>): SchemaEntity<Row, Key, Columns, B, Abstract>;
|
|
152
155
|
/** Functions each lifecycle event runs on the row, in order, given the querier writing it. */
|
|
153
156
|
hooks(hooks: {
|
|
154
157
|
readonly [E in HookEvent]?: readonly SchemaHook<Row>[];
|
|
155
|
-
}): SchemaEntity<Row, Key, Columns, B>;
|
|
156
|
-
/** The foreign keys no relation joins on, each column's target: `{ authorId: () => Author }`. */
|
|
157
|
-
references(references: SchemaReferences<Columns>): SchemaEntity<Row, Key, Columns, B>;
|
|
158
|
+
}): SchemaEntity<Row, Key, Columns, B, Abstract>;
|
|
158
159
|
/**
|
|
159
160
|
* The relations, each read lazily so entities pointing at each other declare in either order, and the values
|
|
160
|
-
* read over the to-many ones, its base's too: `(
|
|
161
|
+
* read over the to-many ones, its base's too: `(author) => ({ postCount: () => author.posts.count() })`.
|
|
161
162
|
*/
|
|
162
|
-
relations<const R, const A = {}>(relations: (rel: RelationBuilder<Columns>) => R,
|
|
163
|
+
relations<const R, const A extends DerivedFields = {}>(relations: (rel: RelationBuilder<Columns>) => R, derived?: (refs: RefMap<Columns> & AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): RelatedEntity<Row & RelationRow<R> & DerivedRow<A>, Key, Columns, Abstract>;
|
|
164
|
+
};
|
|
165
|
+
/** A schema entity's class once its relations are in: its filters may follow, and read through them. */
|
|
166
|
+
export type RelatedEntity<Row, Key, Columns, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & {
|
|
167
|
+
filters(filters: FilterSection<Row>): SchemaClass<Row, Key, Columns, Abstract>;
|
|
163
168
|
};
|
|
164
169
|
/** A schema entity's class while its sections may still be declared. */
|
|
165
|
-
export type SchemaEntity<Row, Key, Columns, B> = SchemaClass<Row, Key, Columns> & SchemaSections<Row, Key, Columns, B>;
|
|
166
|
-
/** The class a schema declares, to use as it is or to extend with behaviour. */
|
|
167
|
-
export type SchemaClass<Row, Key = unknown, Columns = unknown> = (new () => Row) & SchemaShape<Key, Columns>;
|
|
170
|
+
export type SchemaEntity<Row, Key, Columns, B, Abstract = false> = SchemaClass<Row, Key, Columns, Abstract> & SchemaSections<Row, Key, Columns, B, Abstract>;
|
|
171
|
+
/** The class a schema declares, to use as it is or to extend with behaviour; abstract for a base never a table. */
|
|
172
|
+
export type SchemaClass<Row, Key = unknown, Columns = unknown, Abstract = false> = (Abstract extends true ? abstract new () => Row : new () => Row) & SchemaShape<Key, Columns>;
|
|
168
173
|
declare const schemaShape: unique symbol;
|
|
169
174
|
/**
|
|
170
175
|
* What a relation or an aggregate pointing at a schema reads of it, its key's type and its columns, carried beside
|
|
@@ -183,8 +188,4 @@ type SchemaShape<Key, Columns = unknown> = {
|
|
|
183
188
|
export type SchemaKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
|
|
184
189
|
readonly isId: true;
|
|
185
190
|
}>> extends infer K extends keyof F ? [K] extends [never] ? Inherited : true extends IsUnion<K> ? never : ColumnValueOf<F[K]> : never;
|
|
186
|
-
/** The columns of `O` holding a `V`: a foreign key to a key of that type. */
|
|
187
|
-
type KeyHolding<O, V> = {
|
|
188
|
-
[K in keyof O]-?: NonNullable<O[K]> extends V ? K : never;
|
|
189
|
-
}[keyof O];
|
|
190
191
|
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Standard Schema interface (standardschema.dev, v1), vendored as types so no schema library is a dependency. Zod,
|
|
3
|
+
* Valibot and ArkType implement it, and a payload is typed by its output.
|
|
4
|
+
*/
|
|
5
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
6
|
+
readonly '~standard': {
|
|
7
|
+
readonly version: 1;
|
|
8
|
+
readonly vendor: string;
|
|
9
|
+
readonly validate: (value: unknown) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
|
|
10
|
+
readonly types?: {
|
|
11
|
+
readonly input: Input;
|
|
12
|
+
readonly output: Output;
|
|
13
|
+
} | undefined;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** A validation's outcome: the value it accepts, or the issues it found. */
|
|
17
|
+
export type StandardSchemaV1Result<Output> = {
|
|
18
|
+
readonly value: Output;
|
|
19
|
+
readonly issues?: undefined;
|
|
20
|
+
} | {
|
|
21
|
+
readonly issues: readonly StandardSchemaV1Issue[];
|
|
22
|
+
};
|
|
23
|
+
export interface StandardSchemaV1Issue {
|
|
24
|
+
readonly message: string;
|
|
25
|
+
readonly path?: readonly (PropertyKey | {
|
|
26
|
+
readonly key: PropertyKey;
|
|
27
|
+
})[] | undefined;
|
|
28
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/type/utility.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
/** An entity's class, an abstract base included. */
|
|
2
|
+
export type AbstractType<T> = abstract new (...args: unknown[]) => T;
|
|
3
|
+
/** A concrete entity: an abstract base is never a table, so a query or write does not take one. */
|
|
4
|
+
export type Type<T> = new (...args: unknown[]) => T;
|
|
2
5
|
export type BooleanLike = boolean | 0 | 1;
|
|
3
6
|
export type MongoId = {
|
|
4
7
|
toHexString: () => string;
|
|
@@ -19,9 +22,8 @@ export type QueryComparableScalar = string | number | bigint | Date;
|
|
|
19
22
|
*/
|
|
20
23
|
export type PrimaryKey = string | number | bigint;
|
|
21
24
|
/**
|
|
22
|
-
* Brands a JSON field
|
|
23
|
-
*
|
|
24
|
-
* `null` in `T` stays `null`, so a `JsonValue` type that includes it is a field that may be `null`.
|
|
25
|
+
* Brands a JSON field so it reads as a field rather than a relation: `settings?: Json<{ isArchived?: boolean }>`.
|
|
26
|
+
* A bare `Json` holds any JSON value. A `null` in `T` stays `null`, so `Json<X | null>` may be `null`.
|
|
25
27
|
*/
|
|
26
28
|
export type Json<T extends object | string | number | boolean | null = JsonDocument> = T extends null ? null : T & JsonBrand;
|
|
27
29
|
/** Any value a JSON column holds, which a bare {@link Json} stands for. */
|
|
@@ -33,7 +35,9 @@ declare const json: unique symbol;
|
|
|
33
35
|
export interface JsonBrand {
|
|
34
36
|
readonly [json]?: never;
|
|
35
37
|
}
|
|
36
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Whether `T` carries the {@link Json} brand. A primitive matches `Json<infer P>` too, so the key tells.
|
|
40
|
+
*/
|
|
37
41
|
export type IsJson<T> = typeof json extends keyof T ? true : false;
|
|
38
42
|
export type ExpandScalar<T> = T extends Date ? Date | string : T;
|
|
39
43
|
/**
|
|
@@ -51,44 +55,32 @@ export type IsEqual<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => (T e
|
|
|
51
55
|
export type Writable<T> = {
|
|
52
56
|
-readonly [K in keyof T]: T[K];
|
|
53
57
|
};
|
|
54
|
-
/**
|
|
55
|
-
* `Omit` whose key has to exist, which distributes over a union rather than flattening it, and removes
|
|
56
|
-
* a key from a type with an index signature.
|
|
57
|
-
*
|
|
58
|
-
* `Omit<T, K>` is `Pick<T, Exclude<keyof T, K>>`; its `K extends keyof any` admits any string, so a typo
|
|
59
|
-
* (`Omit<Post, 'titl'>`) compiles and silently drops nothing. `Except` requires `K extends keyof T`, so a
|
|
60
|
-
* misspelled key is a compile error the instant it is written.
|
|
61
|
-
*
|
|
62
|
-
* Beyond the key check, the two differ structurally. `Omit` computes `keyof (A | B)` (the common keys),
|
|
63
|
-
* then `Pick`s from that flat set, so `Omit<A | B, 'x'>` loses every key unique to one arm. `Except` is a
|
|
64
|
-
* homomorphic mapped type over `T`, which TypeScript distributes over unions: `Except<A | B, 'x'>` is
|
|
65
|
-
* `Except<A, 'x'> | Except<B, 'x'>`, each arm keeping its own keys. It also preserves index signatures
|
|
66
|
-
* and property modifiers that `Pick` over a computed key set drops.
|
|
67
|
-
*/
|
|
58
|
+
/** `Omit` whose key must exist and that distributes over unions. See architecture/type-helpers.md. */
|
|
68
59
|
export type Except<T, K extends keyof T> = {
|
|
69
60
|
[P in keyof T as P extends K ? never : P]: T[P];
|
|
70
61
|
};
|
|
62
|
+
/** `T` with each key of `B` replaced by `B`'s: `Except` on the keys both share, then `B` added. */
|
|
63
|
+
export type Merge<A, B> = Except<A, keyof A & keyof B> & B;
|
|
64
|
+
/** Every key any member of a union has, where `keyof` keeps only the ones they share. */
|
|
65
|
+
type KeysOfUnion<T> = T extends unknown ? keyof T : never;
|
|
71
66
|
/**
|
|
72
67
|
* Exactly one key of `T` with its value; every other key is forbidden (`never`). `Pick`, not `Record`,
|
|
73
|
-
* so the chosen key stays linked to `T`'s own property and renames follow it through.
|
|
68
|
+
* so the chosen key stays linked to `T`'s own property and renames follow it through. Distributes over a
|
|
69
|
+
* union, so each arm keeps its own keys and forbids the others'.
|
|
74
70
|
*/
|
|
75
|
-
export type ExactlyOne<T> =
|
|
76
|
-
|
|
77
|
-
|
|
71
|
+
export type ExactlyOne<T> = ExactlyOneOf<T, KeysOfUnion<T>>;
|
|
72
|
+
type ExactlyOneOf<T, Keys extends PropertyKey> = T extends unknown ? {
|
|
73
|
+
[K in keyof T]: Readonly<Pick<T, K>> & Partial<Readonly<Record<Exclude<Keys, K>, never>>>;
|
|
74
|
+
}[keyof T] : never;
|
|
78
75
|
/**
|
|
79
76
|
* At least one key of `T` with its value, the rest optional: the looser sibling of {@link ExactlyOne},
|
|
80
77
|
* for options that combine but cannot all be left out. `Pick`, so every key stays linked to `T`'s own
|
|
81
|
-
* property and renames follow it through.
|
|
78
|
+
* property and renames follow it through. Distributes over a union for the same reason.
|
|
82
79
|
*/
|
|
83
|
-
export type AtLeastOne<T> =
|
|
84
|
-
[K in keyof T]
|
|
85
|
-
}[keyof T];
|
|
80
|
+
export type AtLeastOne<T> = T extends unknown ? {
|
|
81
|
+
[K in keyof T]-?: Required<Pick<T, K>>;
|
|
82
|
+
}[keyof T] & Partial<T> : never;
|
|
86
83
|
export type Unpacked<T> = T extends readonly (infer U)[] ? U : T extends (...args: unknown[]) => infer U ? U : T extends Promise<infer U> ? U : T;
|
|
87
|
-
/**
|
|
88
|
-
* Whether the value a property holds is many rather than one: a to-many relation, a scalar array, a
|
|
89
|
-
* vector. Every array test in the type layer goes through this, because writing one by hand gets some
|
|
90
|
-
* part of it wrong in ways nothing reports. `isMany.test-d.ts` has one case per part, and says what
|
|
91
|
-
* each is load-bearing for.
|
|
92
|
-
*/
|
|
84
|
+
/** Whether a property holds many values, not one. See architecture/type-helpers.md. */
|
|
93
85
|
export type IsMany<V> = [NonNullable<V>] extends [readonly unknown[]] ? true : false;
|
|
94
86
|
export {};
|
package/dist/util/hook.util.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import type { HookContext, HookEvent,
|
|
1
|
+
import type { HookContext, HookEvent, AbstractType } from '../type/index.js';
|
|
2
2
|
/** Runs each hook registered for `event` on each payload, in order, awaiting each: a hook mutates the payload itself. */
|
|
3
|
-
export declare function runHooks<E extends object>(entity:
|
|
3
|
+
export declare function runHooks<E extends object>(entity: AbstractType<E>, event: HookEvent, payloads: readonly E[], ctx: HookContext): Promise<void>;
|
package/dist/util/sql.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ColumnRef, type IndexRefMap, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type
|
|
1
|
+
import { ColumnRef, type IndexRefMap, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type SqlArg, type SqlStatement, type SqlValueName, type TriggerRowName, type AbstractType } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Raw SQL, where an interpolated value binds, a `refs` field renders its column, and a `sql` renders
|
|
4
4
|
* in place: `sql`GREATEST(0, ${user.credits} - ${amount})``. A callback writes whatever it writes, so
|
|
@@ -37,14 +37,12 @@ export declare const SQL_VALUES: Readonly<Record<SqlValueName, QuerySql>>;
|
|
|
37
37
|
* the dialect names it, so the naming strategy and `.name()` apply, and qualified by the alias
|
|
38
38
|
* in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
|
|
39
39
|
*/
|
|
40
|
-
export declare function refs<E>(entity:
|
|
40
|
+
export declare function refs<E>(entity: AbstractType<E>): RefMap<E>;
|
|
41
41
|
/**
|
|
42
42
|
* The refs a definition's callbacks read: a check's, a computed field's, a predicate's. A member decorator
|
|
43
43
|
* sees no class, so these name no entity and resolve against the one rendering them.
|
|
44
44
|
*/
|
|
45
45
|
export declare function memberRefs<E>(): ComputedRefs<E>;
|
|
46
|
-
/** Each to-many as a schema's aggregates read it, by key: the same refs {@link memberRefs} gives a decorated entity. */
|
|
47
|
-
export declare function relationRefs(): Readonly<Record<string, RelationRef<object>>>;
|
|
48
46
|
/**
|
|
49
47
|
* The refs an index's callbacks read: each field's column, a JSON one also read into along its paths,
|
|
50
48
|
* `(user) => [user.settings.theme]`. Named for no entity, as {@link memberRefs} are.
|
|
@@ -56,11 +54,11 @@ export declare function indexRefs<E>(): IndexRefMap<E>;
|
|
|
56
54
|
* {@link refs} are, so each names its own column wherever it renders, a write to another table included.
|
|
57
55
|
* Columns only: a relation's aggregate is a subquery, and a trigger fires on one row, not over a table.
|
|
58
56
|
*/
|
|
59
|
-
export declare function rowRefs<E>(entity:
|
|
57
|
+
export declare function rowRefs<E>(entity: AbstractType<E>, qualifier: TriggerRowName): RefMap<E>;
|
|
60
58
|
/**
|
|
61
59
|
* One field as SQL, against its own entity or, read off a definition, the entity rendering it. A
|
|
62
60
|
* `qualifier` names the row it reads from, `NEW` or `OLD`, instead of the alias in scope.
|
|
63
61
|
*/
|
|
64
|
-
export declare function columnRef(entity:
|
|
62
|
+
export declare function columnRef(entity: AbstractType<unknown> | undefined, key: string, qualifier?: string): ColumnRef;
|
|
65
63
|
/** @deprecated Renamed to {@link sql}, the tag editors recognise for SQL highlighting. */
|
|
66
64
|
export declare const raw: typeof sql;
|
package/dist/util/sql.js
CHANGED
|
@@ -105,10 +105,6 @@ function refMap(ref) {
|
|
|
105
105
|
export function memberRefs() {
|
|
106
106
|
return refMap(memberRef);
|
|
107
107
|
}
|
|
108
|
-
/** Each to-many as a schema's aggregates read it, by key: the same refs {@link memberRefs} gives a decorated entity. */
|
|
109
|
-
export function relationRefs() {
|
|
110
|
-
return refMap(memberRef);
|
|
111
|
-
}
|
|
112
108
|
/**
|
|
113
109
|
* The refs an index's callbacks read: each field's column, a JSON one also read into along its paths,
|
|
114
110
|
* `(user) => [user.settings.theme]`. Named for no entity, as {@link memberRefs} are.
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { type EntityPredicate, type QueryConflictPaths, type QuerySql, type TriggerWrite, type
|
|
1
|
+
import { type EntityPredicate, type QueryConflictPaths, type QuerySql, type TriggerWrite, type AbstractType, type UpdatePayload, type WritableKey, type WriteRow } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* A row inserted by a trigger's body, into any table: `insertInto(PostAudit, { postId: newRow.id })`.
|
|
4
4
|
* Each value is a literal or SQL, a row's ref most often, and every engine renders it, SQL Server's
|
|
5
5
|
* set-based trigger included, where it inserts one row for each the statement touched.
|
|
6
6
|
*/
|
|
7
|
-
export declare function insertInto<E extends object>(entity:
|
|
7
|
+
export declare function insertInto<E extends object>(entity: AbstractType<E>, row: WriteRow<E>): QuerySql;
|
|
8
8
|
/**
|
|
9
9
|
* A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
|
|
10
10
|
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { count: { $inc: 1 } })`.
|
|
11
11
|
*/
|
|
12
|
-
export declare function upsertInto<E extends object>(entity:
|
|
12
|
+
export declare function upsertInto<E extends object>(entity: AbstractType<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>, update?: UpdatePayload<E, QuerySql, WritableKey<E>, never>): QuerySql;
|
|
13
13
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
|
14
|
-
export declare function updateTable<E extends object>(entity:
|
|
14
|
+
export declare function updateTable<E extends object>(entity: AbstractType<E>, q: {
|
|
15
15
|
readonly $where: EntityPredicate<E>;
|
|
16
16
|
}, set: UpdatePayload<E, QuerySql, WritableKey<E>, never>): QuerySql;
|
|
17
17
|
/** The rows `q.$where` names deleted by a trigger's body, outright: a soft delete is an `updateTable`. */
|
|
18
|
-
export declare function deleteFrom<E extends object>(entity:
|
|
18
|
+
export declare function deleteFrom<E extends object>(entity: AbstractType<E>, q: {
|
|
19
19
|
readonly $where: EntityPredicate<E>;
|
|
20
20
|
}): QuerySql;
|
|
21
21
|
/**
|
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.106.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -77,12 +77,12 @@ export class Post {
|
|
|
77
77
|
}
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
- A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal()`, `f.decimal(precision)`, `f.decimal(precision, scale)`, `f.boolean()`, `f.date()`, `f.json(
|
|
80
|
+
- A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal()`, `f.decimal(precision)`, `f.decimal(precision, scale)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other column type, and `f.references(() => Target)` for a foreign key, which takes the target's key type. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A bound holds in either order around `.columnType('char')`, but not around a `sql` type, which carries its own.
|
|
81
81
|
- A column is NOT NULL unless `.nullable()`; its property then admits `null` (`title?: string | null`).
|
|
82
|
-
- Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable, `.eager(false)
|
|
82
|
+
- Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable columns, `.eager(false)` fields, and relations. A computed field is present on a default read, so it is not optional. uql fills a single-column key and a version.
|
|
83
83
|
- A NOT NULL field a default fills (`.default()`, `.onInsert()`) is `!` and listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
|
|
84
84
|
- `.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.
|
|
85
|
-
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... })`.
|
|
85
|
+
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... }) abstract class`, or a schema's `abstract: true`. A query or write on one does not compile: query the entities extending it.
|
|
86
86
|
- `Date` is an instant, stored in UTC to the millisecond on every engine. `f.decimal()` is exact text (`price?: string | null`). `f.number().precision(10).scale(2)` opts into a rounding JS number.
|
|
87
87
|
- Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`. Either may be left out where only one member fits: a decorated many-to-one's one foreign key to its target, a one-to-many's one many-to-one pointing back.
|
|
88
88
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows in the same transaction; an update replaces a to-many's rows.
|
|
@@ -99,17 +99,30 @@ The same entities declared as data, the row type derived:
|
|
|
99
99
|
|
|
100
100
|
```ts
|
|
101
101
|
import { defineEntity, f, sql } from 'uql-orm';
|
|
102
|
+
import { z } from 'zod';
|
|
103
|
+
|
|
104
|
+
// Any Standard Schema types the payload: a Zod schema here.
|
|
105
|
+
const Settings = z.object({ theme: z.string(), bio: z.string().optional() });
|
|
102
106
|
|
|
103
107
|
export const Author = defineEntity({
|
|
104
108
|
name: 'Author',
|
|
105
109
|
fields: {
|
|
106
110
|
id: f.number().id(),
|
|
107
111
|
name: f.string(),
|
|
108
|
-
settings: f.json(
|
|
112
|
+
settings: f.json(Settings).nullable(),
|
|
109
113
|
},
|
|
110
114
|
}).relations(
|
|
111
115
|
(rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }),
|
|
112
|
-
(
|
|
116
|
+
(author) => ({
|
|
117
|
+
bookCount: () => author.books.count(),
|
|
118
|
+
topStock: () => author.books.max((book) => book.stock),
|
|
119
|
+
// A derived field may also combine its own columns with an aggregate in one expression.
|
|
120
|
+
stockGap: () =>
|
|
121
|
+
f
|
|
122
|
+
.number()
|
|
123
|
+
.nullable()
|
|
124
|
+
.as(sql`${author.books.max((book) => book.stock)} - ${author.id}`),
|
|
125
|
+
}),
|
|
113
126
|
);
|
|
114
127
|
export type Author = InstanceType<typeof Author>;
|
|
115
128
|
|
|
@@ -126,16 +139,18 @@ export const Book = defineEntity({
|
|
|
126
139
|
.computed((book) => ({ shout: f.string().as(sql`upper(${book.title})`) }))
|
|
127
140
|
.indexes((book, index) => [index([book.title])])
|
|
128
141
|
.hooks({ beforeInsert: [(book) => void (book.stock ??= 0)] })
|
|
129
|
-
.
|
|
130
|
-
|
|
142
|
+
.relations((rel) => ({
|
|
143
|
+
author: () => rel.manyToOne(Author, { references: (book) => book.authorId }),
|
|
144
|
+
editor: () => rel.manyToOne(Author, { references: (book) => book.editorId, onDelete: 'SET NULL' }),
|
|
145
|
+
}));
|
|
131
146
|
```
|
|
132
147
|
|
|
133
148
|
- Each field is a column builder, as in the decorated form. The row follows from them: a key, a version and a NOT NULL column are always present, a `.nullable()` one reads `| null`; a default (`.default()`, `.onInsert()`, `.autoIncrement()`) makes it optional on insert; `f.enum()` gives the literal union. No `!`, `?` or brands to write.
|
|
134
|
-
- The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `
|
|
135
|
-
- Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. `manyToOne` names its `references
|
|
136
|
-
- `relations`' second callback
|
|
149
|
+
- The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `relations` comes last, but for a `filters` that reads through them: `.relations(...).filters({ byActiveAuthor: { where: { author: { active: true } } } })`. `defineEntity` itself takes `name` (the class name, which a naming strategy derives the table from), `table`, `schema`, `extends` and `fields`.
|
|
150
|
+
- Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. A schema's foreign key is a relation: `manyToOne` names its `references` column, whose type is checked against the target's key; the column itself stays a plain field. `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
|
|
151
|
+
- `relations`' second callback declares the derived fields: each value is a thunk, read lazily, of an aggregate over a to-many (`() => author.books.count()`) or a column expression. The callback's refs are the entity's own columns and its relations, so one expression can combine them.
|
|
137
152
|
- A hook is a function of the row and `{ querier, onCommit }`.
|
|
138
|
-
- A JSON column's payload is
|
|
153
|
+
- A JSON column's payload is a Standard Schema, `f.json(schema)`, typed by its output: any library's schema (Zod, Valibot, ArkType), or a hand-written `StandardSchemaV1`. Without one, any path reads. The schema types the column; uql never runs it, so a write is not validated.
|
|
139
154
|
- Behaviour is a function of the row, `label(author: Author)`: a row reads back as a plain object, so a method would never be there.
|
|
140
155
|
|
|
141
156
|
## Queries
|