uql-orm 0.105.1 → 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.
@@ -22,9 +22,8 @@ export type QueryComparableScalar = string | number | bigint | Date;
22
22
  */
23
23
  export type PrimaryKey = string | number | bigint;
24
24
  /**
25
- * Brands a JSON field, `settings?: Json<{ isArchived?: boolean }>`, so it reads as a field rather than a
26
- * relation; `Json<T>[]` is a list of documents, and a bare `Json` holds any JSON value, under any path. A
27
- * `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`.
28
27
  */
29
28
  export type Json<T extends object | string | number | boolean | null = JsonDocument> = T extends null ? null : T & JsonBrand;
30
29
  /** Any value a JSON column holds, which a bare {@link Json} stands for. */
@@ -36,7 +35,9 @@ declare const json: unique symbol;
36
35
  export interface JsonBrand {
37
36
  readonly [json]?: never;
38
37
  }
39
- /** Whether `T` carries the {@link Json} brand: a primitive matches `Json<infer P>` too, so the key is what tells. */
38
+ /**
39
+ * Whether `T` carries the {@link Json} brand. A primitive matches `Json<infer P>` too, so the key tells.
40
+ */
40
41
  export type IsJson<T> = typeof json extends keyof T ? true : false;
41
42
  export type ExpandScalar<T> = T extends Date ? Date | string : T;
42
43
  /**
@@ -54,44 +55,32 @@ export type IsEqual<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => (T e
54
55
  export type Writable<T> = {
55
56
  -readonly [K in keyof T]: T[K];
56
57
  };
57
- /**
58
- * `Omit` whose key has to exist, which distributes over a union rather than flattening it, and removes
59
- * a key from a type with an index signature.
60
- *
61
- * `Omit<T, K>` is `Pick<T, Exclude<keyof T, K>>`; its `K extends keyof any` admits any string, so a typo
62
- * (`Omit<Post, 'titl'>`) compiles and silently drops nothing. `Except` requires `K extends keyof T`, so a
63
- * misspelled key is a compile error the instant it is written.
64
- *
65
- * Beyond the key check, the two differ structurally. `Omit` computes `keyof (A | B)` (the common keys),
66
- * then `Pick`s from that flat set, so `Omit<A | B, 'x'>` loses every key unique to one arm. `Except` is a
67
- * homomorphic mapped type over `T`, which TypeScript distributes over unions: `Except<A | B, 'x'>` is
68
- * `Except<A, 'x'> | Except<B, 'x'>`, each arm keeping its own keys. It also preserves index signatures
69
- * and property modifiers that `Pick` over a computed key set drops.
70
- */
58
+ /** `Omit` whose key must exist and that distributes over unions. See architecture/type-helpers.md. */
71
59
  export type Except<T, K extends keyof T> = {
72
60
  [P in keyof T as P extends K ? never : P]: T[P];
73
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;
74
66
  /**
75
67
  * Exactly one key of `T` with its value; every other key is forbidden (`never`). `Pick`, not `Record`,
76
- * 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'.
77
70
  */
78
- export type ExactlyOne<T> = {
79
- [K in keyof T]: Readonly<Pick<T, K>> & Partial<Readonly<Record<Exclude<keyof T, K>, never>>>;
80
- }[keyof T];
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;
81
75
  /**
82
76
  * At least one key of `T` with its value, the rest optional: the looser sibling of {@link ExactlyOne},
83
77
  * for options that combine but cannot all be left out. `Pick`, so every key stays linked to `T`'s own
84
- * property and renames follow it through.
78
+ * property and renames follow it through. Distributes over a union for the same reason.
85
79
  */
86
- export type AtLeastOne<T> = Partial<T> & {
87
- [K in keyof T]: Pick<T, K>;
88
- }[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;
89
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;
90
- /**
91
- * Whether the value a property holds is many rather than one: a to-many relation, a scalar array, a
92
- * vector. Every array test in the type layer goes through this, because writing one by hand gets some
93
- * part of it wrong in ways nothing reports. `isMany.test-d.ts` has one case per part, and says what
94
- * each is load-bearing for.
95
- */
84
+ /** Whether a property holds many values, not one. See architecture/type-helpers.md. */
96
85
  export type IsMany<V> = [NonNullable<V>] extends [readonly unknown[]] ? true : false;
97
86
  export {};
@@ -16,7 +16,7 @@ const FIELD_OPTION_FAMILY = {
16
16
  references: '*',
17
17
  onDelete: '*',
18
18
  enum: '*',
19
- shape: 'json',
19
+ schema: 'json',
20
20
  computed: '*',
21
21
  stored: '*',
22
22
  updatable: '*',
@@ -1,4 +1,4 @@
1
- import { ColumnRef, type IndexRefMap, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type RelationRef, type SqlArg, type SqlStatement, type SqlValueName, type TriggerRowName, type AbstractType } from '../type/index.js';
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
@@ -43,8 +43,6 @@ export declare function refs<E>(entity: AbstractType<E>): RefMap<E>;
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.
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.
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.105.1",
6
+ "version": "0.106.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -77,9 +77,9 @@ 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(shape?)`, `f.jsonb(shape?)`, `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.
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)`, computed fields and relations. uql fills a single-column key and a version.
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
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.
@@ -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({ theme: String, 'bio?': String }).nullable(),
112
+ settings: f.json(Settings).nullable(),
109
113
  },
110
114
  }).relations(
111
115
  (rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }),
112
- (agg) => ({ bookCount: () => agg.books.count(), topStock: () => agg.books.max((book) => book.stock) }),
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
- .references({ editorId: { entity: () => Author, onDelete: 'SET NULL' } })
130
- .relations((rel) => ({ author: () => rel.manyToOne(Author, { references: (book) => book.authorId }) }));
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; `references` points a foreign key with no relation at its target; `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`.
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`; `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
136
- - `relations`' second callback reads values over a to-many as columns: `(agg) => ({ bookCount: () => agg.books.count() })`.
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 its shape, `f.json(shape)`: `String`, `Number` or `Boolean`, an object of shapes, `[shape]` for an array, `'key?'` for an optional member. Without one, any path reads.
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