uql-orm 0.83.1 → 0.85.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/README.md +30 -9
- package/dist/betterAuth/authEntities.d.ts +7 -0
- package/dist/betterAuth/authEntities.js +154 -0
- package/dist/betterAuth/index.d.ts +2 -0
- package/dist/betterAuth/index.js +2 -0
- package/dist/betterAuth/uqlAdapter.d.ts +16 -0
- package/dist/betterAuth/uqlAdapter.js +155 -0
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +4 -4
- package/dist/context/context.browser.d.ts +0 -1
- package/dist/context/context.browser.js +0 -1
- package/dist/context/context.d.ts +0 -1
- package/dist/context/context.js +0 -1
- package/dist/d1/d1SqliteDialect.js +1 -1
- package/dist/dialect/mysqlLikeSqlDialect.js +1 -0
- package/dist/dialect/pgLikeSqlDialect.js +1 -0
- package/dist/http/fetchHandler.js +2 -1
- package/dist/http/handler.d.ts +7 -3
- package/dist/http/handler.js +101 -105
- package/dist/http/query.d.ts +8 -1
- package/dist/http/query.js +8 -7
- package/dist/mongo/mongoDialect.js +1 -0
- package/dist/mssql/mssqlDialect.js +1 -0
- package/dist/querier/abstractQuerier.d.ts +11 -3
- package/dist/querier/abstractQuerier.js +55 -8
- package/dist/querier/queryError.js +2 -2
- package/dist/sqlite/sqliteDialect.js +1 -0
- package/dist/type/dialect.d.ts +5 -0
- package/dist/util/dialect.util.d.ts +13 -2
- package/dist/util/dialect.util.js +59 -40
- package/dist/util/uqlError.d.ts +19 -8
- package/dist/util/uqlError.js +15 -6
- package/package.json +10 -3
- package/skills/uql-orm/SKILL.md +12 -3
- package/dist/context/securityError.d.ts +0 -4
- package/dist/context/securityError.js +0 -4
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
</picture>
|
|
8
8
|
</a>
|
|
9
9
|
|
|
10
|
-
<h3>
|
|
10
|
+
<h3>JSON-native ORM for TypeScript</h3>
|
|
11
11
|
|
|
12
12
|
<p align="left">UQL queries SQL databases and MongoDB with plain, type-safe JSON-syntax.
|
|
13
13
|
</p>
|
|
@@ -121,19 +121,42 @@ const posts = await pool.findMany(Post, {
|
|
|
121
121
|
|
|
122
122
|
The result is typed to what the query selected: `posts[0].author?.email` compiles, `posts[0].likes` does not.
|
|
123
123
|
|
|
124
|
-
### 4.
|
|
124
|
+
### 4. Or serve it over HTTP, scoped to the signed-in user
|
|
125
125
|
|
|
126
126
|
```ts
|
|
127
127
|
// server.ts: Bun, Deno, Cloudflare Workers, or any framework that takes a fetch handler
|
|
128
|
+
import { defineFilter } from 'uql-orm';
|
|
128
129
|
import { createFetchHandler } from 'uql-orm/http';
|
|
129
|
-
import {
|
|
130
|
+
import { authenticate } from './auth.js';
|
|
131
|
+
import { Post } from './entities.js';
|
|
130
132
|
import { pool } from './uql.config.js';
|
|
131
133
|
|
|
132
|
-
|
|
134
|
+
declare module 'uql-orm' {
|
|
135
|
+
interface UqlContext {
|
|
136
|
+
userId?: number;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Scopes every read and write on Post: no `$where` widens it, a new post gets `authorId`, and with no user it throws.
|
|
141
|
+
defineFilter(Post, 'ownPosts', {
|
|
142
|
+
where: (ctx) => (ctx?.userId != null ? { authorId: ctx.userId } : undefined),
|
|
143
|
+
security: true,
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
export default {
|
|
147
|
+
fetch: createFetchHandler({
|
|
148
|
+
pool,
|
|
149
|
+
include: [Post],
|
|
150
|
+
// From your verified session, never from client input.
|
|
151
|
+
getContext: async (request) => ({ userId: (await authenticate(request)).userId }),
|
|
152
|
+
}),
|
|
153
|
+
};
|
|
133
154
|
```
|
|
134
155
|
|
|
156
|
+
The client sends a query as JSON and gets the same typed result, never touching the database:
|
|
157
|
+
|
|
135
158
|
```ts
|
|
136
|
-
//
|
|
159
|
+
// client.ts
|
|
137
160
|
import { HttpQuerier } from 'uql-orm/browser';
|
|
138
161
|
import { Post } from './entities.js';
|
|
139
162
|
|
|
@@ -141,15 +164,13 @@ const api = new HttpQuerier('https://api.example.com');
|
|
|
141
164
|
|
|
142
165
|
const { data: posts } = await api.findMany(Post, {
|
|
143
166
|
$select: { title: true },
|
|
144
|
-
$populate: { author: { $select: { email: true } } },
|
|
145
167
|
$where: { likes: { $gte: 10 } },
|
|
146
168
|
$sort: { likes: 'desc' },
|
|
147
169
|
$limit: 10,
|
|
148
170
|
});
|
|
149
|
-
// GET /post?$select={"title":true}&$populate={"author":{"$select":{"email":true}}}&$where={"likes":{"$gte":10}}&$sort={"likes":"desc"}&$limit=10
|
|
150
171
|
```
|
|
151
172
|
|
|
152
|
-
|
|
173
|
+
Only the entities in `include` are served: a `$populate: { author: true }` here is a `400`, as `User` is not. More in [HTTP](https://uql-orm.dev/http) and [multi-tenancy](https://uql-orm.dev/multi-tenancy).
|
|
153
174
|
|
|
154
175
|
### When CRUD is not enough
|
|
155
176
|
|
|
@@ -164,7 +185,7 @@ The query object is the same on both sides, and so is its type check. Authorizat
|
|
|
164
185
|
- **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
|
|
165
186
|
- **Relations without N+1.** [`$populate`](https://uql-orm.dev/querying/relations) reads a to-many inside the parent's statement, so a read is one round trip. Nothing is lazy, so nothing fires behind your back in a serializer.
|
|
166
187
|
- **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 27 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
|
|
167
|
-
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [multi-tenant filters you cannot bypass by accident](https://uql-orm.dev/multi-tenancy), [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming),
|
|
188
|
+
- **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [multi-tenant filters you cannot bypass by accident](https://uql-orm.dev/multi-tenancy), [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming), [drift checks](https://uql-orm.dev/migrations) that catch a database that no longer matches, and [Better Auth](https://uql-orm.dev/better-auth) on every engine.
|
|
168
189
|
- **The fastest ORM.** On a full PostgreSQL round trip it adds the least over hand-written driver code of any ORM in our open-source [benchmark](https://github.com/rogerpadilla/ts-orm-benchmark), on Bun, Node and Deno alike. The same benchmark [scores the types](https://github.com/rogerpadilla/ts-orm-benchmark#type-safety) by compiling ordinary mistakes in each ORM's API: UQL is the only one that catches them all.
|
|
169
190
|
|
|
170
191
|
## Get started
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from 'better-auth';
|
|
2
|
+
import type { Type } from '../type/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* The entities Better Auth's tables are for these options, its core tables and every plugin's: list them
|
|
5
|
+
* in `uql.config.ts` so `uql-migrate` creates and migrates them with the rest.
|
|
6
|
+
*/
|
|
7
|
+
export declare function authEntities(options: BetterAuthOptions): Type<object>[];
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { getAuthTables } from 'better-auth/db';
|
|
2
|
+
import { defineEntity, defineField, defineId, defineIndex, defineRelation } from '../entity/index.js';
|
|
3
|
+
import { UqlUsageError } from '../util/uqlError.js';
|
|
4
|
+
/**
|
|
5
|
+
* The entities Better Auth's tables are for these options, its core tables and every plugin's: list them
|
|
6
|
+
* in `uql.config.ts` so `uql-migrate` creates and migrates them with the rest.
|
|
7
|
+
*/
|
|
8
|
+
export function authEntities(options) {
|
|
9
|
+
const shapes = shapesOf(options);
|
|
10
|
+
// A field type that is a constructor keyed by its name, which JSON would drop.
|
|
11
|
+
const key = JSON.stringify(shapes, (_, value) => (typeof value === 'function' ? value.name : value));
|
|
12
|
+
let entities = defined.get(key);
|
|
13
|
+
if (!entities) {
|
|
14
|
+
entities = defineTables(shapes);
|
|
15
|
+
defined.set(key, entities);
|
|
16
|
+
}
|
|
17
|
+
return [...entities];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Each set of tables defined so far, by its shapes: kept, since an adapter built on it may still be
|
|
21
|
+
* reading, and a table defined twice for one shape would be two entities over one table.
|
|
22
|
+
*/
|
|
23
|
+
const defined = new Map();
|
|
24
|
+
/** Defines every table at once, since each one's foreign keys point at the others. */
|
|
25
|
+
function defineTables(shapes) {
|
|
26
|
+
const byName = Object.fromEntries(shapes.map(({ name }) => [
|
|
27
|
+
name,
|
|
28
|
+
{
|
|
29
|
+
[name]: class {
|
|
30
|
+
},
|
|
31
|
+
}[name],
|
|
32
|
+
]));
|
|
33
|
+
for (const { name, id, fields, indexes } of shapes) {
|
|
34
|
+
const entity = byName[name];
|
|
35
|
+
defineId(entity, 'id', id);
|
|
36
|
+
for (const field of fields) {
|
|
37
|
+
defineField(entity, field.name, field.options);
|
|
38
|
+
const { references } = field;
|
|
39
|
+
if (references) {
|
|
40
|
+
defineRelation(entity, `${field.name}Ref`, {
|
|
41
|
+
entity: () => byName[references.table],
|
|
42
|
+
cardinality: 'm1',
|
|
43
|
+
references: (local, foreign) => [{ local: local[field.name], foreign: foreign[references.column] }],
|
|
44
|
+
onDelete: references.onDelete,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
for (const index of indexes) {
|
|
49
|
+
defineIndex(entity, { ...index, columns: (refs) => index.columns.map((column) => refs[column]) });
|
|
50
|
+
}
|
|
51
|
+
defineEntity(entity, { name });
|
|
52
|
+
}
|
|
53
|
+
return Object.values(byName);
|
|
54
|
+
}
|
|
55
|
+
/** Better Auth's schema as the tables UQL defines, every reference resolved to the column it points at. */
|
|
56
|
+
function shapesOf(options) {
|
|
57
|
+
const schema = getAuthTables(options);
|
|
58
|
+
const id = keyOf(options);
|
|
59
|
+
const columnOf = (fields, key) => fields[key]?.fieldName ?? key;
|
|
60
|
+
// Refused rather than left for the schema build, which drops a foreign key whose column it cannot find.
|
|
61
|
+
const referenceOf = ({ model, field, onDelete = 'cascade' }) => {
|
|
62
|
+
const table = schema[model] ?? Object.values(schema).find(({ modelName }) => modelName === model);
|
|
63
|
+
const column = table?.fields[field];
|
|
64
|
+
if (!table || (field !== 'id' && !column)) {
|
|
65
|
+
throw new UqlUsageError(`a Better Auth field references '${model}.${field}', which its schema does not have`);
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
// Every foreign key is indexed, so it takes the type an indexed copy of the column it points at would.
|
|
69
|
+
type: column ? typeOf({ ...column, index: true }) : id.type,
|
|
70
|
+
references: {
|
|
71
|
+
table: table.modelName,
|
|
72
|
+
column: column ? columnOf(table.fields, field) : 'id',
|
|
73
|
+
onDelete: ON_DELETE[onDelete],
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
return Object.values(schema).map((table) => ({
|
|
78
|
+
name: table.modelName,
|
|
79
|
+
id,
|
|
80
|
+
fields: Object.entries(table.fields).map(([key, field]) => {
|
|
81
|
+
const name = columnOf(table.fields, key);
|
|
82
|
+
const reference = field.references && referenceOf(field.references);
|
|
83
|
+
return {
|
|
84
|
+
name,
|
|
85
|
+
options: {
|
|
86
|
+
name,
|
|
87
|
+
type: reference?.type ?? typeOf(field),
|
|
88
|
+
nullable: field.required === false,
|
|
89
|
+
unique: field.unique,
|
|
90
|
+
index: field.index,
|
|
91
|
+
defaultValue: staticDefault(field),
|
|
92
|
+
},
|
|
93
|
+
references: reference?.references,
|
|
94
|
+
};
|
|
95
|
+
}),
|
|
96
|
+
indexes: (table.indexes ?? []).map(({ fields, unique, name }) => ({
|
|
97
|
+
columns: fields.map((key) => columnOf(table.fields, key)),
|
|
98
|
+
unique,
|
|
99
|
+
name,
|
|
100
|
+
})),
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
/** The key: Better Auth's own string, its UUID, or the database's number; a key left to the database otherwise is refused. */
|
|
104
|
+
function keyOf(options) {
|
|
105
|
+
const generateId = options.advanced?.database?.generateId;
|
|
106
|
+
if (generateId === false) {
|
|
107
|
+
throw new UqlUsageError("Better Auth's 'generateId: false' leaves the key to the database, which it can generate in more than one " +
|
|
108
|
+
"way: set 'serial' for a number or 'uuid' for a UUID");
|
|
109
|
+
}
|
|
110
|
+
if (generateId === 'serial') {
|
|
111
|
+
return { type: Number, autoIncrement: true };
|
|
112
|
+
}
|
|
113
|
+
return { type: generateId === 'uuid' ? 'uuid' : String };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* A field's column type. Text is `text` unless something indexes it, which a column of unbounded length
|
|
117
|
+
* cannot be on MySQL; a list of allowed values is text too, since Better Auth checks them itself and a
|
|
118
|
+
* database check on them would need a migration each time one is added.
|
|
119
|
+
*/
|
|
120
|
+
function typeOf(field) {
|
|
121
|
+
const { type } = field;
|
|
122
|
+
if (type === 'string' || Array.isArray(type)) {
|
|
123
|
+
return field.unique || field.index || field.sortable ? String : 'text';
|
|
124
|
+
}
|
|
125
|
+
switch (type) {
|
|
126
|
+
case 'number':
|
|
127
|
+
return field.bigint ? BigInt : Number;
|
|
128
|
+
case 'boolean':
|
|
129
|
+
return Boolean;
|
|
130
|
+
case 'date':
|
|
131
|
+
return Date;
|
|
132
|
+
case 'json':
|
|
133
|
+
case 'string[]':
|
|
134
|
+
case 'number[]':
|
|
135
|
+
return 'json';
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The default a column takes in the database, as Better Auth's own migrator gives one: a plain value on a
|
|
140
|
+
* text, number or boolean field, so a required column added to a populated table has one to backfill. A
|
|
141
|
+
* nullable unique column gets none, `NULL` being its only backfill two rows can share.
|
|
142
|
+
*/
|
|
143
|
+
function staticDefault({ type, defaultValue, unique, required }) {
|
|
144
|
+
const plain = typeof defaultValue === 'string' || typeof defaultValue === 'number' || typeof defaultValue === 'boolean';
|
|
145
|
+
const typed = type === 'string' || type === 'number' || type === 'boolean';
|
|
146
|
+
return plain && typed && !(unique && required === false) ? defaultValue : undefined;
|
|
147
|
+
}
|
|
148
|
+
const ON_DELETE = {
|
|
149
|
+
cascade: 'CASCADE',
|
|
150
|
+
'no action': 'NO ACTION',
|
|
151
|
+
restrict: 'RESTRICT',
|
|
152
|
+
'set null': 'SET NULL',
|
|
153
|
+
'set default': 'SET DEFAULT',
|
|
154
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from 'better-auth';
|
|
2
|
+
import { type DBAdapter, type DBAdapterDebugLogOption } from 'better-auth/adapters';
|
|
3
|
+
import type { QuerierPool } from '../type/index.js';
|
|
4
|
+
export type UqlAdapterOptions = {
|
|
5
|
+
readonly debugLogs?: DBAdapterDebugLogOption;
|
|
6
|
+
/**
|
|
7
|
+
* Whether Better Auth runs its multi-step writes in one transaction: on wherever the engine has them,
|
|
8
|
+
* so off on D1. A standalone MongoDB, which has them only as a replica set, needs `false`.
|
|
9
|
+
*/
|
|
10
|
+
readonly transaction?: boolean;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Better Auth on a UQL pool, on every engine UQL runs on: `betterAuth({ database: uqlAdapter(pool) })`.
|
|
14
|
+
* Its tables are the entities {@link authEntities} returns, which `uql-migrate` creates like any other.
|
|
15
|
+
*/
|
|
16
|
+
export declare function uqlAdapter(pool: QuerierPool, opts?: UqlAdapterOptions): (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createAdapterFactory, } from 'better-auth/adapters';
|
|
2
|
+
import { likeLiteral } from '../dialect/operators.js';
|
|
3
|
+
import { getMeta, idOf } from '../entity/index.js';
|
|
4
|
+
import { whereIds } from '../util/dialect.util.js';
|
|
5
|
+
import { entityName } from '../util/object.util.js';
|
|
6
|
+
import { UqlUsageError } from '../util/uqlError.js';
|
|
7
|
+
import { authEntities } from './authEntities.js';
|
|
8
|
+
/**
|
|
9
|
+
* Better Auth on a UQL pool, on every engine UQL runs on: `betterAuth({ database: uqlAdapter(pool) })`.
|
|
10
|
+
* Its tables are the entities {@link authEntities} returns, which `uql-migrate` creates like any other.
|
|
11
|
+
*/
|
|
12
|
+
export function uqlAdapter(pool, opts = {}) {
|
|
13
|
+
const transactions = opts.transaction ?? pool.dialect.features.transactions;
|
|
14
|
+
return (options) => {
|
|
15
|
+
const entities = Object.fromEntries(authEntities(options).map((entity) => [entityName(getMeta(entity)), entity]));
|
|
16
|
+
const on = (querier, inTransaction) => createAdapterFactory({
|
|
17
|
+
config: {
|
|
18
|
+
adapterId: 'uql',
|
|
19
|
+
adapterName: 'UQL',
|
|
20
|
+
debugLogs: opts.debugLogs,
|
|
21
|
+
supportsJSON: true,
|
|
22
|
+
supportsDates: true,
|
|
23
|
+
supportsBooleans: true,
|
|
24
|
+
supportsNumericIds: true,
|
|
25
|
+
supportsArrays: true,
|
|
26
|
+
// The same adapter over the transaction's querier, as Better Auth's own adapters rebuild theirs.
|
|
27
|
+
transaction: transactions && !inTransaction ? (callback) => pool.transaction((trx) => callback(on(trx, true))) : false,
|
|
28
|
+
},
|
|
29
|
+
adapter: ({ getFieldName }) => methodsOf(querier, entities, getFieldName),
|
|
30
|
+
})(options);
|
|
31
|
+
return on(pool, false);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Better Auth's database methods over `querier`, its tables by the names its factory checked each `model`
|
|
36
|
+
* against. Only `where` arrives in database names; the rest are mapped here.
|
|
37
|
+
*/
|
|
38
|
+
function methodsOf(querier, entities, getFieldName) {
|
|
39
|
+
const select = (model, fields) => fields?.length ? Object.fromEntries(fields.map((field) => [getFieldName({ model, field }), true])) : undefined;
|
|
40
|
+
const filter = (where) => ({ $where: whereOf(where) });
|
|
41
|
+
/**
|
|
42
|
+
* Writes `payload` to the first row `where` finds, pinned to that row while it still matches `where`,
|
|
43
|
+
* and reads it back: `null` where none matched, or a concurrent write moved the row past the guard first.
|
|
44
|
+
*/
|
|
45
|
+
const updateOne = async (model, where, payload) => {
|
|
46
|
+
const entity = entities[model];
|
|
47
|
+
const row = await querier.findOne(entity, filter(where));
|
|
48
|
+
if (!row) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const meta = getMeta(entity);
|
|
52
|
+
const id = idOf(meta, row);
|
|
53
|
+
const pinned = { $where: { $and: [whereOf(where), whereIds(meta, id)] } };
|
|
54
|
+
const changed = await querier.updateMany(entity, pinned, payload);
|
|
55
|
+
return changed ? asRow(await querier.findOneById(entity, id)) : null;
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
async create({ model, data }) {
|
|
59
|
+
const entity = entities[model];
|
|
60
|
+
const id = await querier.insertOne(entity, data);
|
|
61
|
+
// The row as stored, which Better Auth's SQL adapters return too: a column left out reads its default.
|
|
62
|
+
const row = id === undefined ? undefined : await querier.findOneById(entity, id);
|
|
63
|
+
if (!row) {
|
|
64
|
+
throw new UqlUsageError(`Better Auth inserted a '${model}' row it cannot read back: does a filter hide it?`);
|
|
65
|
+
}
|
|
66
|
+
return asRow(row);
|
|
67
|
+
},
|
|
68
|
+
async findOne({ model, modelKey = model, where, select: fields }) {
|
|
69
|
+
return asRow(await querier.findOne(entities[model], { ...filter(where), $select: select(modelKey, fields) }));
|
|
70
|
+
},
|
|
71
|
+
async findMany({ model, modelKey = model, where = [], select: fields, sortBy, offset, limit }) {
|
|
72
|
+
const rows = await querier.findMany(entities[model], {
|
|
73
|
+
...filter(where),
|
|
74
|
+
$select: select(modelKey, fields),
|
|
75
|
+
$sort: sortBy && { [getFieldName({ model: modelKey, field: sortBy.field })]: sortBy.direction },
|
|
76
|
+
$skip: offset,
|
|
77
|
+
$limit: limit,
|
|
78
|
+
});
|
|
79
|
+
return rows.map((row) => asRow(row));
|
|
80
|
+
},
|
|
81
|
+
count({ model, where = [] }) {
|
|
82
|
+
return querier.count(entities[model], filter(where));
|
|
83
|
+
},
|
|
84
|
+
update({ model, where, update }) {
|
|
85
|
+
return updateOne(model, where, payloadOf(update));
|
|
86
|
+
},
|
|
87
|
+
// `$inc` adds in the statement, so racing increments all land, where a read-then-write would retry.
|
|
88
|
+
incrementOne({ model, where, increment, set }) {
|
|
89
|
+
const steps = Object.fromEntries(Object.entries(increment).map(([field, $inc]) => [field, { $inc }]));
|
|
90
|
+
return updateOne(model, where, { ...set, ...steps });
|
|
91
|
+
},
|
|
92
|
+
updateMany({ model, where, update }) {
|
|
93
|
+
return querier.updateMany(entities[model], filter(where), update, { unfiltered: !where.length });
|
|
94
|
+
},
|
|
95
|
+
async delete({ model, where }) {
|
|
96
|
+
// Unlike `deleteMany`, never unfiltered: UQL refuses one naming no row.
|
|
97
|
+
await querier.deleteMany(entities[model], filter(where));
|
|
98
|
+
},
|
|
99
|
+
deleteMany({ model, where }) {
|
|
100
|
+
return querier.deleteMany(entities[model], filter(where), { unfiltered: !where.length });
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A row as the type Better Auth asks for, `null` for none: each method lets its caller name the shape of
|
|
106
|
+
* its own table, which no query can check, so this is the one place UQL takes that on trust.
|
|
107
|
+
*/
|
|
108
|
+
function asRow(row) {
|
|
109
|
+
return (row ?? null);
|
|
110
|
+
}
|
|
111
|
+
/** An update's payload, which Better Auth types as anything and always sends as a row of fields. */
|
|
112
|
+
function payloadOf(update) {
|
|
113
|
+
if (typeof update !== 'object' || update === null) {
|
|
114
|
+
throw new UqlUsageError('Better Auth sent an update that is not a row of fields');
|
|
115
|
+
}
|
|
116
|
+
return update;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Better Auth's clauses as one `$where`: all of those joined by `AND`, and any of those joined by `OR`.
|
|
120
|
+
* Each clause is an entry of its own, since two on one field would overwrite each other in one map.
|
|
121
|
+
*/
|
|
122
|
+
function whereOf(where) {
|
|
123
|
+
const all = where.filter((clause) => clause.connector === 'AND').map(clauseOf);
|
|
124
|
+
const any = where.filter((clause) => clause.connector === 'OR').map(clauseOf);
|
|
125
|
+
const $where = {};
|
|
126
|
+
if (all.length)
|
|
127
|
+
$where['$and'] = all;
|
|
128
|
+
if (any.length)
|
|
129
|
+
$where['$or'] = any;
|
|
130
|
+
return $where;
|
|
131
|
+
}
|
|
132
|
+
/** One clause; ignoring case applies where every value is text, as Better Auth's own adapters hold. */
|
|
133
|
+
function clauseOf({ field, operator, value, mode }) {
|
|
134
|
+
const values = [value].flat();
|
|
135
|
+
const texts = mode === 'insensitive' && values.length && values.every((it) => typeof it === 'string') ? values : undefined;
|
|
136
|
+
return CLAUSES[operator](field, value, texts);
|
|
137
|
+
}
|
|
138
|
+
/** A literal case-insensitive match, which reads the same on every engine. */
|
|
139
|
+
const ilike = (field, text) => ({ [field]: { $ilike: likeLiteral(text) } });
|
|
140
|
+
/** An `in` list without `null`, which no `IN` matches and which makes every `NOT IN` match nothing. */
|
|
141
|
+
const listOf = (value) => [value].flat().filter((it) => it !== null);
|
|
142
|
+
/** Every Better Auth operator as the clause it is; `satisfies` fails the build on one it adds. */
|
|
143
|
+
const CLAUSES = {
|
|
144
|
+
eq: (field, value, texts) => (texts ? ilike(field, texts[0]) : { [field]: { $eq: value } }),
|
|
145
|
+
ne: (field, value, texts) => (texts ? { $not: [ilike(field, texts[0])] } : { [field]: { $ne: value } }),
|
|
146
|
+
lt: (field, value) => ({ [field]: { $lt: value } }),
|
|
147
|
+
lte: (field, value) => ({ [field]: { $lte: value } }),
|
|
148
|
+
gt: (field, value) => ({ [field]: { $gt: value } }),
|
|
149
|
+
gte: (field, value) => ({ [field]: { $gte: value } }),
|
|
150
|
+
in: (field, value, texts) => texts ? { $or: texts.map((text) => ilike(field, text)) } : { [field]: { $in: listOf(value) } },
|
|
151
|
+
not_in: (field, value, texts) => texts ? { $nor: texts.map((text) => ilike(field, text)) } : { [field]: { $nin: listOf(value) } },
|
|
152
|
+
contains: (field, value, texts) => ({ [field]: { [texts ? '$iincludes' : '$includes']: value } }),
|
|
153
|
+
starts_with: (field, value, texts) => ({ [field]: { [texts ? '$istartsWith' : '$startsWith']: value } }),
|
|
154
|
+
ends_with: (field, value, texts) => ({ [field]: { [texts ? '$iendsWith' : '$endsWith']: value } }),
|
|
155
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var c=[];function d(e){for(let r of c)r(e)}function
|
|
1
|
+
var c=[];function d(e){for(let r of c)r(e)}function M(e){c.push(e);let r=c.length-1;return()=>{c.splice(r,1)}}var O=["$select","$populate","$exclude","$where","$sort"],f=["$count"],b=["$skip","$limit"],R=["$candidates"],T=["$distinct"],L=["$lock",...f,...R];var C=Symbol("rawValue"),N=Symbol("rawAlias"),D=Symbol("rawText");class k extends Error{}class i extends k{name="UqlUsageError";kind="usage";status=400}function l(e){return e?Object.keys(e):[]}function K(e){if(typeof e!=="object"||e===null)return!0;if(Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null}var _=["hardDelete","count"],te=new Set([...O,...f,...b,...R,...T,..._]);function u(e){if(!e)return"";let r=new URLSearchParams;for(let n of l(e)){let o=e[n];if(o===void 0)continue;r.append(n,typeof o==="object"&&o!==null?a(o):String(o))}let t=r.toString();return t?`?${t}`:""}function a(e){return JSON.stringify(e,(r,t)=>{if(typeof t!=="object"||t===null)return t;if(C in t)throw new i("raw SQL cannot travel over HTTP: what leaves the browser is JSON");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))throw new i("binary cannot travel over HTTP: what leaves the browser is JSON");return t})}class U extends Error{status;constructor(e,r){super(e);this.status=r;this.name="RequestError"}}function x(e,r){return y(e,{method:"get"},r)}function h(e,r,t){return y(e,{method:"post",body:a(r)},t)}function Q(e,r,t){return y(e,{method:"patch",body:a(r)},t)}function g(e,r,t){return y(e,{method:"put",body:a(r)},t)}function m(e,r){return y(e,{method:"delete"},r)}function q(e,r,t){return y(e,{method:"QUERY",body:a(r)},t)}function y(e,r,t){if(d({phase:"start",opts:t}),r.headers={accept:"application/json","content-type":"application/json",...t?.headers},t?.signal)r.signal=t.signal;return fetch(e,r).then((n)=>n.json().then((o)=>{if(n.status>=200&&n.status<300)return d({phase:"success",opts:t}),o;let P=o,E={message:P?.error?.message??n.statusText,code:P?.error?.code??n.status};throw d({phase:"error",error:E,opts:t}),new U(E.message,E.code)})).finally(()=>{d({phase:"complete",opts:t})})}function F(e){let r=e.charAt(0).toLowerCase();for(let t=1;t<e.length;++t)r+=e[t]===e[t].toUpperCase()?"-"+e[t].toLowerCase():e[t];return r}var s={findMany:{method:"GET",path:""},findOne:{method:"GET",path:"/one"},count:{method:"GET",path:"/count"},findOneById:{method:"GET",path:"/:id"},insertOne:{method:"POST",path:""},insertMany:{method:"POST",path:"/many"},saveOne:{method:"PUT",path:""},saveMany:{method:"PUT",path:"/many"},updateMany:{method:"PATCH",path:""},updateOneById:{method:"PATCH",path:"/:id"},deleteOneById:{method:"DELETE",path:"/:id"},deleteMany:{method:"DELETE",path:""}},A=l(s),ye=new Map(A.filter((e)=>s[e].method==="GET"&&s[e].path!=="/:id").map((e)=>[s[e].path,e]));function V(e){return F(e.name)}function w(e,r){if(!K(r))throw new i(`'${e.name}' was addressed by an id object, which the HTTP route cannot carry.`);return String(r)}class S{basePath;defaults;constructor(e,r={}){this.basePath=e;this.defaults=r}async findOneById(e,r,t,n){let o=this.getBasePath(e),p=u(t);return x(`${o}/${w(e,r)}${p}`,this.buildOptions(n))}findOne(e,r,t){return this.read(`${this.getBasePath(e)}${s.findOne.path}`,r,t)}findMany(e,r,t){let n={...r};if(t?.count)n.count=!0;return this.read(this.getBasePath(e),n,t)}async findManyAndCount(e,r,t){let n=await this.findMany(e,r,{...t,count:!0});if(typeof n.count!=="number")throw TypeError("findManyAndCount response has an invalid count");return{...n,count:n.count}}count(e,r,t){return this.read(`${this.getBasePath(e)}${s.count.path}`,r,t)}async exists(e,r,t){let n=await this.count(e,{...r,$limit:1},t);return{...n,data:n.data>0}}insertOne(e,r,t){let n=this.getBasePath(e);return h(n,r,this.buildOptions(t))}insertMany(e,r,t){let n=this.getBasePath(e);return h(`${n}${s.insertMany.path}`,r,this.buildOptions(t))}async updateOneById(e,r,t,n){let o=this.getBasePath(e);return Q(`${o}/${w(e,r)}`,t,this.buildOptions(n))}updateMany(e,r,t,n){let o=this.getBasePath(e),p=u(r);return Q(`${o}${p}`,t,this.buildOptions(n))}saveOne(e,r,t){let n=this.getBasePath(e);return g(n,r,this.buildOptions(t))}saveMany(e,r,t){let n=this.getBasePath(e);return g(`${n}${s.saveMany.path}`,r,this.buildOptions(t))}async deleteOneById(e,r,t={}){let n=this.getBasePath(e),o=t.hardDelete?u({hardDelete:t.hardDelete}):"";return m(`${n}/${w(e,r)}${o}`,this.buildOptions(t))}deleteMany(e,r,t={}){let n=this.getBasePath(e),o=u(t.hardDelete?{...r,hardDelete:t.hardDelete}:r);return m(`${n}${o}`,this.buildOptions(t))}getBasePath(e){return`${this.basePath}/${(this.defaults.entityPath??V)(e)}`}read(e,r,t){if(this.defaults.readMethod==="QUERY")return q(e,r??{},this.buildOptions(t));return x(`${e}${u(r)}`,this.buildOptions(t))}buildOptions(e){if(!this.defaults.headers&&!e?.headers)return e;return{...e,headers:{...this.defaults.headers,...e?.headers}}}}var j={getQuerier:()=>new S("/api")};function he(e){j=e}function v(){return j}function Qe(){return v().getQuerier()}export{S as HttpQuerier,U as RequestError,x as get,Qe as getQuerier,v as getQuerierPool,d as notify,M as on,Q as patch,h as post,g as put,q as query,m as remove,he as setQuerierPool};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=20295AB43B909F0564756E2164756E21
|
|
4
4
|
//# sourceMappingURL=uql-browser.min.js.map
|