uql-orm 0.103.0 → 0.103.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/package.json +4 -4
- package/skills/uql-orm/SKILL.md +57 -43
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.103.
|
|
6
|
+
"version": "0.103.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
|
@@ -123,8 +123,8 @@
|
|
|
123
123
|
}
|
|
124
124
|
},
|
|
125
125
|
"devDependencies": {
|
|
126
|
-
"@electric-sql/pglite": "0.5.
|
|
127
|
-
"@electric-sql/pglite-pgvector": "0.0.
|
|
126
|
+
"@electric-sql/pglite": "0.5.11",
|
|
127
|
+
"@electric-sql/pglite-pgvector": "0.0.12",
|
|
128
128
|
"@libsql/client": "^0.18.0",
|
|
129
129
|
"@neondatabase/serverless": "^1.2.0",
|
|
130
130
|
"@nestjs/common": "^12.2.0",
|
|
@@ -141,7 +141,7 @@
|
|
|
141
141
|
"express": "^5.3.0",
|
|
142
142
|
"mariadb": "^3.5.4",
|
|
143
143
|
"mongodb": "^7.7.0",
|
|
144
|
-
"mssql": "^12.7.
|
|
144
|
+
"mssql": "^12.7.11",
|
|
145
145
|
"mysql2": "^3.24.6",
|
|
146
146
|
"pg": "^8.23.1",
|
|
147
147
|
"pg-query-stream": "^4.17.1",
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -12,7 +12,7 @@ description: >
|
|
|
12
12
|
|
|
13
13
|
Entities are classes. A query is a JSON object checked key by key against the entity, and it runs the same on every supported database. There is no schema file, no generated client and no query builder.
|
|
14
14
|
|
|
15
|
-
Full docs are Markdown: the index at https://uql-orm.dev/llms.txt, and each page at its URL plus `.md`. Read the page for the task before guessing an option.
|
|
15
|
+
Full docs are Markdown: the index at https://uql-orm.dev/llms.txt, and each page at its URL plus `.md`. Read the page for the task before guessing an option.
|
|
16
16
|
|
|
17
17
|
## Setup
|
|
18
18
|
|
|
@@ -20,11 +20,11 @@ Full docs are Markdown: the index at https://uql-orm.dev/llms.txt, and each page
|
|
|
20
20
|
npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/client, ...
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
ESM only
|
|
23
|
+
ESM only. Needs Node 22.18+, Bun or an edge runtime, and TypeScript 5.7+.
|
|
24
24
|
|
|
25
|
-
Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`.
|
|
25
|
+
Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`. A project on legacy decorators (NestJS, Angular) keeps its config and defines entities with `defineEntity`: https://uql-orm.dev/entities/imperative.md
|
|
26
26
|
|
|
27
|
-
Node
|
|
27
|
+
Node runs no decorators natively yet, so add `tsx` there (`npm i -D tsx`); `uql-migrate` loads `uql.config.ts` through it. A bundler that minifies class names needs `@Entity({ name: 'todo' })`, since the table name defaults to the class name.
|
|
28
28
|
|
|
29
29
|
```ts
|
|
30
30
|
// uql.config.ts
|
|
@@ -72,22 +72,19 @@ export class Post {
|
|
|
72
72
|
}
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. The base needs no `@Entity()` unless it is a table.
|
|
76
|
-
- Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references` and inherits the target's type. A
|
|
77
|
-
- A column is nullable unless it says `nullable: false`. Its property must admit `null
|
|
78
|
-
-
|
|
79
|
-
- Declare a `nullable: false` column with `!` (`email!: string`). Declare `?` for anything an insert may omit: nullable, `onInsert`, `defaultValue`, `eager: false`, `computed` fields, and relations. A single-column key and a `version` are filled by uql.
|
|
75
|
+
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. The base needs no `@Entity()` unless it is a table.
|
|
76
|
+
- Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references` and inherits the target's type. A JSON column of no fixed shape is a bare `Json`.
|
|
77
|
+
- A column is nullable unless it says `nullable: false`. Its property must admit `null` (`title?: string | null`).
|
|
78
|
+
- Declare a `nullable: false` column with `!` (`email!: string`). Declare `?` for anything an insert may omit: nullable, `onInsert`, `defaultValue`, `eager: false`, computed fields and relations. uql fills a single-column key and a `version`.
|
|
80
79
|
- `defaultValue` is 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.
|
|
81
|
-
- `
|
|
82
|
-
- An engine's own column type is a `sql` constant: ``columnType: sql`tsvector` ``.
|
|
80
|
+
- `Date` is an instant, stored in UTC to the millisecond on every engine. `'decimal'` is exact text (`price?: string | null`). `type: Number` with `precision`/`scale` opts into a rounding JS number.
|
|
83
81
|
- Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
84
|
-
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity.
|
|
85
|
-
-
|
|
86
|
-
-
|
|
87
|
-
-
|
|
88
|
-
-
|
|
89
|
-
- `@Trigger({ on: 'afterUpdate', of: (post) => [post.status],
|
|
90
|
-
- `defineEntity` defines the same entity without decorators: https://uql-orm.dev/entities/imperative.md
|
|
82
|
+
- `@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.
|
|
83
|
+
- **MongoDB:** a key declared `Number` and left to the database is refused, since MongoDB only generates ObjectIds. Declare the key a `String`, or give it an `onInsert` generator.
|
|
84
|
+
- Optimistic lock: `@Field({ type: Number, version: true })` with `[versionKey]?: 'version'` on the class. An update must carry the version it read. A stale one throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409).
|
|
85
|
+
- Computed fields are `readonly` and read in any query that names them. As SQL over the row ``(u) => sql`${u.first} || ' ' || ${u.last}` ``, or as a relation aggregate: `@Field({ computed: (user) => user.resources.count() })`. `stored: true` makes a generated column.
|
|
86
|
+
- Partial index: `@Index((post) => [post.authorId], { where: { archived: { $ne: true } } })`. Write the predicate as a query, not `sql`.
|
|
87
|
+
- Triggers run in the database: `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], run })`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. A trigger's writes skip uql's fills and entity filters. MongoDB has no triggers: https://uql-orm.dev/entities/triggers.md
|
|
91
88
|
|
|
92
89
|
## Queries
|
|
93
90
|
|
|
@@ -109,22 +106,47 @@ const users = await pool.findMany(User, {
|
|
|
109
106
|
- 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, or the query's `$entity`. Signatures: https://uql-orm.dev/querying/methods.md
|
|
110
107
|
- Results are narrowed to what the query selected and populated. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`.
|
|
111
108
|
- `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent.
|
|
112
|
-
- In code generic over its entity, `{ [key]: 'asc' }` widens to an index signature. Take the member as a selector, `since: (keys: KeyMap<E>) => K`, read it with `keyOf(since)`, and sort with `sortOf<E>([[key, 'asc']])`. A selector follows a rename; a string key does not. `$where` and writes by a constant have no such builder: take a callback the caller writes against its own entity, `(state) => ({ state })`.
|
|
113
109
|
- `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, plus `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`, which behave the same on every engine. Unqualified, each engine keeps its own null order.
|
|
114
110
|
- `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`, `$isNotNull`. Combine with `$and`, `$or`, `$not`, `$nor`. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
|
|
115
111
|
- An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
|
|
116
|
-
- NULL compares as the engine does: on SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.
|
|
117
|
-
-
|
|
118
|
-
- `
|
|
119
|
-
-
|
|
120
|
-
- Writes take `{ returning: { id: true } }` as their last argument and resolve to those rows, read back in the same transaction. Without it, inserts and upserts resolve to ids, and updates and deletes to a count. An update or delete writes exactly the rows it reports. One that reads its rows first holds them, so a racing writer waits for the commit. SQLite and MongoDB have no row locks and fail the racing writer with a retryable error instead.
|
|
121
|
-
- A query is plain data, so it can be sent from a browser to `uql-orm/http`. Its handler serves only the entities its required `include` names.
|
|
112
|
+
- NULL compares as the engine does: on SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.
|
|
113
|
+
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does. It returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique `nullable: false` field, and takes no `$skip`.
|
|
114
|
+
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update payload with operators. Without `update`, a conflicting row takes the payload but keeps its own key. Resolves to the row's id.
|
|
115
|
+
- Writes take `{ returning: { id: true } }` as their last argument and resolve to those rows. Without it, inserts and upserts resolve to ids, and updates and deletes to a count.
|
|
122
116
|
- `updateMany` and `deleteMany` that name no rows throw: no `$where` holding a value, and no `$limit`. Pass `{ unfiltered: true }` to mean the whole table.
|
|
123
|
-
- Updates use operators
|
|
124
|
-
- JSON fields take `$pull`, `$set`, `$push`, `$addToSet`, then `$unset`, applied in that order on one value. `$set` and `$unset` take keys or dotted paths and create parents: `settings: { $set: { 'billing.plan': 'pro' } }`.
|
|
117
|
+
- Updates use operators: `{ stock: { $inc: -1 } }` or `$mul`, with NULL counted as 0. Put a guard in `$where` (`stock: { $gte: 1 }`) to make a decrement race-safe.
|
|
118
|
+
- JSON fields take `$pull`, `$set`, `$push`, `$addToSet`, then `$unset`, applied in that order on one value. `$set` and `$unset` take keys or dotted paths and create parents: `settings: { $set: { 'billing.plan': 'pro' } }`.
|
|
125
119
|
- `$lock: true` locks the rows a read returns, and `{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds. It needs an open transaction. SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
|
|
126
|
-
- `queryErrorKind(err)` names a failure the same on every engine: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code.
|
|
127
|
-
- Raw SQL: ``pool.all`SELECT ... WHERE id = ${id}` `` for a `SELECT`, ``pool.run`...` `` for a write. Interpolated values bind: a scalar, `null` or a list, never `undefined` or a plain object
|
|
120
|
+
- `queryErrorKind(err)` names a failure the same on every engine: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code.
|
|
121
|
+
- Raw SQL: ``pool.all`SELECT ... WHERE id = ${id}` `` for a `SELECT`, ``pool.run`...` `` for a write. Interpolated values bind: a scalar, `null` or a list, never `undefined` or a plain object. `sql` builds a fragment, and `sql.join(fragments, ' AND ')` joins them. `sql.text(s)` runs trusted SQL held in a string. Never build it from user input.
|
|
122
|
+
|
|
123
|
+
## Aggregates
|
|
124
|
+
|
|
125
|
+
Compute in SQL, not in code. Loading rows to dedupe, count or sum them in JavaScript costs a round trip and every row.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { Post } from './entities.js';
|
|
129
|
+
import { pool } from './uql.config.js';
|
|
130
|
+
|
|
131
|
+
// Distinct values: a $group with no $select returns each once.
|
|
132
|
+
const titles = await pool.aggregate(Post, {
|
|
133
|
+
$group: { title: true },
|
|
134
|
+
$sort: { title: 1 },
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// Tallies per group, in one statement.
|
|
138
|
+
const counts = await pool.aggregate(Post, {
|
|
139
|
+
$group: { authorId: true },
|
|
140
|
+
$select: { distinctTitles: { $countDistinct: { title: true } } },
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- `$select` takes `$count` (`'*'` or a field), `$countDistinct`, `$sum`, `$avg`, `$min` and `$max`. Over no rows a count is `0` and the others are `null`.
|
|
145
|
+
- `$where` on the query filters rows before grouping. An operator's own `$where` filters only the rows that operator reads, which pivots rows into columns in one query: `{ $count: '*', $where: { published: true } }`.
|
|
146
|
+
- `$having` and `$sort` name a grouped column or a `$select` alias, never a field that is not grouped.
|
|
147
|
+
- A `$group` key can reach a to-one relation's field: `{ orderId: { transaction: { orderId: true } } }`. A to-many cannot be grouped, since it multiplies the rows.
|
|
148
|
+
- A per-row count belongs on the entity as a `computed` field, not as an aggregate per request. Counts for a read's rows: `$count: { posts: true }`.
|
|
149
|
+
- Details: https://uql-orm.dev/querying/aggregate.md
|
|
128
150
|
|
|
129
151
|
## Connections and transactions
|
|
130
152
|
|
|
@@ -137,33 +159,25 @@ await pool.transaction(async (querier) => {
|
|
|
137
159
|
});
|
|
138
160
|
```
|
|
139
161
|
|
|
140
|
-
The callback commits when it returns and rolls back when it throws. Inside it, `pool` calls run on its querier. A
|
|
162
|
+
The callback commits when it returns and rolls back when it throws. Inside it, `pool` calls run on its querier. A nested `transaction()` is a savepoint; MongoDB refuses it. For a transaction that opens in one place and ends in another, use `beginTransaction`, `commitTransaction` and `rollbackTransaction`. `querier.onCommit(fn)` runs `fn` after the outermost commit and never on rollback: use it for mail and queued jobs. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
141
163
|
|
|
142
|
-
A
|
|
143
|
-
|
|
144
|
-
A `findManyStream` holds its querier until the loop ends, and other statements on it are refused meanwhile. Inside the loop, run them on another connection. Inside a transaction, or on SQLite and PGlite (one shared connection), run them after the loop. That includes an `@AfterLoad` querying through its `querier` on a streamed row. A statement binding more values than the engine takes (100 on D1, 2098 on SQL Server, 32,767 on Neon) is refused: split a long `$in`.
|
|
164
|
+
A `findManyStream` holds its querier until the loop ends, and other statements on it are refused meanwhile. Run them after the loop, or on another connection.
|
|
145
165
|
|
|
146
166
|
## Migrations
|
|
147
167
|
|
|
148
168
|
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|
|
149
169
|
|
|
150
170
|
- `sync`: applies what the entities imply. Development only.
|
|
151
|
-
- `generate:entities`: writes the diff as a migration file to review. A renamed column is a drop and an add, unless a naming strategy maps it
|
|
152
|
-
- `up` and `down`: each migration runs in its own transaction, under a lock so concurrent instances run it once. From code, `await new Migrator(pool, { migrationsPath }).up()` before the app starts.
|
|
171
|
+
- `generate:entities`: writes the diff as a migration file to review. A renamed column is a drop and an add, unless a naming strategy maps it or you write `renameColumn(table, from, to)`. It refuses a required column with no default on a table that holds rows.
|
|
172
|
+
- `up` and `down`: each migration runs in its own transaction, under a lock so concurrent instances run it once. From code, `await new Migrator(pool, { migrationsPath }).up()` before the app starts.
|
|
153
173
|
- `generate:from-db`: writes entity classes from an existing database.
|
|
154
|
-
- `drift:check`: fails when the database no longer matches
|
|
155
|
-
- `sync --dry-run`: prints only SQL on stdout, for a migration file another tool applies
|
|
156
|
-
|
|
157
|
-
In a migration, ``querier.run /*sql*/ `CREATE TABLE ...` `` marks the SQL: the comment is what es6-string-html highlights.
|
|
158
|
-
|
|
159
|
-
Checks, enums and triggers are part of the diff. uql owns the `_uql_`-prefixed checks and triggers and never touches another. On MongoDB, checks and enums are the collection's validator, which uql owns whole: a check fails a document that lacks the field it compares.
|
|
174
|
+
- `drift:check`: fails when the database no longer matches the entities.
|
|
175
|
+
- `sync --dry-run`: prints only SQL on stdout, for a migration file another tool applies.
|
|
160
176
|
|
|
161
177
|
## Where to read more
|
|
162
178
|
|
|
163
179
|
- Operators and per-dialect SQL: https://uql-orm.dev/querying/comparison-operators.md
|
|
164
180
|
- Relations and deep `$populate`: https://uql-orm.dev/querying/relations.md
|
|
165
181
|
- Computed fields and stamps: https://uql-orm.dev/entities/computed-fields.md
|
|
166
|
-
- Triggers: https://uql-orm.dev/entities/triggers.md
|
|
167
182
|
- Coming from Prisma, Drizzle, TypeORM, MikroORM or Mongoose: https://uql-orm.dev/switching-to-uql.md
|
|
168
|
-
- Moving data off MongoDB: https://uql-orm.dev/mongodb.md#moving-to-sql
|
|
169
183
|
- Breaking changes by version: https://uql-orm.dev/upgrade-guide.md
|