uql-orm 0.92.0 → 0.93.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/dist/browser/uql-browser.min.js.map +2 -2
- package/dist/cockroachdb/cockroachDialect.js +1 -1
- package/dist/dialect/abstractSqlDialect.d.ts +45 -10
- package/dist/dialect/abstractSqlDialect.js +147 -64
- package/dist/dialect/mergeSqlDialect.d.ts +11 -2
- package/dist/dialect/mergeSqlDialect.js +28 -12
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
- package/dist/dialect/mysqlLikeSqlDialect.js +34 -21
- package/dist/dialect/pgLikeSqlDialect.d.ts +5 -1
- package/dist/dialect/pgLikeSqlDialect.js +8 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/maria/mariaDialect.d.ts +3 -1
- package/dist/maria/mariaDialect.js +3 -1
- package/dist/migrate/builder/index.d.ts +0 -1
- package/dist/migrate/builder/index.js +0 -1
- package/dist/migrate/builder/tableBuilder.js +2 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +4 -11
- package/dist/migrate/ddl/defaultSql.d.ts +31 -0
- package/dist/migrate/ddl/defaultSql.js +109 -0
- package/dist/migrate/ddl/index.d.ts +1 -1
- package/dist/migrate/ddl/index.js +3 -3
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +3 -1
- package/dist/migrate/ddl/mssqlTableDdl.js +4 -0
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +1 -1
- package/dist/migrate/ddl/mysqlTableDdl.js +2 -2
- package/dist/migrate/ddl/pgTableDdl.d.ts +5 -1
- package/dist/migrate/ddl/pgTableDdl.js +13 -7
- package/dist/migrate/ddl/tableDdl.d.ts +9 -6
- package/dist/migrate/ddl/tableDdl.js +16 -7
- package/dist/migrate/ddl/tableRebuild.d.ts +2 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +4 -5
- package/dist/migrate/introspection/mysqlIntrospector.js +4 -2
- package/dist/migrate/schemaChange.d.ts +2 -5
- package/dist/migrate/schemaGenerator.js +2 -2
- package/dist/migrate/storage/databaseStorage.js +2 -2
- package/dist/migrate/triggerSql.js +9 -2
- package/dist/mongo/mongoDialect.d.ts +0 -2
- package/dist/mongo/mongoDialect.js +18 -14
- package/dist/mongo/mongodbQuerier.d.ts +13 -5
- package/dist/mongo/mongodbQuerier.js +39 -5
- package/dist/mssql/mssqlDialect.d.ts +9 -4
- package/dist/mssql/mssqlDialect.js +18 -5
- package/dist/postgres/postgresDialect.d.ts +5 -2
- package/dist/postgres/postgresDialect.js +5 -5
- package/dist/querier/abstractQuerier.d.ts +5 -5
- package/dist/querier/abstractQuerier.js +19 -15
- package/dist/querier/abstractQuerierPool.js +22 -22
- package/dist/querier/abstractSqlQuerier.d.ts +3 -3
- package/dist/querier/abstractSqlQuerier.js +7 -7
- package/dist/schema/schemaASTBuilder.js +2 -16
- package/dist/schema/sqlExpression.d.ts +9 -3
- package/dist/schema/sqlExpression.js +14 -0
- package/dist/schema/types.d.ts +2 -5
- package/dist/sqlite/sqliteDialect.d.ts +5 -4
- package/dist/sqlite/sqliteDialect.js +12 -4
- package/dist/type/dialect.d.ts +29 -11
- package/dist/type/dialect.js +2 -0
- package/dist/type/entity.d.ts +20 -5
- package/dist/type/migration.d.ts +7 -8
- package/dist/type/query.d.ts +12 -1
- package/dist/type/universalQuerier.d.ts +3 -3
- package/dist/util/dialect.util.d.ts +1 -1
- package/dist/util/index.d.ts +1 -1
- package/dist/util/index.js +1 -1
- package/dist/util/raw.d.ts +13 -3
- package/dist/util/raw.js +29 -3
- package/dist/util/triggerWrite.d.ts +11 -1
- package/dist/util/triggerWrite.js +14 -0
- package/package.json +10 -10
- package/skills/uql-orm/SKILL.md +22 -52
- package/dist/migrate/builder/expressions.d.ts +0 -63
- package/dist/migrate/builder/expressions.js +0 -142
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -10,11 +10,9 @@ description: >
|
|
|
10
10
|
|
|
11
11
|
# UQL
|
|
12
12
|
|
|
13
|
-
Entities are classes; a query is a JSON object checked key by key against the entity; the same query runs
|
|
14
|
-
on every database UQL supports. There is no schema file, no generated client, and no query builder.
|
|
13
|
+
Entities are classes; a query is a JSON object checked key by key against the entity; the same query runs on every database UQL supports. There is no schema file, no generated client, and no query builder.
|
|
15
14
|
|
|
16
|
-
The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Read the page for the task
|
|
17
|
-
before guessing an option: every page listed there is a `.md` URL.
|
|
15
|
+
The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Read the page for the task before guessing an option: every page listed there is a `.md` URL.
|
|
18
16
|
|
|
19
17
|
## Setup
|
|
20
18
|
|
|
@@ -22,9 +20,7 @@ before guessing an option: every page listed there is a `.md` URL.
|
|
|
22
20
|
npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/client, ...
|
|
23
21
|
```
|
|
24
22
|
|
|
25
|
-
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard:
|
|
26
|
-
never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`.
|
|
27
|
-
In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
23
|
+
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard: never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`. In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
28
24
|
|
|
29
25
|
```ts
|
|
30
26
|
// uql.config.ts
|
|
@@ -37,9 +33,7 @@ export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_U
|
|
|
37
33
|
export default { pool, entities: [User, Post] } satisfies Config;
|
|
38
34
|
```
|
|
39
35
|
|
|
40
|
-
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/maria`, `uql-orm/sqlite`,
|
|
41
|
-
`uql-orm/mongo`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`,
|
|
42
|
-
`uql-orm/bunSql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
36
|
+
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/maria`, `uql-orm/sqlite`, `uql-orm/mongo`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`, `uql-orm/bunSql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
43
37
|
|
|
44
38
|
## Entities
|
|
45
39
|
|
|
@@ -78,16 +72,14 @@ export class Post {
|
|
|
78
72
|
- A column is nullable unless it says `nullable: false`, and its property must admit `null` to match: `title?: string | null`. A property typed without `| null` on a nullable column is a compile error.
|
|
79
73
|
- Declare a `nullable: false` column `!` (`email!: string`): reads have it and inserts must name it, except a single-column key and a `version`, which uql fills. Declare `?` whatever an insert may leave out: a nullable, `onInsert`, `defaultValue`, `eager: false` or `computed` field, and relations.
|
|
80
74
|
- An engine's own column type is a `raw` constant, ``columnType: raw`tsvector` ``, rendered verbatim and carrying its own `length`/`precision`: never a bare string.
|
|
81
|
-
- `defaultValue` is a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`
|
|
75
|
+
- `defaultValue` is a value of the field's type, or SQL the database evaluates per row: one of `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``raw`...` ``. A string is always text, `'CURRENT_TIMESTAMP'` included. The migration builder takes the same.
|
|
82
76
|
- `currentTimestamp` is the database clock, UTC to the millisecond on every engine, where a raw `CURRENT_TIMESTAMP` is not on SQLite, MySQL or SQL Server. Use it for a default, a stamp, `onUpdate` or `$where`.
|
|
83
77
|
- Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
84
78
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
|
|
85
79
|
- `@Index((post) => [post.authorId], { where: { archived: { $ne: true } } })` states a partial index's filter as the predicate the query passes, never as `raw`: a planner matches the two by shape, so `raw` that means the same thing leaves the index unused.
|
|
86
|
-
- `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock:
|
|
87
|
-
|
|
88
|
-
- `@
|
|
89
|
-
`stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
|
|
90
|
-
- `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires. `run(newRow, oldRow)` returns the body, written with `insertInto`, `updateTable` and `deleteFrom`, which are typed by the entity written and render on every engine; anything else is `raw` SQL over the rows, per engine where they differ. A trigger's writes skip uql's fills and entity filters, soft delete included. MongoDB has none. Details, SQL Server's per-statement shape included: https://uql-orm.dev/entities/triggers.md
|
|
80
|
+
- `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock: an update must carry the version it read (a compile error otherwise), and one against a row someone else moved on throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409). Its updates name one row by its id; save and upsert are refused.
|
|
81
|
+
- `@Field({ computed })` is a value the database produces, on a `readonly` property: SQL over the row, ``(u) => raw`${u.first} || ' ' || ${u.last}` ``, or a relation aggregate, `(order) => order.items.count()`. `stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
|
|
82
|
+
- `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires. `run(newRow, oldRow)` returns the body, written with `insertInto`, `upsertInto` (as `upsertOne` takes it), `updateTable`, `deleteFrom` and `refuse(message)` (fails the write), which are typed by the entity written and render on every engine; `deferred: true` fires an after trigger at commit, on Postgres only; anything else is `raw` SQL over the rows, per engine where they differ. A trigger's writes skip uql's fills and entity filters, soft delete included. MongoDB has none. Details, SQL Server's per-statement shape included: https://uql-orm.dev/entities/triggers.md
|
|
91
83
|
- `defineEntity` defines the same entity without decorators: https://uql-orm.dev/entities/imperative.md
|
|
92
84
|
|
|
93
85
|
## Queries
|
|
@@ -106,47 +98,26 @@ const users = await pool.findMany(User, {
|
|
|
106
98
|
});
|
|
107
99
|
```
|
|
108
100
|
|
|
109
|
-
- The keys are `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`;
|
|
110
|
-
|
|
111
|
-
-
|
|
112
|
-
|
|
113
|
-
`NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
|
|
114
|
-
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000
|
|
115
|
-
costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass
|
|
116
|
-
`endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique
|
|
117
|
-
`nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages
|
|
118
|
-
correctly but cannot use an index.
|
|
119
|
-
- `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`,
|
|
120
|
-
`$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`,
|
|
121
|
-
`$isNotNull`. `$and`, `$or`, `$not` and `$nor` combine clauses.
|
|
101
|
+
- The keys are `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`; `$count: { posts: true }` tallies a to-many under `_count` without loading it.
|
|
102
|
+
- `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, and `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'` or `'descNullsLast'` to say where nulls land, which reads the same on every engine (emulated where there is no `NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
|
|
103
|
+
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass `endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique `nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages correctly but cannot use an index.
|
|
104
|
+
- `$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`. `$and`, `$or`, `$not` and `$nor` combine clauses.
|
|
122
105
|
- NULL compares the way the engine compares it: on SQL, `$ne`, `$nin`, `$not` and `$nor` leave out a NULL row, where MongoDB keeps it. Name NULL where you want it, `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`; ask for NULL with `{ col: null }` and its absence with `{ col: { $ne: null } }`.
|
|
123
|
-
- `$text: { $value }` in `$where` searches text on every engine with full-text search, through the entity's
|
|
124
|
-
|
|
125
|
-
relevance, and `{ $text: { $project: 'score' } }` also returns it, typed with `WithProjection<E, 'score'>`.
|
|
126
|
-
- A result is narrowed to what the query selected and populated: reading an unselected field is a compile error.
|
|
127
|
-
Name that shape with `QueryFindResult<User, 'id' | 'email'>` rather than widening the query.
|
|
106
|
+
- `$text: { $value }` in `$where` searches text on every engine with full-text search, through the entity's `@Index(..., { type: 'fulltext', config })`, whose columns may carry a `weight`. `$sort: { $text: 'desc' }` ranks by relevance, and `{ $text: { $project: 'score' } }` also returns it, typed with `WithProjection<E, 'score'>`.
|
|
107
|
+
- A result is narrowed to what the query selected and populated: reading an unselected field is a compile error. Name that shape with `QueryFindResult<User, 'id' | 'email'>` rather than widening the query.
|
|
128
108
|
- `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
|
|
129
|
-
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`,
|
|
130
|
-
|
|
131
|
-
-
|
|
132
|
-
`aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`,
|
|
133
|
-
`upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first.
|
|
109
|
+
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`, whose handler serves only the entities its required `include` names.
|
|
110
|
+
- 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.
|
|
111
|
+
- `upsertOne(Entity, { email: true }, row, { update })`: a conflicting row takes `update`, an update's payload with its operators, instead of `row`; a new one inserts `row`. `{ update: {} }` leaves a conflicting row as it is: insert if absent.
|
|
134
112
|
- `updateMany` and `deleteMany` naming no rows - no `$where` holding a value (an `undefined` or an empty group holds none), no `$limit` - throw; `{ unfiltered: true }` means the whole table.
|
|
135
|
-
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0,
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row
|
|
139
|
-
someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and
|
|
140
|
-
refuse it.
|
|
141
|
-
- `queryErrorKind(err)` names any failure the same on every engine - `uniqueViolation`, `foreignKeyViolation`,
|
|
142
|
-
`notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security` - so catch by kind
|
|
143
|
-
rather than by a driver's code or an `instanceof`. Every error UQL raises itself is a `UqlError`.
|
|
113
|
+
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0, so a guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. On SQL the step may be a ref or `raw` of the field's type (`{ total: { $inc: newRow.amount } }` in a trigger). JSON fields take `$set`, `$unset`, `$push`, `$pull`.
|
|
114
|
+
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
|
|
115
|
+
- `queryErrorKind(err)` names any failure the same on every engine - `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security` - so catch by kind rather than by a driver's code or an `instanceof`. Every error UQL raises itself is a `UqlError`.
|
|
144
116
|
- `raw()` embeds SQL anywhere a value or field goes; `pool.all(sql, values)` runs a raw `SELECT`. A field read off `refs(Entity)` carries its type: on its own as a value it fits only a field of that type.
|
|
145
117
|
|
|
146
118
|
## Connections and transactions
|
|
147
119
|
|
|
148
|
-
Every method is on both the pool and a querier. A pool call acquires a connection for that call and releases it.
|
|
149
|
-
To run several operations on one connection, or atomically, hold a querier:
|
|
120
|
+
Every method is on both the pool and a querier. A pool call acquires a connection for that call and releases it. To run several operations on one connection, or atomically, hold a querier:
|
|
150
121
|
|
|
151
122
|
```ts
|
|
152
123
|
await pool.transaction(async (querier) => {
|
|
@@ -155,8 +126,7 @@ await pool.transaction(async (querier) => {
|
|
|
155
126
|
});
|
|
156
127
|
```
|
|
157
128
|
|
|
158
|
-
Inside the callback, call `querier`, never `pool`: a `pool` call runs on another connection, outside the
|
|
159
|
-
transaction. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
129
|
+
Inside the callback, call `querier`, never `pool`: a `pool` call runs on another connection, outside the transaction. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
160
130
|
|
|
161
131
|
## Migrations
|
|
162
132
|
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import type { AbstractSqlDialect } from '../../dialect/index.js';
|
|
2
|
-
import { SqlExpression, type SqlExpressionKind } from '../../schema/sqlExpression.js';
|
|
3
|
-
import type { SqlDialectName } from '../../type/index.js';
|
|
4
|
-
export { SqlExpression, type SqlExpressionKind };
|
|
5
|
-
/**
|
|
6
|
-
* Each kind's DDL spelling, or `null` where the engine has none. `raw` carries its own SQL instead. `now`
|
|
7
|
-
* defaults to the dialect's `currentTimestamp`, the clock every other statement reads, unless set here.
|
|
8
|
-
*/
|
|
9
|
-
export type SqlExpressionMap = Readonly<Record<Exclude<SqlExpressionKind, 'raw' | 'now'>, string | null>> & {
|
|
10
|
-
readonly now?: string;
|
|
11
|
-
};
|
|
12
|
-
/** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
|
|
13
|
-
export type DialectDefaults = {
|
|
14
|
-
/** Spelling of each kind, `null` where the engine has none. */
|
|
15
|
-
readonly expressions: SqlExpressionMap;
|
|
16
|
-
/** Column types whose `DEFAULT` this engine takes only as a parenthesized expression. */
|
|
17
|
-
readonly wrapTypes?: RegExp;
|
|
18
|
-
/** Column types whose `CURRENT_TIMESTAMP` default must repeat their precision, captured by the pattern. */
|
|
19
|
-
readonly preciseTypes?: RegExp;
|
|
20
|
-
};
|
|
21
|
-
/**
|
|
22
|
-
* Looked up by name rather than carried on the dialect, which keeps DDL data out of the query
|
|
23
|
-
* bundle - the same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`. `uuidv7()` is
|
|
24
|
-
* Postgres 18+ and `UUID_v7()` MariaDB 11.7+; a server below those rejects it itself, the version
|
|
25
|
-
* not being knowable here.
|
|
26
|
-
*/
|
|
27
|
-
export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDefaults>>;
|
|
28
|
-
/**
|
|
29
|
-
* Symbolic DDL defaults. Each builds a token the dialect spells at DDL time, so `expr.uuid()` is
|
|
30
|
-
* `gen_random_uuid()` on Postgres and `UUID()` on MySQL from one migration.
|
|
31
|
-
*
|
|
32
|
-
* Use in migrations: `t.timestamp('createdAt', { defaultValue: expr.now() })`
|
|
33
|
-
*/
|
|
34
|
-
export declare const expr: {
|
|
35
|
-
/** Current timestamp. */
|
|
36
|
-
now: () => SqlExpression;
|
|
37
|
-
/** Current date. */
|
|
38
|
-
currentDate: () => SqlExpression;
|
|
39
|
-
/** Current time. */
|
|
40
|
-
currentTime: () => SqlExpression;
|
|
41
|
-
/** Generated UUID. SQLite has no built-in one and throws; pass `expr.raw` there. */
|
|
42
|
-
uuid: () => SqlExpression;
|
|
43
|
-
/**
|
|
44
|
-
* Time-ordered UUID, which indexes far better than a random one as a key. Postgres 18+ and
|
|
45
|
-
* MariaDB 11.7+ only; MySQL, SQLite and CockroachDB have no such function and throw.
|
|
46
|
-
*/
|
|
47
|
-
uuidv7: () => SqlExpression;
|
|
48
|
-
/** MySQL's `ON UPDATE CURRENT_TIMESTAMP`. Throws on dialects without it. */
|
|
49
|
-
onUpdateNow: () => SqlExpression;
|
|
50
|
-
/** SQL taken verbatim, for anything the kinds above do not cover. Not portable by definition. */
|
|
51
|
-
raw: (sql: string) => SqlExpression;
|
|
52
|
-
};
|
|
53
|
-
/**
|
|
54
|
-
* The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
|
|
55
|
-
* else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
|
|
56
|
-
* the result needs wrapping, which MySQL demands on its large types whatever the value.
|
|
57
|
-
*/
|
|
58
|
-
export declare function formatDefaultValue(value: unknown, dialect: AbstractSqlDialect, columnType?: string): string;
|
|
59
|
-
/**
|
|
60
|
-
* Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
|
|
61
|
-
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
62
|
-
*/
|
|
63
|
-
export declare function sameDefault(desired: unknown, current: unknown, dialect: AbstractSqlDialect): boolean;
|
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
import { SqlExpression, writtenDefault } from '../../schema/sqlExpression.js';
|
|
2
|
-
import { UqlUsageError } from '../../util/uqlError.js';
|
|
3
|
-
export { SqlExpression };
|
|
4
|
-
const ANSI = {
|
|
5
|
-
currentDate: 'CURRENT_DATE',
|
|
6
|
-
currentTime: 'CURRENT_TIME',
|
|
7
|
-
uuid: null,
|
|
8
|
-
uuidv7: null,
|
|
9
|
-
onUpdateNow: null,
|
|
10
|
-
};
|
|
11
|
-
const PG = { ...ANSI, uuid: 'gen_random_uuid()' };
|
|
12
|
-
const MYSQL = {
|
|
13
|
-
...ANSI,
|
|
14
|
-
// Bare, unlike the dialect's `CURRENT_TIMESTAMP(3)`: `preciseTypes` adds the column's own precision.
|
|
15
|
-
now: 'CURRENT_TIMESTAMP',
|
|
16
|
-
uuid: 'UUID()',
|
|
17
|
-
onUpdateNow: 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
|
|
18
|
-
};
|
|
19
|
-
/** MySQL 8.0.13+ rejects `DEFAULT 'x'` on these but accepts `DEFAULT ('x')`, whatever the value. */
|
|
20
|
-
const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY)\b/i;
|
|
21
|
-
/** A `DATETIME(3)` or `TIMESTAMP(3)`, whose fractional-second precision is captured. */
|
|
22
|
-
const MYSQL_PRECISE_TYPES = /^\s*(?:DATETIME|TIMESTAMP)\((\d)\)/i;
|
|
23
|
-
/**
|
|
24
|
-
* Looked up by name rather than carried on the dialect, which keeps DDL data out of the query
|
|
25
|
-
* bundle - the same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`. `uuidv7()` is
|
|
26
|
-
* Postgres 18+ and `UUID_v7()` MariaDB 11.7+; a server below those rejects it itself, the version
|
|
27
|
-
* not being knowable here.
|
|
28
|
-
*/
|
|
29
|
-
export const DIALECT_DEFAULTS = {
|
|
30
|
-
postgres: { expressions: { ...PG, uuidv7: 'uuidv7()' } },
|
|
31
|
-
cockroachdb: { expressions: PG },
|
|
32
|
-
mysql: { expressions: MYSQL, wrapTypes: MYSQL_LARGE_TYPES, preciseTypes: MYSQL_PRECISE_TYPES },
|
|
33
|
-
mariadb: {
|
|
34
|
-
expressions: { ...MYSQL, uuidv7: 'UUID_v7()' },
|
|
35
|
-
wrapTypes: MYSQL_LARGE_TYPES,
|
|
36
|
-
preciseTypes: MYSQL_PRECISE_TYPES,
|
|
37
|
-
},
|
|
38
|
-
// Writes today in the same text as a bound `Date` at UTC midnight; `CURRENT_DATE` writes a different text.
|
|
39
|
-
sqlite: { expressions: { ...ANSI, currentDate: "(strftime('%Y-%m-%d 00:00:00.000', 'now'))" } },
|
|
40
|
-
// No `uuidv7`: `NEWSEQUENTIALID()` is an ordered v4 GUID, so it carries no readable timestamp and
|
|
41
|
-
// does not sort the way a v7 does elsewhere - a `uuidv7()` default is refused rather than served
|
|
42
|
-
// something that only looks like one.
|
|
43
|
-
mssql: { expressions: { ...ANSI, uuid: 'NEWID()' } },
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* Symbolic DDL defaults. Each builds a token the dialect spells at DDL time, so `expr.uuid()` is
|
|
47
|
-
* `gen_random_uuid()` on Postgres and `UUID()` on MySQL from one migration.
|
|
48
|
-
*
|
|
49
|
-
* Use in migrations: `t.timestamp('createdAt', { defaultValue: expr.now() })`
|
|
50
|
-
*/
|
|
51
|
-
export const expr = {
|
|
52
|
-
/** Current timestamp. */
|
|
53
|
-
now: () => new SqlExpression('now'),
|
|
54
|
-
/** Current date. */
|
|
55
|
-
currentDate: () => new SqlExpression('currentDate'),
|
|
56
|
-
/** Current time. */
|
|
57
|
-
currentTime: () => new SqlExpression('currentTime'),
|
|
58
|
-
/** Generated UUID. SQLite has no built-in one and throws; pass `expr.raw` there. */
|
|
59
|
-
uuid: () => new SqlExpression('uuid'),
|
|
60
|
-
/**
|
|
61
|
-
* Time-ordered UUID, which indexes far better than a random one as a key. Postgres 18+ and
|
|
62
|
-
* MariaDB 11.7+ only; MySQL, SQLite and CockroachDB have no such function and throw.
|
|
63
|
-
*/
|
|
64
|
-
uuidv7: () => new SqlExpression('uuidv7'),
|
|
65
|
-
/** MySQL's `ON UPDATE CURRENT_TIMESTAMP`. Throws on dialects without it. */
|
|
66
|
-
onUpdateNow: () => new SqlExpression('onUpdateNow'),
|
|
67
|
-
/** SQL taken verbatim, for anything the kinds above do not cover. Not portable by definition. */
|
|
68
|
-
raw: (sql) => new SqlExpression('raw', sql),
|
|
69
|
-
};
|
|
70
|
-
/**
|
|
71
|
-
* The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
|
|
72
|
-
* else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
|
|
73
|
-
* the result needs wrapping, which MySQL demands on its large types whatever the value.
|
|
74
|
-
*/
|
|
75
|
-
export function formatDefaultValue(value, dialect, columnType) {
|
|
76
|
-
const sql = defaultLiteral(value, dialect, columnType);
|
|
77
|
-
const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
|
|
78
|
-
return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
|
|
82
|
-
* and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
|
|
83
|
-
*/
|
|
84
|
-
export function sameDefault(desired, current, dialect) {
|
|
85
|
-
// Both spellings of "no default" are the same fact, and engines disagree on which they report:
|
|
86
|
-
// MariaDB says `null` where MySQL says nothing at all. Reading them as different values asked to
|
|
87
|
-
// `MODIFY` every nullable column, on every sync, forever.
|
|
88
|
-
if (desired == null || current == null)
|
|
89
|
-
return desired == null && current == null;
|
|
90
|
-
if (SqlExpression.isExpression(desired) || SqlExpression.isExpression(current)) {
|
|
91
|
-
return (SqlExpression.isExpression(desired) &&
|
|
92
|
-
SqlExpression.isExpression(current) &&
|
|
93
|
-
reprinted(formatDefaultValue(desired, dialect)) === reprinted(formatDefaultValue(current, dialect)));
|
|
94
|
-
}
|
|
95
|
-
// Compared as text, since a catalogue may report a number either as a number or as its text.
|
|
96
|
-
return writtenDefault(desired) === writtenDefault(current);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Normalizes what engines reprint differently in SQL: it lowercases, collapses spacing, and strips wrapping
|
|
100
|
-
* parentheses (SQLite and MySQL drop them, SQL Server adds them) and the empty argument list of
|
|
101
|
-
* CockroachDB's `current_timestamp()`.
|
|
102
|
-
*/
|
|
103
|
-
function reprinted(sql) {
|
|
104
|
-
let text = sql
|
|
105
|
-
.toLowerCase()
|
|
106
|
-
.replace(/\s*([(),])\s*/g, '$1')
|
|
107
|
-
.replace(/\s+/g, ' ')
|
|
108
|
-
.trim();
|
|
109
|
-
while (/^\(.*\)$/s.test(text)) {
|
|
110
|
-
text = text.slice(1, -1);
|
|
111
|
-
}
|
|
112
|
-
return text.replace(/\(\)$/, '');
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* Quoting is the dialect's `escape`, so a backslash in a default is escaped the way the engine reads
|
|
116
|
-
* it - MySQL takes `'a\b'` as a backspace where Postgres takes it literally. Only the cases `escape`
|
|
117
|
-
* cannot serve stay here: a boolean is `1` where booleans are integers, and a plain object or array
|
|
118
|
-
* is JSON rather than the throw and the IN-list `escape` gives them.
|
|
119
|
-
*/
|
|
120
|
-
function defaultLiteral(value, dialect, columnType) {
|
|
121
|
-
if (value === undefined || value === null) {
|
|
122
|
-
return 'NULL';
|
|
123
|
-
}
|
|
124
|
-
if (SqlExpression.isExpression(value)) {
|
|
125
|
-
return expressionSql(value, dialect, columnType);
|
|
126
|
-
}
|
|
127
|
-
if (typeof value === 'boolean') {
|
|
128
|
-
return dialect.booleanLiteral === 'native' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0';
|
|
129
|
-
}
|
|
130
|
-
return dialect.escape(typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : value);
|
|
131
|
-
}
|
|
132
|
-
function expressionSql(expression, dialect, columnType) {
|
|
133
|
-
const { expressions, preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
|
|
134
|
-
const raw = expression.kind === 'raw';
|
|
135
|
-
const sql = raw ? expression.sql : { now: dialect.currentTimestamp, ...expressions }[expression.kind];
|
|
136
|
-
if (sql == null) {
|
|
137
|
-
throw new UqlUsageError(`${dialect.dialectName} has no '${expression.kind}' default; pass expr.raw(...) with SQL this engine accepts`);
|
|
138
|
-
}
|
|
139
|
-
// A raw default is the caller's SQL, never rewritten.
|
|
140
|
-
const precision = raw || columnType === undefined ? undefined : preciseTypes?.exec(columnType)?.[1];
|
|
141
|
-
return precision === undefined ? sql : sql.replaceAll('CURRENT_TIMESTAMP', `CURRENT_TIMESTAMP(${precision})`);
|
|
142
|
-
}
|