@forestfuture/active-record 0.8.2 → 0.9.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/dist/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-D3nP3g83.mjs → batch-Ca1JtVcK.mjs} +3255 -2527
- package/dist/cli.d.mts +4 -4
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +19 -18
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +9 -4
- package/dist/for-adapters-Bl6BCiR1.mjs +12 -0
- package/dist/{for-adapters-CgEQfuyD.mjs → for-adapters-D35a5x3t.mjs} +6 -3
- package/dist/{for-adapters-DAn1wSYz.d.mts → for-adapters-DoyXc8Dq.d.mts} +1 -1
- package/dist/{generated-model-FB7oT7V1.mjs → generated-model-L4WAqgOZ.mjs} +1949 -1149
- package/dist/{epoch-storage-C7186hd1.mjs → identifiers-CzqYL_nC.mjs} +248 -223
- package/dist/{index-BfX3Dgy_.d.mts → index-Fq4gT3c8.d.mts} +115 -96
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -5
- package/dist/metadata-BIUbGJlS.d.mts +363 -0
- package/dist/{plugin-BY2QaRpq.mjs → plugin-BHUP4ssD.mjs} +10 -7
- package/dist/{plugin-IHD0I6Rg.mjs → plugin-BMAJKgj6.mjs} +7 -7
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +28 -4
- package/dist/{src-DnuvSHF6.mjs → src-fYq-nVHE.mjs} +2 -2
- package/dist/{storage-override-BFC-GSR0.mjs → storage-override-yF2NT5ST.mjs} +1 -1
- package/dist/{validations-DFLjJ203.d.mts → validations-CKPJoSj4.d.mts} +290 -103
- package/llms-full.txt +8280 -4094
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +4 -3
- package/dist/for-adapters-l4rNitkK.mjs +0 -31
- package/dist/metadata-CzntpYzC.d.mts +0 -182
|
@@ -19,6 +19,13 @@ var NoDatabase = class extends ActiveRecordError {
|
|
|
19
19
|
var RecordNotFound = class extends ActiveRecordError {
|
|
20
20
|
name = "RecordNotFound";
|
|
21
21
|
};
|
|
22
|
+
/**
|
|
23
|
+
* A token a finder that must find a record was given isn't valid (#517): it was changed, signed
|
|
24
|
+
* with another secret, made for another purpose, or has expired.
|
|
25
|
+
*/
|
|
26
|
+
var InvalidToken = class extends ActiveRecordError {
|
|
27
|
+
name = "InvalidToken";
|
|
28
|
+
};
|
|
22
29
|
/** `sole()` or `findSoleBy()` matched more than one record. */
|
|
23
30
|
var SoleRecordExceeded = class extends ActiveRecordError {
|
|
24
31
|
name = "SoleRecordExceeded";
|
|
@@ -31,7 +38,7 @@ var MissingAttribute = class extends ActiveRecordError {
|
|
|
31
38
|
var DeleteRestriction = class extends ActiveRecordError {
|
|
32
39
|
name = "DeleteRestriction";
|
|
33
40
|
};
|
|
34
|
-
/** `last()` can't reverse an order given as an `sql` fragment
|
|
41
|
+
/** `last()` can't reverse an order given as an `sql` fragment. */
|
|
35
42
|
var IrreversibleOrder = class extends ActiveRecordError {
|
|
36
43
|
name = "IrreversibleOrder";
|
|
37
44
|
};
|
|
@@ -116,6 +123,20 @@ var RecordNotSaved = class extends ActiveRecordError {
|
|
|
116
123
|
name = "RecordNotSaved";
|
|
117
124
|
};
|
|
118
125
|
/**
|
|
126
|
+
* A save, destroy or `touch()` of a record whose row another write changed since it was loaded
|
|
127
|
+
* (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
|
|
128
|
+
*/
|
|
129
|
+
var StaleRecord = class extends ActiveRecordError {
|
|
130
|
+
name = "StaleRecord";
|
|
131
|
+
record;
|
|
132
|
+
action;
|
|
133
|
+
constructor(record, action, options) {
|
|
134
|
+
super(`Attempted to ${action} a stale ${record.constructor.name} record`, options);
|
|
135
|
+
this.record = record;
|
|
136
|
+
this.action = action;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
119
140
|
* `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
|
|
120
141
|
* `afterDestroy`, `afterTouch`), or from an around callback once its `next()` resolved. That's a
|
|
121
142
|
* mistake: the write already succeeded and nothing rolls back.
|
|
@@ -151,7 +172,7 @@ var ReadonlyAssociation = class extends ActiveRecordError {
|
|
|
151
172
|
};
|
|
152
173
|
/**
|
|
153
174
|
* A polymorphic belongsTo's type that names none of the Models it lists (#60), read from the
|
|
154
|
-
* database
|
|
175
|
+
* database.
|
|
155
176
|
*/
|
|
156
177
|
var UnknownModelName = class extends ActiveRecordError {
|
|
157
178
|
name = "UnknownModelName";
|
|
@@ -163,7 +184,7 @@ var AssociationNotLoaded = class extends ActiveRecordError {
|
|
|
163
184
|
// src/naming.ts
|
|
164
185
|
/**
|
|
165
186
|
* Converts a camelCase attribute name to its snake_case column name, treating
|
|
166
|
-
* a run of capitals as one word
|
|
187
|
+
* a run of capitals as one word: `htmlURL` → `html_url`,
|
|
167
188
|
* `userID` → `user_id`, `sha256Hash` → `sha256_hash`.
|
|
168
189
|
*/
|
|
169
190
|
function underscore(name) {
|
|
@@ -173,6 +194,10 @@ function underscore(name) {
|
|
|
173
194
|
function camelize(name) {
|
|
174
195
|
return name.replace(/_([a-z\d])/g, (_, letter) => letter.toUpperCase());
|
|
175
196
|
}
|
|
197
|
+
/** A name with its first letter capitalized, as a method's name holds it: `authToken` → `AuthToken`. */
|
|
198
|
+
function capitalized(name) {
|
|
199
|
+
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
200
|
+
}
|
|
176
201
|
// src/inflections.ts
|
|
177
202
|
/** Words whose plural no rule makes: singular, then plural. */
|
|
178
203
|
const IRREGULARS = [
|
|
@@ -183,7 +208,7 @@ const IRREGULARS = [
|
|
|
183
208
|
["move", "moves"],
|
|
184
209
|
["zombie", "zombies"]
|
|
185
210
|
];
|
|
186
|
-
/** Plural rules in
|
|
211
|
+
/** Plural rules in order of definition. The last one that matches wins. */
|
|
187
212
|
const PLURALS = [
|
|
188
213
|
[/$/, "s"],
|
|
189
214
|
[/s$/i, "s"],
|
|
@@ -208,7 +233,7 @@ const PLURALS = [
|
|
|
208
233
|
[/(quiz)$/i, "$1zes"],
|
|
209
234
|
...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, plural))
|
|
210
235
|
];
|
|
211
|
-
/** Singular rules, likewise in
|
|
236
|
+
/** Singular rules, likewise in order of definition. */
|
|
212
237
|
const SINGULARS = [
|
|
213
238
|
[/s$/i, ""],
|
|
214
239
|
[/(ss)$/i, "$1"],
|
|
@@ -239,16 +264,16 @@ const SINGULARS = [
|
|
|
239
264
|
[/(database)s$/i, "$1"],
|
|
240
265
|
...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, singular))
|
|
241
266
|
];
|
|
242
|
-
/** Words with no plural, matched as the last word
|
|
267
|
+
/** Words with no plural, matched as the last word. */
|
|
243
268
|
const UNCOUNTABLE = /\b(?:equipment|information|rice|money|species|series|fish|sheep|jeans|police)$/i;
|
|
244
269
|
/**
|
|
245
|
-
*
|
|
270
|
+
* Irregular words: rules turning either form into `into` (the plural for plural rules, the
|
|
246
271
|
* singular for singular ones), keeping the first letter's case.
|
|
247
272
|
*/
|
|
248
273
|
function irregular(singular, plural, into) {
|
|
249
274
|
return [[new RegExp(`(${singular[0]})${singular.slice(1)}$`, "i"), `$1${into.slice(1)}`], [new RegExp(`(${plural[0]})${plural.slice(1)}$`, "i"), `$1${into.slice(1)}`]];
|
|
250
275
|
}
|
|
251
|
-
/** Applies the last rule that matches
|
|
276
|
+
/** Applies the last rule that matches; uncountable words stay as they are. */
|
|
252
277
|
function inflect(word, rules) {
|
|
253
278
|
if (word === "" || UNCOUNTABLE.test(word)) return word;
|
|
254
279
|
for (let index = rules.length - 1; index >= 0; index--) {
|
|
@@ -257,11 +282,11 @@ function inflect(word, rules) {
|
|
|
257
282
|
}
|
|
258
283
|
return word;
|
|
259
284
|
}
|
|
260
|
-
/**
|
|
285
|
+
/** A word's plural: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
|
|
261
286
|
function pluralize(word) {
|
|
262
287
|
return inflect(word, PLURALS);
|
|
263
288
|
}
|
|
264
|
-
/**
|
|
289
|
+
/** A word's singular: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
|
|
265
290
|
function singularize(word) {
|
|
266
291
|
return inflect(word, SINGULARS);
|
|
267
292
|
}
|
|
@@ -313,7 +338,7 @@ function repeatProblem(entries) {
|
|
|
313
338
|
}
|
|
314
339
|
/**
|
|
315
340
|
* The validations an enum declared `validate: true` adds, before a Model's own: its value must be
|
|
316
|
-
* one of its names, and not null unless `allowNull
|
|
341
|
+
* one of its names, and not null unless `allowNull`.
|
|
317
342
|
*/
|
|
318
343
|
function enumValidations(definitions) {
|
|
319
344
|
return [...definitions].flatMap(([attribute, { enum: values, validate = false }]) => {
|
|
@@ -345,49 +370,6 @@ function enumValuesOf(model, attribute) {
|
|
|
345
370
|
if (values === void 0) throw new UnknownAttribute(`${model.name} has no enum attribute "${attribute}"`);
|
|
346
371
|
return mappingOf(values);
|
|
347
372
|
}
|
|
348
|
-
// src/identifiers.ts
|
|
349
|
-
/** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
|
|
350
|
-
function isIdentifier(name) {
|
|
351
|
-
return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
|
|
352
|
-
}
|
|
353
|
-
/** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
|
|
354
|
-
const reservedWords = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" "));
|
|
355
|
-
// src/binary-values.ts
|
|
356
|
-
/** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
|
|
357
|
-
function castBinary(value) {
|
|
358
|
-
if (value instanceof Uint8Array) return value;
|
|
359
|
-
return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
|
|
360
|
-
}
|
|
361
|
-
/**
|
|
362
|
-
* A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
|
|
363
|
-
* a `bytea` as a `Buffer`.
|
|
364
|
-
*/
|
|
365
|
-
function readBinary(cell) {
|
|
366
|
-
if (cell instanceof Uint8Array) return Uint8Array.from(cell);
|
|
367
|
-
return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
|
|
368
|
-
}
|
|
369
|
-
/** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
|
|
370
|
-
function isSameCell(a, b) {
|
|
371
|
-
if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
|
|
372
|
-
return a.length === b.length && a.every((byte, index) => byte === b[index]);
|
|
373
|
-
}
|
|
374
|
-
/** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
|
|
375
|
-
const digitCodes = new TextEncoder().encode("0123456789abcdef");
|
|
376
|
-
const decoder = new TextDecoder();
|
|
377
|
-
/**
|
|
378
|
-
* Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
|
|
379
|
-
* digits' character codes are written into one array and decoded once: mapping each byte to a
|
|
380
|
-
* string of its own takes many times the memory and time, which a large file can't afford.
|
|
381
|
-
*/
|
|
382
|
-
function hexOf(bytes) {
|
|
383
|
-
const text = new Uint8Array(bytes.length * 2);
|
|
384
|
-
for (let index = 0; index < bytes.length; index++) {
|
|
385
|
-
const byte = bytes[index];
|
|
386
|
-
text[index * 2] = digitCodes[byte >> 4];
|
|
387
|
-
text[index * 2 + 1] = digitCodes[byte & 15];
|
|
388
|
-
}
|
|
389
|
-
return decoder.decode(text);
|
|
390
|
-
}
|
|
391
373
|
// src/calendar-values.ts
|
|
392
374
|
/** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
|
|
393
375
|
const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
|
|
@@ -428,6 +410,179 @@ function withoutTrailingZeros(digits) {
|
|
|
428
410
|
while (digits[end - 1] === "0") end--;
|
|
429
411
|
return digits.slice(0, end);
|
|
430
412
|
}
|
|
413
|
+
// src/decimal-values.ts
|
|
414
|
+
/**
|
|
415
|
+
* A decimal number: a sign, digits with an optional point (`1.5`, `5.`, `.5`), an optional
|
|
416
|
+
* exponent, and spaces around it. Digits after the point only follow a point, so no run of digits
|
|
417
|
+
* can match two ways (ReDoS).
|
|
418
|
+
*/
|
|
419
|
+
const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
|
|
420
|
+
/** The most digits Postgres's `numeric` holds before its point, and after it. */
|
|
421
|
+
const maxWholeDigits = 131072;
|
|
422
|
+
const maxFractionDigits = 16383;
|
|
423
|
+
/**
|
|
424
|
+
* The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
|
|
425
|
+
* point, an exponent and spaces. Longer text is refused before it's read.
|
|
426
|
+
*/
|
|
427
|
+
const maxTextLength = 147519;
|
|
428
|
+
/** The significant digits a number keeps when it's cast to a decimal. */
|
|
429
|
+
const numberPrecision = 16;
|
|
430
|
+
/**
|
|
431
|
+
* An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
|
|
432
|
+
* 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
|
|
433
|
+
* Postgres's `numeric` holds, is `uncastable`.
|
|
434
|
+
*/
|
|
435
|
+
function castDecimal(value) {
|
|
436
|
+
if (typeof value === "bigint") return canonical(String(value));
|
|
437
|
+
if (typeof value === "number") return castNumber(value);
|
|
438
|
+
return typeof value === "string" ? canonical(value) : uncastable;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
|
|
442
|
+
* cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
|
|
443
|
+
* significant digits, a whole number past a safe integer too.
|
|
444
|
+
*/
|
|
445
|
+
function readDecimal(cell) {
|
|
446
|
+
if (typeof cell === "number") return castNumber(cell);
|
|
447
|
+
return typeof cell === "string" ? canonical(cell) : uncastable;
|
|
448
|
+
}
|
|
449
|
+
function castNumber(value) {
|
|
450
|
+
if (!Number.isFinite(value)) return uncastable;
|
|
451
|
+
const decimal = canonical(value.toPrecision(numberPrecision));
|
|
452
|
+
return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
|
|
456
|
+
* no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
|
|
457
|
+
*/
|
|
458
|
+
function canonical(text) {
|
|
459
|
+
const parts = partsOf(text);
|
|
460
|
+
if (parts === void 0) return uncastable;
|
|
461
|
+
const { negative, digits, point } = parts;
|
|
462
|
+
const first = digits.search(/[1-9]/);
|
|
463
|
+
if (first === -1) return "0";
|
|
464
|
+
const last = lastNonZero(digits) + 1;
|
|
465
|
+
if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
|
|
466
|
+
const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
|
|
467
|
+
return isWithinDouble(decimal) ? decimal : uncastable;
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
|
|
471
|
+
* underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
|
|
472
|
+
* which reads as NULL, or as 0, so every database refuses one alike (#391).
|
|
473
|
+
*/
|
|
474
|
+
function isWithinDouble(decimal) {
|
|
475
|
+
const number = Number(decimal);
|
|
476
|
+
return Number.isFinite(number) && number !== 0;
|
|
477
|
+
}
|
|
478
|
+
/** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
|
|
479
|
+
function partsOf(text) {
|
|
480
|
+
if (text.length > maxTextLength) return void 0;
|
|
481
|
+
const match = decimalText.exec(text);
|
|
482
|
+
if (match === null) return void 0;
|
|
483
|
+
const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
|
|
484
|
+
return {
|
|
485
|
+
negative: sign === "-",
|
|
486
|
+
digits: whole + (pointed ?? unpointed ?? ""),
|
|
487
|
+
point: whole.length + Number(exponent)
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
|
|
492
|
+
* on a long run of zeros it takes quadratic time.
|
|
493
|
+
*/
|
|
494
|
+
function lastNonZero(digits) {
|
|
495
|
+
let index = digits.length - 1;
|
|
496
|
+
while (digits[index] === "0") index--;
|
|
497
|
+
return index;
|
|
498
|
+
}
|
|
499
|
+
/** Significant `digits` with the point `point` digits after the first, padded with zeros. */
|
|
500
|
+
function placePoint(digits, point) {
|
|
501
|
+
if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
|
|
502
|
+
if (point >= digits.length) return digits + "0".repeat(point - digits.length);
|
|
503
|
+
return `${digits.slice(0, point)}.${digits.slice(point)}`;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
|
|
507
|
+
* by the digits before the point (more is larger), then digit by digit, which is exact.
|
|
508
|
+
*/
|
|
509
|
+
function compareDecimals(a, b) {
|
|
510
|
+
const [signA, signB] = [signOf(a), signOf(b)];
|
|
511
|
+
if (signA !== signB) return Math.sign(signA - signB);
|
|
512
|
+
const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
|
|
513
|
+
return signA < 0 ? -order : order;
|
|
514
|
+
}
|
|
515
|
+
function signOf(decimal) {
|
|
516
|
+
if (decimal === "0") return 0;
|
|
517
|
+
return decimal.startsWith("-") ? -1 : 1;
|
|
518
|
+
}
|
|
519
|
+
function compareMagnitudes(a, b) {
|
|
520
|
+
const [wholeA = "", fractionA = ""] = a.split(".");
|
|
521
|
+
const [wholeB = "", fractionB = ""] = b.split(".");
|
|
522
|
+
if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
|
|
523
|
+
const width = Math.max(fractionA.length, fractionB.length);
|
|
524
|
+
const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
|
|
525
|
+
if (left === right) return 0;
|
|
526
|
+
return left < right ? -1 : 1;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Where a decimal falls against a bound given as a number or decimal text: exactly, as
|
|
530
|
+
* `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
|
|
531
|
+
* every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
|
|
532
|
+
*/
|
|
533
|
+
function orderDecimal(value, bound) {
|
|
534
|
+
if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
|
|
535
|
+
const decimal = castDecimal(bound);
|
|
536
|
+
return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
|
|
537
|
+
}
|
|
538
|
+
/** The most digits Postgres's `numeric` takes as a precision or a scale. */
|
|
539
|
+
const maxDigits = 1e3;
|
|
540
|
+
/** Whether `value` is a whole number of digits from `least` to 1000. */
|
|
541
|
+
function isDigitCount(value, least) {
|
|
542
|
+
return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Why a precision and scale can't be a `NUMERIC(p, s)`'s, as the words after "has", or undefined:
|
|
546
|
+
* a precision is 1 to 1000 digits, and a scale 0 to the precision. The spec, the schema readers and
|
|
547
|
+
* the generators all check it here (#398).
|
|
548
|
+
*/
|
|
549
|
+
function digitsProblem({ precision, scale }) {
|
|
550
|
+
if (precision !== void 0 && !isDigitCount(precision, 1)) return `a precision of ${precision}; a precision is 1 to 1000 digits`;
|
|
551
|
+
if (scale !== void 0 && !isDigitCount(scale, 0)) return `a scale of ${scale}; a scale is 0 to 1000 digits`;
|
|
552
|
+
if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
|
|
553
|
+
return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* A decimal in its one form, rounded to its scale, half away from zero, as Postgres's `numeric`
|
|
557
|
+
* rounds; `uncastable` when its digits before the point are more than the precision
|
|
558
|
+
* leaves them. A precision without a scale has a scale of 0, as SQL's `NUMERIC(10)` does.
|
|
559
|
+
*/
|
|
560
|
+
function limitDecimal(decimal, { precision, scale }) {
|
|
561
|
+
const places = scale ?? (precision === void 0 ? void 0 : 0);
|
|
562
|
+
const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
|
|
563
|
+
if (precision === void 0 || rounded === uncastable) return rounded;
|
|
564
|
+
const whole = rounded.replace("-", "").split(".")[0];
|
|
565
|
+
return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* A decimal in its one form, rounded to `places` digits after the point, half away from zero; or
|
|
569
|
+
* `uncastable` when rounding carries it past a double's range.
|
|
570
|
+
*/
|
|
571
|
+
function roundDecimal(decimal, places) {
|
|
572
|
+
const negative = decimal.startsWith("-");
|
|
573
|
+
const [whole = "", fraction = ""] = decimal.replace("-", "").split(".");
|
|
574
|
+
if (fraction.length <= places) return decimal;
|
|
575
|
+
const kept = whole + fraction.slice(0, places);
|
|
576
|
+
const digits = fraction[places] >= "5" ? incremented(kept) : kept;
|
|
577
|
+
const point = digits.length - places;
|
|
578
|
+
return canonical(`${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`);
|
|
579
|
+
}
|
|
580
|
+
/** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
|
|
581
|
+
function incremented(digits) {
|
|
582
|
+
let index = digits.length - 1;
|
|
583
|
+
while (index >= 0 && digits[index] === "9") index--;
|
|
584
|
+
return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
|
|
585
|
+
}
|
|
431
586
|
// src/conversion.ts
|
|
432
587
|
/** A value that can't be read as the attribute's type. */
|
|
433
588
|
const uncastable = Symbol("uncastable");
|
|
@@ -577,8 +732,8 @@ function customConverter(type, stored) {
|
|
|
577
732
|
}
|
|
578
733
|
/**
|
|
579
734
|
* An enum's values are its names (#340). A name is cast as itself, and so is the value it's
|
|
580
|
-
* stored as (`1`, or `"1"` from a form)
|
|
581
|
-
* cell of its type that's none of its values reads as null,
|
|
735
|
+
* stored as (`1`, or `"1"` from a form); anything else is `uncastable`. A stored
|
|
736
|
+
* cell of its type that's none of its values reads as null, so a row written
|
|
582
737
|
* by code that lists a newer value doesn't fail every list it's in; one of another type is
|
|
583
738
|
* `uncastable`, as for any attribute of that type (#159).
|
|
584
739
|
*/
|
|
@@ -602,7 +757,7 @@ function castValue(attribute, value) {
|
|
|
602
757
|
/**
|
|
603
758
|
* A condition's value as the attribute's type, or `uncastable`: as `castValue`, except that a
|
|
604
759
|
* finite number matches a string attribute as its decimal string (`7` → `"7"`), as `find` does
|
|
605
|
-
* for a text key
|
|
760
|
+
* for a text key, so a foreign key of another type still finds its target.
|
|
606
761
|
*/
|
|
607
762
|
function castCondition(attribute, value) {
|
|
608
763
|
return castKey(withoutPrecision(attribute), value);
|
|
@@ -810,180 +965,50 @@ function dayOf(day) {
|
|
|
810
965
|
function isInvalidDate(value) {
|
|
811
966
|
return value instanceof Date && Number.isNaN(value.getTime());
|
|
812
967
|
}
|
|
813
|
-
// src/
|
|
814
|
-
/**
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
*/
|
|
819
|
-
const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
|
|
820
|
-
/** The most digits Postgres's `numeric` holds before its point, and after it. */
|
|
821
|
-
const maxWholeDigits = 131072;
|
|
822
|
-
const maxFractionDigits = 16383;
|
|
823
|
-
/**
|
|
824
|
-
* The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
|
|
825
|
-
* point, an exponent and spaces. Longer text is refused before it's read.
|
|
826
|
-
*/
|
|
827
|
-
const maxTextLength = 147519;
|
|
828
|
-
/** A number's significant digits when it's cast, as Rails casts a float to a decimal. */
|
|
829
|
-
const numberPrecision = 16;
|
|
830
|
-
/**
|
|
831
|
-
* An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
|
|
832
|
-
* 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
|
|
833
|
-
* Postgres's `numeric` holds, is `uncastable`.
|
|
834
|
-
*/
|
|
835
|
-
function castDecimal(value) {
|
|
836
|
-
if (typeof value === "bigint") return canonical(String(value));
|
|
837
|
-
if (typeof value === "number") return castNumber(value);
|
|
838
|
-
return typeof value === "string" ? canonical(value) : uncastable;
|
|
839
|
-
}
|
|
840
|
-
/**
|
|
841
|
-
* A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
|
|
842
|
-
* cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
|
|
843
|
-
* significant digits, a whole number past a safe integer too, as Rails reads one on SQLite.
|
|
844
|
-
*/
|
|
845
|
-
function readDecimal(cell) {
|
|
846
|
-
if (typeof cell === "number") return castNumber(cell);
|
|
847
|
-
return typeof cell === "string" ? canonical(cell) : uncastable;
|
|
848
|
-
}
|
|
849
|
-
function castNumber(value) {
|
|
850
|
-
if (!Number.isFinite(value)) return uncastable;
|
|
851
|
-
const decimal = canonical(value.toPrecision(numberPrecision));
|
|
852
|
-
return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
|
|
853
|
-
}
|
|
854
|
-
/**
|
|
855
|
-
* Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
|
|
856
|
-
* no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
|
|
857
|
-
*/
|
|
858
|
-
function canonical(text) {
|
|
859
|
-
const parts = partsOf(text);
|
|
860
|
-
if (parts === void 0) return uncastable;
|
|
861
|
-
const { negative, digits, point } = parts;
|
|
862
|
-
const first = digits.search(/[1-9]/);
|
|
863
|
-
if (first === -1) return "0";
|
|
864
|
-
const last = lastNonZero(digits) + 1;
|
|
865
|
-
if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
|
|
866
|
-
const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
|
|
867
|
-
return isWithinDouble(decimal) ? decimal : uncastable;
|
|
868
|
-
}
|
|
869
|
-
/**
|
|
870
|
-
* Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
|
|
871
|
-
* underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
|
|
872
|
-
* which reads as NULL, or as 0, so every database refuses one alike (#391).
|
|
873
|
-
*/
|
|
874
|
-
function isWithinDouble(decimal) {
|
|
875
|
-
const number = Number(decimal);
|
|
876
|
-
return Number.isFinite(number) && number !== 0;
|
|
877
|
-
}
|
|
878
|
-
/** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
|
|
879
|
-
function partsOf(text) {
|
|
880
|
-
if (text.length > maxTextLength) return void 0;
|
|
881
|
-
const match = decimalText.exec(text);
|
|
882
|
-
if (match === null) return void 0;
|
|
883
|
-
const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
|
|
884
|
-
return {
|
|
885
|
-
negative: sign === "-",
|
|
886
|
-
digits: whole + (pointed ?? unpointed ?? ""),
|
|
887
|
-
point: whole.length + Number(exponent)
|
|
888
|
-
};
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
|
|
892
|
-
* on a long run of zeros it takes quadratic time.
|
|
893
|
-
*/
|
|
894
|
-
function lastNonZero(digits) {
|
|
895
|
-
let index = digits.length - 1;
|
|
896
|
-
while (digits[index] === "0") index--;
|
|
897
|
-
return index;
|
|
898
|
-
}
|
|
899
|
-
/** Significant `digits` with the point `point` digits after the first, padded with zeros. */
|
|
900
|
-
function placePoint(digits, point) {
|
|
901
|
-
if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
|
|
902
|
-
if (point >= digits.length) return digits + "0".repeat(point - digits.length);
|
|
903
|
-
return `${digits.slice(0, point)}.${digits.slice(point)}`;
|
|
904
|
-
}
|
|
905
|
-
/**
|
|
906
|
-
* Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
|
|
907
|
-
* by the digits before the point (more is larger), then digit by digit, which is exact.
|
|
908
|
-
*/
|
|
909
|
-
function compareDecimals(a, b) {
|
|
910
|
-
const [signA, signB] = [signOf(a), signOf(b)];
|
|
911
|
-
if (signA !== signB) return Math.sign(signA - signB);
|
|
912
|
-
const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
|
|
913
|
-
return signA < 0 ? -order : order;
|
|
914
|
-
}
|
|
915
|
-
function signOf(decimal) {
|
|
916
|
-
if (decimal === "0") return 0;
|
|
917
|
-
return decimal.startsWith("-") ? -1 : 1;
|
|
918
|
-
}
|
|
919
|
-
function compareMagnitudes(a, b) {
|
|
920
|
-
const [wholeA = "", fractionA = ""] = a.split(".");
|
|
921
|
-
const [wholeB = "", fractionB = ""] = b.split(".");
|
|
922
|
-
if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
|
|
923
|
-
const width = Math.max(fractionA.length, fractionB.length);
|
|
924
|
-
const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
|
|
925
|
-
if (left === right) return 0;
|
|
926
|
-
return left < right ? -1 : 1;
|
|
927
|
-
}
|
|
928
|
-
/**
|
|
929
|
-
* Where a decimal falls against a bound given as a number or decimal text: exactly, as
|
|
930
|
-
* `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
|
|
931
|
-
* every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
|
|
932
|
-
*/
|
|
933
|
-
function orderDecimal(value, bound) {
|
|
934
|
-
if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
|
|
935
|
-
const decimal = castDecimal(bound);
|
|
936
|
-
return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
|
|
937
|
-
}
|
|
938
|
-
/** The most digits Postgres's `numeric` takes as a precision or a scale. */
|
|
939
|
-
const maxDigits = 1e3;
|
|
940
|
-
/** Whether `value` is a whole number of digits from `least` to 1000. */
|
|
941
|
-
function isDigitCount(value, least) {
|
|
942
|
-
return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
|
|
968
|
+
// src/binary-values.ts
|
|
969
|
+
/** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
|
|
970
|
+
function castBinary(value) {
|
|
971
|
+
if (value instanceof Uint8Array) return value;
|
|
972
|
+
return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
|
|
943
973
|
}
|
|
944
974
|
/**
|
|
945
|
-
*
|
|
946
|
-
* a
|
|
947
|
-
* the generators all check it here (#398).
|
|
975
|
+
* A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
|
|
976
|
+
* a `bytea` as a `Buffer`.
|
|
948
977
|
*/
|
|
949
|
-
function
|
|
950
|
-
if (
|
|
951
|
-
|
|
952
|
-
if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
|
|
953
|
-
return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
|
|
978
|
+
function readBinary(cell) {
|
|
979
|
+
if (cell instanceof Uint8Array) return Uint8Array.from(cell);
|
|
980
|
+
return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
|
|
954
981
|
}
|
|
955
|
-
/**
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
*/
|
|
960
|
-
function limitDecimal(decimal, { precision, scale }) {
|
|
961
|
-
const places = scale ?? (precision === void 0 ? void 0 : 0);
|
|
962
|
-
const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
|
|
963
|
-
if (precision === void 0 || rounded === uncastable) return rounded;
|
|
964
|
-
const whole = rounded.replace("-", "").split(".")[0];
|
|
965
|
-
return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
|
|
982
|
+
/** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
|
|
983
|
+
function isSameCell(a, b) {
|
|
984
|
+
if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
|
|
985
|
+
return a.length === b.length && a.every((byte, index) => byte === b[index]);
|
|
966
986
|
}
|
|
987
|
+
/** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
|
|
988
|
+
const digitCodes = new TextEncoder().encode("0123456789abcdef");
|
|
989
|
+
const decoder = new TextDecoder();
|
|
967
990
|
/**
|
|
968
|
-
*
|
|
969
|
-
*
|
|
991
|
+
* Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
|
|
992
|
+
* digits' character codes are written into one array and decoded once: mapping each byte to a
|
|
993
|
+
* string of its own takes many times the memory and time, which a large file can't afford.
|
|
970
994
|
*/
|
|
971
|
-
function
|
|
972
|
-
const
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
return
|
|
979
|
-
}
|
|
980
|
-
/** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
|
|
981
|
-
function incremented(digits) {
|
|
982
|
-
let index = digits.length - 1;
|
|
983
|
-
while (index >= 0 && digits[index] === "9") index--;
|
|
984
|
-
return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
|
|
995
|
+
function hexOf(bytes) {
|
|
996
|
+
const text = new Uint8Array(bytes.length * 2);
|
|
997
|
+
for (let index = 0; index < bytes.length; index++) {
|
|
998
|
+
const byte = bytes[index];
|
|
999
|
+
text[index * 2] = digitCodes[byte >> 4];
|
|
1000
|
+
text[index * 2 + 1] = digitCodes[byte & 15];
|
|
1001
|
+
}
|
|
1002
|
+
return decoder.decode(text);
|
|
985
1003
|
}
|
|
986
1004
|
// src/epoch-storage.ts
|
|
987
1005
|
/** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
|
|
988
1006
|
const epochStorages = ["unixSeconds", "unixMilliseconds"];
|
|
989
|
-
|
|
1007
|
+
// src/identifiers.ts
|
|
1008
|
+
/** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
|
|
1009
|
+
function isIdentifier(name) {
|
|
1010
|
+
return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
|
|
1011
|
+
}
|
|
1012
|
+
/** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
|
|
1013
|
+
const reservedWords = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" "));
|
|
1014
|
+
export { UnknownAssociation as $, AssociationNotLoaded as A, MissingAttribute as B, pluralize as C, underscore as D, capitalized as E, IncompatibleRelation as F, RecordInvalid as G, NotNullViolation as H, InvalidForeignKey as I, RecordNotSaved as J, RecordNotDestroyed as K, InvalidModel as L, CheckViolation as M, ConstraintViolation as N, AbortAfterPersistence as O, DeleteRestriction as P, StrictValidationFailed as Q, InvalidToken as R, listedNames as S, camelize as T, ReadonlyAssociation as U, NoDatabase as V, RecordDestroyed as W, SoleRecordExceeded as X, RecordNotUnique as Y, StaleRecord as Z, enumEntries as _, isSameCell as a, enumValuesOf as b, castValue as c, uncastable as d, UnknownAttribute as et, writeUntypedValue as f, orderDecimal as g, digitsProblem as h, hexOf as i, CallbackAbort as j, ActiveRecordError as k, isInvalidDate as l, zonelessDateTime as m, reservedWords as n, abort as nt, castCondition as o, writeValue as p, RecordNotFound as q, epochStorages as r, castKey as s, isIdentifier as t, UnknownModelName as tt, readValue as u, enumProblem as v, singularize as w, isEnumValues as x, enumValidations as y, IrreversibleOrder as z };
|