@tinyshed/tinystore 0.1.0-rc.4 → 0.1.0-rc.6
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 +37 -37
- package/bin/tinystore.js +12 -1
- package/dist/backup.d.ts +33 -0
- package/dist/backup.js +49 -0
- package/dist/blobs.d.ts +160 -79
- package/dist/blobs.js +510 -217
- package/dist/channels.d.ts +90 -0
- package/dist/channels.js +291 -0
- package/dist/clock.js +3 -3
- package/dist/config.d.ts +209 -86
- package/dist/config.js +581 -538
- package/dist/connection.d.ts +64 -2
- package/dist/connection.js +201 -16
- package/dist/console.d.ts +27 -3
- package/dist/console.js +165 -12
- package/dist/dotenv.d.ts +7 -0
- package/dist/dotenv.js +79 -0
- package/dist/errors.d.ts +61 -1
- package/dist/errors.js +81 -1
- package/dist/handles.d.ts +44 -2
- package/dist/handles.js +81 -2
- package/dist/index.d.ts +17 -11
- package/dist/index.js +5 -3
- package/dist/instruments.d.ts +177 -0
- package/dist/instruments.js +819 -0
- package/dist/jobs.d.ts +335 -239
- package/dist/jobs.js +716 -536
- package/dist/json.d.ts +2 -0
- package/dist/json.js +122 -0
- package/dist/kv.d.ts +130 -243
- package/dist/kv.js +273 -640
- package/dist/limits.d.ts +80 -0
- package/dist/limits.js +139 -0
- package/dist/locks.d.ts +62 -0
- package/dist/locks.js +237 -0
- package/dist/logger.d.ts +45 -9
- package/dist/logger.js +150 -38
- package/dist/metrics.d.ts +210 -209
- package/dist/metrics.js +319 -556
- package/dist/once.d.ts +19 -18
- package/dist/once.js +74 -63
- package/dist/query.d.ts +181 -0
- package/dist/query.js +788 -0
- package/dist/records.d.ts +241 -150
- package/dist/records.js +507 -291
- package/dist/runtime/addon.d.ts +14 -0
- package/dist/runtime/addon.js +69 -0
- package/dist/runtime/bun.js +5 -7
- package/dist/runtime/node.js +5 -7
- package/dist/runtime/pipe.d.ts +17 -0
- package/dist/runtime/pipe.js +133 -0
- package/dist/runtime/shared.d.ts +6 -0
- package/dist/runtime/shared.js +19 -0
- package/dist/runtime.d.ts +5 -2
- package/dist/search.d.ts +189 -0
- package/dist/search.js +281 -0
- package/dist/session.d.ts +31 -3
- package/dist/session.js +153 -41
- package/dist/sql.d.ts +228 -78
- package/dist/sql.js +745 -240
- package/dist/store.d.ts +244 -24
- package/dist/store.js +270 -67
- package/dist/time.d.ts +5 -1
- package/dist/time.js +22 -2
- package/dist/tx.d.ts +61 -0
- package/dist/tx.js +314 -0
- package/dist/wire/codec.d.ts +23 -7
- package/dist/wire/codec.js +56 -35
- package/dist/wire/frame.d.ts +2 -0
- package/dist/wire/frame.js +31 -14
- package/dist/wire/messages.d.ts +259 -0
- package/dist/wire/messages.js +22 -0
- package/dist/wire/msgpack.d.ts +49 -1
- package/dist/wire/msgpack.js +293 -56
- package/dist/wire/protocol.d.ts +2683 -0
- package/dist/wire/protocol.js +10846 -0
- package/package.json +39 -38
- package/src/backup.ts +81 -0
- package/src/blobs.ts +678 -301
- package/src/channels.ts +377 -0
- package/src/clock.ts +4 -4
- package/src/config.ts +902 -612
- package/src/connection.ts +279 -21
- package/src/console.ts +180 -12
- package/src/dotenv.ts +82 -0
- package/src/errors.ts +105 -0
- package/src/handles.ts +157 -8
- package/src/index.ts +158 -52
- package/src/instruments.ts +1042 -0
- package/src/jobs.ts +1017 -733
- package/src/json.ts +133 -0
- package/src/kv.ts +424 -847
- package/src/limits.ts +202 -0
- package/src/locks.ts +320 -0
- package/src/logger.ts +209 -40
- package/src/metrics.ts +557 -752
- package/src/once.ts +86 -83
- package/src/query.ts +1005 -0
- package/src/records.ts +795 -418
- package/src/runtime/addon.ts +99 -0
- package/src/runtime/bun.ts +5 -7
- package/src/runtime/node.ts +5 -7
- package/src/runtime/pipe.ts +178 -0
- package/src/runtime/shared.ts +20 -0
- package/src/runtime.ts +5 -2
- package/src/search.ts +480 -0
- package/src/session.ts +187 -41
- package/src/sql.ts +993 -306
- package/src/store.ts +473 -78
- package/src/time.ts +48 -3
- package/src/tx.ts +426 -0
- package/src/wire/codec.ts +78 -37
- package/src/wire/frame.ts +44 -14
- package/src/wire/messages.ts +25 -0
- package/src/wire/msgpack.ts +327 -56
- package/src/wire/protocol.ts +11709 -0
- package/dist/limiter.d.ts +0 -45
- package/dist/limiter.js +0 -68
- package/dist/quota.d.ts +0 -44
- package/dist/quota.js +0 -98
- package/src/limiter.ts +0 -99
- package/src/quota.ts +0 -137
package/dist/query.js
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
// A table's queries, built from pieces into the SQL a person would write: the
|
|
2
|
+
// builder adds the ands, the parentheses, the placeholders and the quotes
|
|
3
|
+
// around names, and nothing else. It runs in this process; the server sees
|
|
4
|
+
// the text and the values, as it would a statement written by hand.
|
|
5
|
+
var _a;
|
|
6
|
+
import { CorruptError, InvalidError } from './errors.js';
|
|
7
|
+
import { check } from './schema.js';
|
|
8
|
+
import { cellOf, conditionOf, grouped, identOf, joinedWith, placeholders, Sql, } from './sql.js';
|
|
9
|
+
/**
|
|
10
|
+
* A query on a table: a value, each call returning a new one, so that the
|
|
11
|
+
* first stays as it was. `all`, `one`, `scalar`, `count`, `each` and `list`
|
|
12
|
+
* read; `update` and `delete` write.
|
|
13
|
+
*
|
|
14
|
+
* const urgent = await orders
|
|
15
|
+
* .where({ status: 'pending', deleted: false })
|
|
16
|
+
* .where(sql.or(sql`amount >= ${1000}`, { priority: 'high' }))
|
|
17
|
+
* .orderBy('created_at', 'desc')
|
|
18
|
+
* .limit(50)
|
|
19
|
+
* .all()
|
|
20
|
+
*/
|
|
21
|
+
export class Query {
|
|
22
|
+
#source;
|
|
23
|
+
#parts;
|
|
24
|
+
/** Queries come from `db.table`. */
|
|
25
|
+
constructor(source, parts) {
|
|
26
|
+
this.#source = source;
|
|
27
|
+
this.#parts = parts;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Adds a condition with and: equal values, `null` as is null and a list
|
|
31
|
+
* as in (…); a piece of SQL from `sql`; or text and the values of its ?s.
|
|
32
|
+
* `undefined` is InvalidError, never a filter left out.
|
|
33
|
+
*/
|
|
34
|
+
where(condition, ...values) {
|
|
35
|
+
return this.#with({ conditions: [...this.#parts.conditions, ...kept(condition, values)] });
|
|
36
|
+
}
|
|
37
|
+
/** The columns a row holds, as SQL text, and the shape of the row they make. */
|
|
38
|
+
select(columns) {
|
|
39
|
+
const select = typeof columns === 'string' ? new Sql(columns, []) : columns;
|
|
40
|
+
return new _a(this.#source, { ...this.#parts, select });
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Gives each row the rows of another query as a list under `name`, from
|
|
44
|
+
* the same statement: the query names the row it belongs to in its
|
|
45
|
+
* `where`, by this table's alias, names its columns with `select`, and has
|
|
46
|
+
* a `limit`, which counts for each row. Every value comes back as it is
|
|
47
|
+
* kept, bytes and integers past 2^53 among them.
|
|
48
|
+
*
|
|
49
|
+
* const latest = db.table<Post>('posts as p').select<{ id: string; title: string }>('p.id, p.title')
|
|
50
|
+
* .where('p.author_id = u.id').orderBy('p.id', 'desc').limit(3)
|
|
51
|
+
* const authors = await db.table<User>('users as u').include('posts', latest).all()
|
|
52
|
+
*/
|
|
53
|
+
include(name, query) {
|
|
54
|
+
const describe = `the included ${JSON.stringify(name)}`;
|
|
55
|
+
const parts = query.parts;
|
|
56
|
+
if (parts.select === undefined) {
|
|
57
|
+
throw new InvalidError(`${describe}: it names its columns with select('p.id, p.title')`);
|
|
58
|
+
}
|
|
59
|
+
if (parts.limit === undefined) {
|
|
60
|
+
throw new InvalidError(`${describe}: it needs a limit, which counts for each row`);
|
|
61
|
+
}
|
|
62
|
+
if (parts.includes.length > 0) {
|
|
63
|
+
throw new InvalidError(`${describe}: an included query includes nothing itself`);
|
|
64
|
+
}
|
|
65
|
+
const included = {
|
|
66
|
+
name,
|
|
67
|
+
parts,
|
|
68
|
+
source: query.source,
|
|
69
|
+
columns: namesOf(parts.select.text, describe),
|
|
70
|
+
};
|
|
71
|
+
const taken = this.#parts.includes.some(each => each.name === name);
|
|
72
|
+
if (taken || name.length === 0) {
|
|
73
|
+
throw new InvalidError(`${describe}: an included list has a name of its own`);
|
|
74
|
+
}
|
|
75
|
+
return new _a(this.#source, {
|
|
76
|
+
...this.#parts,
|
|
77
|
+
includes: [...this.#parts.includes, included],
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** Joins a table, `'users as u'`, on a condition as SQL text or a piece of SQL. */
|
|
81
|
+
join(table, on) {
|
|
82
|
+
return this.#joined('join', table, on);
|
|
83
|
+
}
|
|
84
|
+
/** Joins a table whose columns may be null where no row of it meets the condition. */
|
|
85
|
+
leftJoin(table, on) {
|
|
86
|
+
return this.#joined('left join', table, on);
|
|
87
|
+
}
|
|
88
|
+
/** Groups the rows by columns, quoted as names. */
|
|
89
|
+
groupBy(...columns) {
|
|
90
|
+
return this.#with({ groups: [...this.#parts.groups, ...columns.map(identOf)] });
|
|
91
|
+
}
|
|
92
|
+
/** A condition on the groups, as `where` takes one. */
|
|
93
|
+
having(condition, ...values) {
|
|
94
|
+
return this.#with({ having: [...this.#parts.having, ...kept(condition, values)] });
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Orders the rows by a column, quoted as a name, so that a sort a request
|
|
98
|
+
* chooses cannot be SQL, or by a piece of SQL: `` orderBy(sql`lower(title)`) ``.
|
|
99
|
+
*/
|
|
100
|
+
orderBy(column, direction = 'asc') {
|
|
101
|
+
if (direction !== 'asc' && direction !== 'desc') {
|
|
102
|
+
throw new InvalidError(`an order is asc or desc, not ${JSON.stringify(direction)}`);
|
|
103
|
+
}
|
|
104
|
+
const order = column instanceof Sql
|
|
105
|
+
? { piece: column, direction }
|
|
106
|
+
: { piece: new Sql(identOf(column), []), column, direction };
|
|
107
|
+
return this.#with({ order: [...this.#parts.order, order] });
|
|
108
|
+
}
|
|
109
|
+
limit(rows) {
|
|
110
|
+
return this.#with({ limit: whole(rows, 'a limit') });
|
|
111
|
+
}
|
|
112
|
+
offset(rows) {
|
|
113
|
+
return this.#with({ offset: whole(rows, 'an offset') });
|
|
114
|
+
}
|
|
115
|
+
/** The text and the values the query sends, to read or to log. */
|
|
116
|
+
toSQL() {
|
|
117
|
+
const rendered = render(this.#parts);
|
|
118
|
+
return { text: rendered.text, values: [...rendered.values] };
|
|
119
|
+
}
|
|
120
|
+
/** The query inside another piece of SQL: a subquery, in parentheses. */
|
|
121
|
+
embedded() {
|
|
122
|
+
const rendered = render(this.#parts);
|
|
123
|
+
return new Sql(`(${rendered.text})`, rendered.values);
|
|
124
|
+
}
|
|
125
|
+
async all() {
|
|
126
|
+
const answered = await this.#source.runner.rows(render(this.#parts), 'all');
|
|
127
|
+
return this.#rows(answered.columns, answered.rows);
|
|
128
|
+
}
|
|
129
|
+
async one() {
|
|
130
|
+
const answered = await this.#source.runner.rows(render(this.#parts), 'one');
|
|
131
|
+
return (await this.#rows(answered.columns, answered.rows))[0];
|
|
132
|
+
}
|
|
133
|
+
async scalar() {
|
|
134
|
+
const answered = await this.#source.runner.rows(render(this.#parts), 'scalar');
|
|
135
|
+
return answered.rows[0]?.[0];
|
|
136
|
+
}
|
|
137
|
+
/** Every row the conditions match, without the order and the limit. */
|
|
138
|
+
async count() {
|
|
139
|
+
const counted = {
|
|
140
|
+
...this.#parts,
|
|
141
|
+
select: new Sql('count(*)', []),
|
|
142
|
+
order: [],
|
|
143
|
+
limit: undefined,
|
|
144
|
+
offset: undefined,
|
|
145
|
+
includes: [],
|
|
146
|
+
};
|
|
147
|
+
const statement = counted.groups.length === 0
|
|
148
|
+
? render(counted)
|
|
149
|
+
: new Sql(`select count(*) from (${render({ ...counted, select: new Sql('1', []) }).text})`, render(counted).values);
|
|
150
|
+
const answered = await this.#source.runner.rows(statement, 'scalar');
|
|
151
|
+
return Number(answered.rows[0]?.[0] ?? 0);
|
|
152
|
+
}
|
|
153
|
+
/** The rows one at a time, as their parts arrive. */
|
|
154
|
+
async *each() {
|
|
155
|
+
const runner = this.#source.runner;
|
|
156
|
+
if (runner.each === undefined) {
|
|
157
|
+
yield* await this.all();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
for await (const row of runner.each(render(this.#parts))) {
|
|
161
|
+
yield (await this.#rows(Object.keys(row), [Object.values(row)]))[0];
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* A page after the last row of the one before, by the query's order,
|
|
166
|
+
* which ends in a unique column so that no row is read twice or skipped.
|
|
167
|
+
* `next` reads the next page, and only of this query.
|
|
168
|
+
*
|
|
169
|
+
* const first = await orders.orderBy('created_at', 'desc').orderBy('id', 'desc').list({ limit: 50 })
|
|
170
|
+
* const second = await orders.orderBy('created_at', 'desc').orderBy('id', 'desc').list({ limit: 50, after: first.next })
|
|
171
|
+
*/
|
|
172
|
+
async list(options = {}) {
|
|
173
|
+
const order = this.#parts.order;
|
|
174
|
+
if (order.length === 0 || order.some(each => each.column === undefined)) {
|
|
175
|
+
throw new InvalidError('a page is read by the query order, of columns by their names: orderBy(…) first');
|
|
176
|
+
}
|
|
177
|
+
const limit = whole(options.limit ?? 100, 'a page limit');
|
|
178
|
+
const digest = digestOf(render({ ...this.#parts, limit: undefined, offset: undefined }));
|
|
179
|
+
let parts = { ...this.#parts, limit, offset: undefined };
|
|
180
|
+
if (options.after !== undefined) {
|
|
181
|
+
const after = cursorOf(options.after, digest);
|
|
182
|
+
parts = {
|
|
183
|
+
...parts,
|
|
184
|
+
conditions: [...parts.conditions, { piece: keyset(order, after), bare: true }],
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
const answered = await this.#source.runner.rows(render(parts), 'all');
|
|
188
|
+
const rows = await this.#rows(answered.columns, answered.rows);
|
|
189
|
+
if (answered.rows.length < limit) {
|
|
190
|
+
return { rows };
|
|
191
|
+
}
|
|
192
|
+
const last = answered.rows[answered.rows.length - 1];
|
|
193
|
+
const values = order.map(each => {
|
|
194
|
+
const name = each.column.split('.').pop();
|
|
195
|
+
const at = answered.columns.indexOf(name);
|
|
196
|
+
if (at < 0) {
|
|
197
|
+
throw new InvalidError(`the page is ordered by ${each.column}, which its rows lack: select it`);
|
|
198
|
+
}
|
|
199
|
+
return last[at] ?? null;
|
|
200
|
+
});
|
|
201
|
+
return { rows, next: cursorText(values, digest) };
|
|
202
|
+
}
|
|
203
|
+
/** SQLite's plan for the query, a line a step. */
|
|
204
|
+
async explain() {
|
|
205
|
+
const rendered = render(this.#parts);
|
|
206
|
+
const answered = await this.#source.runner.rows(new Sql(`explain query plan ${rendered.text}`, rendered.values), 'all');
|
|
207
|
+
const detail = answered.columns.indexOf('detail');
|
|
208
|
+
return answered.rows.map(row => String(row[detail] ?? ''));
|
|
209
|
+
}
|
|
210
|
+
/** Sets columns of the rows the conditions match, and says how many changed. */
|
|
211
|
+
async update(values) {
|
|
212
|
+
this.#refuseEveryRow('an update');
|
|
213
|
+
const names = Object.keys(values);
|
|
214
|
+
if (names.length === 0) {
|
|
215
|
+
throw new InvalidError('an update sets at least one column');
|
|
216
|
+
}
|
|
217
|
+
const sets = [];
|
|
218
|
+
const out = [];
|
|
219
|
+
for (const name of names) {
|
|
220
|
+
const value = values[name];
|
|
221
|
+
if (value instanceof Sql) {
|
|
222
|
+
sets.push(`${identOf(name)} = ${value.text}`);
|
|
223
|
+
out.push(...value.values);
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
sets.push(`${identOf(name)} = ?`);
|
|
227
|
+
out.push(fieldOf(value, name, this.#source.types));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const where = conditionsText(this.#parts.conditions);
|
|
231
|
+
return this.#source.runner.exec(new Sql(`update ${tableName(this.#parts)} set ${sets.join(', ')} where ${where.text}`, [
|
|
232
|
+
...out,
|
|
233
|
+
...where.values,
|
|
234
|
+
]));
|
|
235
|
+
}
|
|
236
|
+
/** Deletes the rows the conditions match, and says how many it deleted. */
|
|
237
|
+
async delete() {
|
|
238
|
+
this.#refuseEveryRow('a delete');
|
|
239
|
+
const where = conditionsText(this.#parts.conditions);
|
|
240
|
+
return this.#source.runner.exec(new Sql(`delete from ${tableName(this.#parts)} where ${where.text}`, where.values));
|
|
241
|
+
}
|
|
242
|
+
/** A row as the table's types and schema read it. */
|
|
243
|
+
async read(row) {
|
|
244
|
+
return (await readAs(this.#source, row));
|
|
245
|
+
}
|
|
246
|
+
get source() {
|
|
247
|
+
return this.#source;
|
|
248
|
+
}
|
|
249
|
+
get parts() {
|
|
250
|
+
return this.#parts;
|
|
251
|
+
}
|
|
252
|
+
async #rows(columns, rows) {
|
|
253
|
+
const includes = this.#parts.includes;
|
|
254
|
+
const out = [];
|
|
255
|
+
for (const values of rows) {
|
|
256
|
+
const row = {};
|
|
257
|
+
const lists = {};
|
|
258
|
+
for (const [at, column] of columns.entries()) {
|
|
259
|
+
const included = includes.find(each => each.name === column);
|
|
260
|
+
if (included === undefined) {
|
|
261
|
+
row[column] = values[at] ?? null;
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
lists[column] = await includedRows(included, values[at] ?? null);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
out.push({ ...(await this.read(row)), ...lists });
|
|
268
|
+
}
|
|
269
|
+
return out;
|
|
270
|
+
}
|
|
271
|
+
#with(changed) {
|
|
272
|
+
return new _a(this.#source, { ...this.#parts, ...changed });
|
|
273
|
+
}
|
|
274
|
+
#joined(kind, table, on) {
|
|
275
|
+
const condition = typeof on === 'string' ? new Sql(on, []) : on;
|
|
276
|
+
const ref = tableRef(table);
|
|
277
|
+
const join = new Sql(`${kind} ${ref.text} on ${condition.text}`, condition.values);
|
|
278
|
+
return this.#with({ joins: [...this.#parts.joins, join] });
|
|
279
|
+
}
|
|
280
|
+
/** Refuses an update or a delete of every row, which SQL says plainly. */
|
|
281
|
+
#refuseEveryRow(what) {
|
|
282
|
+
const conditions = this.#parts.conditions.filter(each => each.piece.text !== '1');
|
|
283
|
+
if (conditions.length === 0) {
|
|
284
|
+
throw new InvalidError(`${what} without a condition: every row is said in SQL, delete from …`);
|
|
285
|
+
}
|
|
286
|
+
if (this.#parts.joins.length > 0) {
|
|
287
|
+
throw new InvalidError(`${what} of a join: write it in SQL`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
_a = Query;
|
|
292
|
+
/**
|
|
293
|
+
* A table: its queries, and its rows' inserts and upserts.
|
|
294
|
+
*
|
|
295
|
+
* const notes = db.table<Note>('notes', { types: { done: 'bool', tags: 'json', created_at: 'time' } })
|
|
296
|
+
* const note = await notes.insert({ id: uuidv7(), author_id: userId, title: 'Buy milk', done: false, tags: [], created_at: new Date() })
|
|
297
|
+
*/
|
|
298
|
+
export class Table extends Query {
|
|
299
|
+
name;
|
|
300
|
+
/** Tables come from `db.table` and `tx.table`. */
|
|
301
|
+
constructor(runner, name, options = {}) {
|
|
302
|
+
const ref = tableRef(name);
|
|
303
|
+
super({ runner, types: options.types ?? {}, schema: options.schema }, emptyParts(ref.name, ref.alias));
|
|
304
|
+
this.name = ref.name;
|
|
305
|
+
}
|
|
306
|
+
async insert(given) {
|
|
307
|
+
const rows = Array.isArray(given) ? given : [given];
|
|
308
|
+
if (rows.length === 0) {
|
|
309
|
+
return [];
|
|
310
|
+
}
|
|
311
|
+
const statement = insertOf(this.name, rows, this.source.types);
|
|
312
|
+
const answered = await this.source.runner.rows(new Sql(`${statement.text} returning *`, statement.values), 'all');
|
|
313
|
+
const read = [];
|
|
314
|
+
for (const values of answered.rows) {
|
|
315
|
+
const row = {};
|
|
316
|
+
answered.columns.forEach((column, at) => {
|
|
317
|
+
row[column] = values[at] ?? null;
|
|
318
|
+
});
|
|
319
|
+
read.push(await this.read(row));
|
|
320
|
+
}
|
|
321
|
+
return Array.isArray(given) ? read : read[0];
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Inserts a row, or, when its key is taken, sets the columns `update`
|
|
325
|
+
* names on the row that holds it, if that row meets `where`. It gives
|
|
326
|
+
* back the row as the file keeps it, or undefined when `where` kept it.
|
|
327
|
+
*/
|
|
328
|
+
async upsert(row, options) {
|
|
329
|
+
const conflict = (typeof options.conflict === 'string' ? [options.conflict] : [...options.conflict]).map(identOf);
|
|
330
|
+
if (options.update.length === 0) {
|
|
331
|
+
throw new InvalidError('an upsert names the columns its update sets');
|
|
332
|
+
}
|
|
333
|
+
const insert = insertOf(this.name, [row], this.source.types);
|
|
334
|
+
const sets = options.update
|
|
335
|
+
.map(name => `${identOf(name)} = excluded.${identOf(name)}`)
|
|
336
|
+
.join(', ');
|
|
337
|
+
let text = `${insert.text} on conflict (${conflict.join(', ')}) do update set ${sets}`;
|
|
338
|
+
const values = [...insert.values];
|
|
339
|
+
if (options.where !== undefined) {
|
|
340
|
+
// in an upsert's update, a column is the row's that holds the key
|
|
341
|
+
const where = conditionOf(options.where);
|
|
342
|
+
text += ` where ${where.text}`;
|
|
343
|
+
values.push(...where.values);
|
|
344
|
+
}
|
|
345
|
+
const answered = await this.source.runner.rows(new Sql(`${text} returning *`, values), 'one');
|
|
346
|
+
if (answered.rows.length === 0) {
|
|
347
|
+
return undefined;
|
|
348
|
+
}
|
|
349
|
+
const read = {};
|
|
350
|
+
answered.columns.forEach((column, at) => {
|
|
351
|
+
read[column] = answered.rows[0][at] ?? null;
|
|
352
|
+
});
|
|
353
|
+
return this.read(read);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function emptyParts(table, alias) {
|
|
357
|
+
return {
|
|
358
|
+
table,
|
|
359
|
+
alias,
|
|
360
|
+
joins: [],
|
|
361
|
+
conditions: [],
|
|
362
|
+
groups: [],
|
|
363
|
+
having: [],
|
|
364
|
+
order: [],
|
|
365
|
+
includes: [],
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
/** A row as a table's types and schema read it. */
|
|
369
|
+
async function readAs(source, row) {
|
|
370
|
+
const typed = { ...row };
|
|
371
|
+
for (const [column, type] of Object.entries(source.types)) {
|
|
372
|
+
if (column in typed) {
|
|
373
|
+
typed[column] = typedOf(typed[column], type, column);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (source.schema === undefined) {
|
|
377
|
+
return typed;
|
|
378
|
+
}
|
|
379
|
+
const checked = await check(source.schema, typed);
|
|
380
|
+
if ('issues' in checked) {
|
|
381
|
+
throw new InvalidError(`a row does not meet the table's schema: ${checked.issues}`);
|
|
382
|
+
}
|
|
383
|
+
return checked.value;
|
|
384
|
+
}
|
|
385
|
+
/** The rows a row's included query gave, read as that query's table reads them. */
|
|
386
|
+
async function includedRows(included, kept) {
|
|
387
|
+
if (kept === null) {
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
if (typeof kept !== 'string') {
|
|
391
|
+
throw new CorruptError(`the included ${JSON.stringify(included.name)} came back as no text`);
|
|
392
|
+
}
|
|
393
|
+
const rows = [];
|
|
394
|
+
for (const values of literalRows(kept)) {
|
|
395
|
+
const row = {};
|
|
396
|
+
included.columns.forEach((column, at) => {
|
|
397
|
+
row[column] = values[at] ?? null;
|
|
398
|
+
});
|
|
399
|
+
rows.push(await readAs(included.source, row));
|
|
400
|
+
}
|
|
401
|
+
return rows;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* The names of the columns a select's text gives, in their order: a column's
|
|
405
|
+
* own name, or what follows its `as`. An expression without a name is
|
|
406
|
+
* refused, since its rows could not be given their fields.
|
|
407
|
+
*/
|
|
408
|
+
export function namesOf(select, describe) {
|
|
409
|
+
const name = `("(?:[^"]|"")+"|[A-Za-z_][\\w$]*)`;
|
|
410
|
+
const aliased = new RegExp(`\\s+as\\s+${name}\\s*$`, 'i');
|
|
411
|
+
const column = new RegExp(`^(?:${name}\\.)?${name}$`);
|
|
412
|
+
const bare = (quoted) => quoted.startsWith('"') ? quoted.slice(1, -1).replaceAll('""', '"') : quoted;
|
|
413
|
+
const names = [];
|
|
414
|
+
for (const item of itemsOf(select)) {
|
|
415
|
+
const found = aliased.exec(item)?.[1] ?? column.exec(item)?.[2];
|
|
416
|
+
if (found === undefined) {
|
|
417
|
+
throw new InvalidError(`${describe}: the column ${JSON.stringify(item)} needs a name: write it as … as name`);
|
|
418
|
+
}
|
|
419
|
+
if (names.includes(bare(found))) {
|
|
420
|
+
throw new InvalidError(`${describe}: two columns named ${bare(found)}`);
|
|
421
|
+
}
|
|
422
|
+
names.push(bare(found));
|
|
423
|
+
}
|
|
424
|
+
return names;
|
|
425
|
+
}
|
|
426
|
+
/** A select's items: its text cut at the commas outside quotes and parentheses. */
|
|
427
|
+
function itemsOf(select) {
|
|
428
|
+
const items = [];
|
|
429
|
+
let [depth, from, at] = [0, 0, 0];
|
|
430
|
+
while (at < select.length) {
|
|
431
|
+
const c = select[at];
|
|
432
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
433
|
+
at = select.indexOf(c, at + 1);
|
|
434
|
+
if (at < 0) {
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
else if (c === '(') {
|
|
439
|
+
depth++;
|
|
440
|
+
}
|
|
441
|
+
else if (c === ')') {
|
|
442
|
+
depth--;
|
|
443
|
+
}
|
|
444
|
+
else if (c === ',' && depth === 0) {
|
|
445
|
+
items.push(select.slice(from, at).trim());
|
|
446
|
+
from = at + 1;
|
|
447
|
+
}
|
|
448
|
+
at++;
|
|
449
|
+
}
|
|
450
|
+
items.push(select.slice(from).trim());
|
|
451
|
+
return items;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* An included query as one value of its row: its rows as SQL literals,
|
|
455
|
+
* `(1,'a'),(2,NULL)`, in the query's order. SQLite's quote() writes an
|
|
456
|
+
* integer, a float, a text and bytes so that each reads back as it is kept,
|
|
457
|
+
* where JSON would lose bytes and the last digits of a float.
|
|
458
|
+
*/
|
|
459
|
+
function includedText(included) {
|
|
460
|
+
const child = included.parts;
|
|
461
|
+
const order = child.order.map((each, at) => ({ ...each, alias: `"$o${at + 1}"` }));
|
|
462
|
+
const select = child.select;
|
|
463
|
+
const inner = render({
|
|
464
|
+
...child,
|
|
465
|
+
select: new Sql([select.text, ...order.map(each => `${each.piece.text} as ${each.alias}`)].join(', '), [...select.values, ...order.flatMap(each => each.piece.values)]),
|
|
466
|
+
});
|
|
467
|
+
const row = included.columns.map(literalOf).join(" || ',' || ");
|
|
468
|
+
const ordered = order.length === 0
|
|
469
|
+
? ''
|
|
470
|
+
: ` order by ${order.map(each => `${each.alias} ${each.direction}`).join(', ')}`;
|
|
471
|
+
return new Sql(`(select group_concat('(' || ${row} || ')', ','${ordered}) from (${inner.text}))`, inner.values);
|
|
472
|
+
}
|
|
473
|
+
/** A column as an SQL literal that keeps it whole: quote() cuts a text at a zero byte, so such a text goes as its bytes. */
|
|
474
|
+
function literalOf(column) {
|
|
475
|
+
const c = `"${column.replaceAll('"', '""')}"`;
|
|
476
|
+
return `case when typeof(${c}) = 'text' and instr(cast(${c} as blob), x'00') > 0 then 'T' || quote(cast(${c} as blob)) else quote(${c}) end`;
|
|
477
|
+
}
|
|
478
|
+
/** The rows an included query gave, read from their literals: `(1,'it''s',NULL),(2,X'00ff',1.5)`. */
|
|
479
|
+
export function literalRows(text) {
|
|
480
|
+
const reader = new Literals(text);
|
|
481
|
+
const rows = [];
|
|
482
|
+
while (!reader.done) {
|
|
483
|
+
reader.expect('(');
|
|
484
|
+
const row = [reader.literal()];
|
|
485
|
+
while (reader.next === ',') {
|
|
486
|
+
reader.expect(',');
|
|
487
|
+
row.push(reader.literal());
|
|
488
|
+
}
|
|
489
|
+
reader.expect(')');
|
|
490
|
+
rows.push(row);
|
|
491
|
+
if (!reader.done) {
|
|
492
|
+
reader.expect(',');
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return rows;
|
|
496
|
+
}
|
|
497
|
+
/** A reader of SQL literals as SQLite's quote() writes them. */
|
|
498
|
+
class Literals {
|
|
499
|
+
#text;
|
|
500
|
+
#at = 0;
|
|
501
|
+
constructor(text) {
|
|
502
|
+
this.#text = text;
|
|
503
|
+
}
|
|
504
|
+
get done() {
|
|
505
|
+
return this.#at >= this.#text.length;
|
|
506
|
+
}
|
|
507
|
+
get next() {
|
|
508
|
+
return this.#text[this.#at];
|
|
509
|
+
}
|
|
510
|
+
expect(wanted) {
|
|
511
|
+
if (this.next !== wanted) {
|
|
512
|
+
throw this.#broken();
|
|
513
|
+
}
|
|
514
|
+
this.#at++;
|
|
515
|
+
}
|
|
516
|
+
literal() {
|
|
517
|
+
switch (this.next) {
|
|
518
|
+
case "'":
|
|
519
|
+
return this.#quoted();
|
|
520
|
+
case 'X':
|
|
521
|
+
return this.#hex();
|
|
522
|
+
case 'T':
|
|
523
|
+
this.#at++;
|
|
524
|
+
return new TextDecoder().decode(this.#hex());
|
|
525
|
+
}
|
|
526
|
+
if (this.#text.startsWith('NULL', this.#at)) {
|
|
527
|
+
this.#at += 4;
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
return this.#number();
|
|
531
|
+
}
|
|
532
|
+
/** A text in single quotes, a quote inside it doubled. */
|
|
533
|
+
#quoted() {
|
|
534
|
+
let value = '';
|
|
535
|
+
for (this.#at++;; this.#at++) {
|
|
536
|
+
const end = this.#text.indexOf("'", this.#at);
|
|
537
|
+
if (end < 0) {
|
|
538
|
+
throw this.#broken();
|
|
539
|
+
}
|
|
540
|
+
value += this.#text.slice(this.#at, end);
|
|
541
|
+
this.#at = end + 1;
|
|
542
|
+
if (this.next !== "'") {
|
|
543
|
+
return value;
|
|
544
|
+
}
|
|
545
|
+
value += "'";
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
/** Bytes as `X'00ff'`. */
|
|
549
|
+
#hex() {
|
|
550
|
+
const end = this.#text.indexOf("'", this.#at + 2);
|
|
551
|
+
const digits = this.#text.slice(this.#at + 2, Math.max(end, 0));
|
|
552
|
+
if (!this.#text.startsWith("X'", this.#at) ||
|
|
553
|
+
end < 0 ||
|
|
554
|
+
!/^(?:[0-9A-Fa-f]{2})*$/.test(digits)) {
|
|
555
|
+
throw this.#broken();
|
|
556
|
+
}
|
|
557
|
+
this.#at = end + 1;
|
|
558
|
+
return new Uint8Array(Buffer.from(digits, 'hex'));
|
|
559
|
+
}
|
|
560
|
+
/** An integer, a bigint past 2^53, or a float, which quote() writes with a point or an exponent. */
|
|
561
|
+
#number() {
|
|
562
|
+
let end = this.#at;
|
|
563
|
+
while (end < this.#text.length && this.#text[end] !== ',' && this.#text[end] !== ')') {
|
|
564
|
+
end++;
|
|
565
|
+
}
|
|
566
|
+
const word = this.#text.slice(this.#at, end);
|
|
567
|
+
if (/^-?\d+$/.test(word)) {
|
|
568
|
+
this.#at = end;
|
|
569
|
+
const whole = BigInt(word);
|
|
570
|
+
return whole >= Number.MIN_SAFE_INTEGER && whole <= Number.MAX_SAFE_INTEGER
|
|
571
|
+
? Number(whole)
|
|
572
|
+
: whole;
|
|
573
|
+
}
|
|
574
|
+
if (word.length === 0 || Number.isNaN(Number(word))) {
|
|
575
|
+
throw this.#broken();
|
|
576
|
+
}
|
|
577
|
+
this.#at = end;
|
|
578
|
+
return Number(word);
|
|
579
|
+
}
|
|
580
|
+
#broken() {
|
|
581
|
+
const shown = this.#text.slice(this.#at, this.#at + 20);
|
|
582
|
+
return new CorruptError(`included rows that do not read at ${this.#at}: ${shown}`);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
/** `'orders'` or `'orders as o'`, quoted as names. */
|
|
586
|
+
function tableRef(text) {
|
|
587
|
+
const matched = /^\s*([A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*)?)(?:\s+(?:as\s+)?([A-Za-z_][\w$]*))?\s*$/i.exec(text);
|
|
588
|
+
if (matched === null) {
|
|
589
|
+
throw new InvalidError(`the table ${JSON.stringify(text)}: a table is its name, and an alias after as`);
|
|
590
|
+
}
|
|
591
|
+
const [, name, alias] = matched;
|
|
592
|
+
return {
|
|
593
|
+
name: name,
|
|
594
|
+
alias,
|
|
595
|
+
text: alias === undefined ? identOf(name) : `${identOf(name)} as ${identOf(alias)}`,
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
function tableName(parts) {
|
|
599
|
+
return identOf(parts.table);
|
|
600
|
+
}
|
|
601
|
+
/** A condition `where` takes, as the pieces an and joins. */
|
|
602
|
+
function kept(condition, values) {
|
|
603
|
+
if (typeof condition === 'string') {
|
|
604
|
+
const counted = placeholders(condition);
|
|
605
|
+
if (counted.positional !== values.length || counted.named.length > 0 || counted.numbered) {
|
|
606
|
+
throw new InvalidError(`${counted.positional} placeholders and ${values.length} values: each ? takes one value`);
|
|
607
|
+
}
|
|
608
|
+
return [
|
|
609
|
+
{
|
|
610
|
+
piece: new Sql(condition, values.map((value, at) => cellOf(value, `value ${at + 1}`))),
|
|
611
|
+
bare: false,
|
|
612
|
+
},
|
|
613
|
+
];
|
|
614
|
+
}
|
|
615
|
+
if (values.length > 0) {
|
|
616
|
+
throw new InvalidError('a condition that is not text carries its values: pass it alone');
|
|
617
|
+
}
|
|
618
|
+
if (condition instanceof Sql) {
|
|
619
|
+
return [{ piece: condition, bare: condition.bare || grouped(condition.text) }];
|
|
620
|
+
}
|
|
621
|
+
return Object.keys(condition)
|
|
622
|
+
.sort()
|
|
623
|
+
.map(name => ({ piece: conditionOf({ [name]: condition[name] }), bare: true }));
|
|
624
|
+
}
|
|
625
|
+
function conditionsText(conditions) {
|
|
626
|
+
return joinedWith(conditions.map(each => each.bare ? new Sql(each.piece.text, each.piece.values, true) : each.piece), 'and');
|
|
627
|
+
}
|
|
628
|
+
/** The query as one statement. */
|
|
629
|
+
function render(parts) {
|
|
630
|
+
const values = [];
|
|
631
|
+
const from = parts.alias === undefined
|
|
632
|
+
? identOf(parts.table)
|
|
633
|
+
: `${identOf(parts.table)} as ${identOf(parts.alias)}`;
|
|
634
|
+
let columns = '*';
|
|
635
|
+
if (parts.select !== undefined) {
|
|
636
|
+
columns = parts.select.text;
|
|
637
|
+
values.push(...parts.select.values);
|
|
638
|
+
}
|
|
639
|
+
else if (parts.joins.length > 0 || parts.includes.length > 0) {
|
|
640
|
+
columns = `${identOf(parts.alias ?? parts.table)}.*`;
|
|
641
|
+
}
|
|
642
|
+
for (const included of parts.includes) {
|
|
643
|
+
const list = includedText(included);
|
|
644
|
+
columns += `, ${list.text} as ${identOf(included.name)}`;
|
|
645
|
+
values.push(...list.values);
|
|
646
|
+
}
|
|
647
|
+
let text = `select ${columns} from ${from}`;
|
|
648
|
+
for (const join of parts.joins) {
|
|
649
|
+
text += ` ${join.text}`;
|
|
650
|
+
values.push(...join.values);
|
|
651
|
+
}
|
|
652
|
+
if (parts.conditions.length > 0) {
|
|
653
|
+
const where = conditionsText(parts.conditions);
|
|
654
|
+
text += ` where ${where.text}`;
|
|
655
|
+
values.push(...where.values);
|
|
656
|
+
}
|
|
657
|
+
if (parts.groups.length > 0) {
|
|
658
|
+
text += ` group by ${parts.groups.join(', ')}`;
|
|
659
|
+
}
|
|
660
|
+
if (parts.having.length > 0) {
|
|
661
|
+
const having = conditionsText(parts.having);
|
|
662
|
+
text += ` having ${having.text}`;
|
|
663
|
+
values.push(...having.values);
|
|
664
|
+
}
|
|
665
|
+
if (parts.order.length > 0) {
|
|
666
|
+
text += ` order by ${parts.order.map(each => `${each.piece.text} ${each.direction}`).join(', ')}`;
|
|
667
|
+
values.push(...parts.order.flatMap(each => each.piece.values));
|
|
668
|
+
}
|
|
669
|
+
if (parts.limit !== undefined) {
|
|
670
|
+
text += ' limit cast(? as integer)';
|
|
671
|
+
values.push(parts.limit);
|
|
672
|
+
}
|
|
673
|
+
if (parts.offset !== undefined) {
|
|
674
|
+
text += `${parts.limit === undefined ? ' limit -1' : ''} offset cast(? as integer)`;
|
|
675
|
+
values.push(parts.offset);
|
|
676
|
+
}
|
|
677
|
+
return new Sql(text, values);
|
|
678
|
+
}
|
|
679
|
+
/** The condition that starts a page after a row's order values. */
|
|
680
|
+
function keyset(order, after) {
|
|
681
|
+
const alternatives = [];
|
|
682
|
+
const values = [];
|
|
683
|
+
order.forEach((each, at) => {
|
|
684
|
+
const equal = order.slice(0, at).map(earlier => `${earlier.piece.text} = ?`);
|
|
685
|
+
values.push(...after.slice(0, at));
|
|
686
|
+
const past = `${each.piece.text} ${each.direction === 'asc' ? '>' : '<'} ?`;
|
|
687
|
+
values.push(after[at] ?? null);
|
|
688
|
+
alternatives.push(equal.length === 0 ? past : `(${[...equal, past].join(' and ')})`);
|
|
689
|
+
});
|
|
690
|
+
return new Sql(`(${alternatives.join(' or ')})`, values);
|
|
691
|
+
}
|
|
692
|
+
/** A short digest of a query, which a cursor carries so that another query refuses it. */
|
|
693
|
+
function digestOf(statement) {
|
|
694
|
+
let hash = 0x811c9dc5;
|
|
695
|
+
const text = `${statement.text}\u0000${JSON.stringify(statement.values, (_, v) => (typeof v === 'bigint' ? `${v}n` : v))}`;
|
|
696
|
+
for (let at = 0; at < text.length; at++) {
|
|
697
|
+
hash ^= text.charCodeAt(at);
|
|
698
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
699
|
+
}
|
|
700
|
+
return hash.toString(36);
|
|
701
|
+
}
|
|
702
|
+
function cursorText(values, digest) {
|
|
703
|
+
const json = JSON.stringify({ q: digest, v: values }, (_, v) => typeof v === 'bigint' ? { n: String(v) } : v);
|
|
704
|
+
return Buffer.from(json).toString('base64url');
|
|
705
|
+
}
|
|
706
|
+
function cursorOf(cursor, digest) {
|
|
707
|
+
let read;
|
|
708
|
+
try {
|
|
709
|
+
read = JSON.parse(Buffer.from(cursor, 'base64url').toString());
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
throw new InvalidError('a cursor that is not one: pass the next of a page');
|
|
713
|
+
}
|
|
714
|
+
if (read.q !== digest || !Array.isArray(read.v)) {
|
|
715
|
+
throw new InvalidError("a cursor of another query: a page's next reads only the query that made it");
|
|
716
|
+
}
|
|
717
|
+
return read.v.map(v => typeof v === 'object' && v !== null && 'n' in v
|
|
718
|
+
? BigInt(v.n)
|
|
719
|
+
: v);
|
|
720
|
+
}
|
|
721
|
+
/** An insert of rows of the same columns, the first row's. */
|
|
722
|
+
function insertOf(table, rows, types) {
|
|
723
|
+
const names = Object.keys(rows[0]).filter(name => rows[0][name] !== undefined);
|
|
724
|
+
if (names.length === 0) {
|
|
725
|
+
throw new InvalidError('a row to insert with no column');
|
|
726
|
+
}
|
|
727
|
+
const values = [];
|
|
728
|
+
const tuples = rows.map((row, at) => {
|
|
729
|
+
const extra = Object.keys(row).filter(name => !names.includes(name) && row[name] !== undefined);
|
|
730
|
+
if (extra.length > 0) {
|
|
731
|
+
throw new InvalidError(`row ${at + 1} has ${extra.join(', ')}, which the first row has not: insert rows of one shape`);
|
|
732
|
+
}
|
|
733
|
+
for (const name of names) {
|
|
734
|
+
values.push(fieldOf(row[name], name, types));
|
|
735
|
+
}
|
|
736
|
+
return `(${names.map(() => '?').join(', ')})`;
|
|
737
|
+
});
|
|
738
|
+
return new Sql(`insert into ${identOf(table)} (${names.map(identOf).join(', ')}) values ${tuples.join(', ')}`, values);
|
|
739
|
+
}
|
|
740
|
+
/** A row's field as it is written: an array or an object as its JSON. */
|
|
741
|
+
function fieldOf(value, name, types) {
|
|
742
|
+
if (value === undefined) {
|
|
743
|
+
throw new InvalidError(`${name} is undefined, which never sets a column to null: leave the field out, or say null`);
|
|
744
|
+
}
|
|
745
|
+
if (types[name] === 'json' ||
|
|
746
|
+
(typeof value === 'object' &&
|
|
747
|
+
value !== null &&
|
|
748
|
+
!(value instanceof Date) &&
|
|
749
|
+
!(value instanceof Uint8Array))) {
|
|
750
|
+
return JSON.stringify(value);
|
|
751
|
+
}
|
|
752
|
+
return cellOf(value, name);
|
|
753
|
+
}
|
|
754
|
+
/** A stored value as its column's type reads it. */
|
|
755
|
+
function typedOf(value, type, column) {
|
|
756
|
+
if (value === null) {
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
759
|
+
switch (type) {
|
|
760
|
+
case 'bool':
|
|
761
|
+
if (value === 0 || value === 1) {
|
|
762
|
+
return value === 1;
|
|
763
|
+
}
|
|
764
|
+
break;
|
|
765
|
+
case 'time':
|
|
766
|
+
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
767
|
+
return new Date(Number(value));
|
|
768
|
+
}
|
|
769
|
+
break;
|
|
770
|
+
case 'json':
|
|
771
|
+
if (typeof value === 'string') {
|
|
772
|
+
return JSON.parse(value);
|
|
773
|
+
}
|
|
774
|
+
break;
|
|
775
|
+
case 'bigint':
|
|
776
|
+
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
777
|
+
return BigInt(value);
|
|
778
|
+
}
|
|
779
|
+
break;
|
|
780
|
+
}
|
|
781
|
+
throw new InvalidError(`column ${column}: ${String(value)} does not read as ${type}`);
|
|
782
|
+
}
|
|
783
|
+
function whole(n, what) {
|
|
784
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
785
|
+
throw new InvalidError(`${what} of ${n}: a whole number`);
|
|
786
|
+
}
|
|
787
|
+
return n;
|
|
788
|
+
}
|