@kiri-orm/core 0.1.6 → 0.2.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 +27 -15
- package/dist/types/client/model-handle.d.ts +4 -1
- package/dist/types/connection.d.ts +66 -0
- package/dist/types/crud/chunk.d.ts +10 -0
- package/dist/types/crud/database-errors.d.ts +61 -0
- package/dist/types/crud/errors.d.ts +10 -0
- package/dist/types/crud/fast-path.d.ts +73 -0
- package/dist/types/crud/index.d.ts +4 -1
- package/dist/types/crud/insert-many.d.ts +12 -13
- package/dist/types/crud/order.d.ts +28 -0
- package/dist/types/crud/repository.d.ts +5 -3
- package/dist/types/crud/row-mapping.d.ts +9 -1
- package/dist/types/crud/upsert.d.ts +39 -0
- package/dist/types/crud/value.d.ts +39 -0
- package/dist/types/dialect/date-bucket.d.ts +2 -2
- package/dist/types/dialect/index.d.ts +1 -0
- package/dist/types/dialect/transaction-guard.d.ts +31 -0
- package/dist/types/domain/compile.d.ts +17 -0
- package/dist/types/fields/filter-value.d.ts +21 -0
- package/dist/types/fields/registry.d.ts +1 -0
- package/dist/types/fields/storage.d.ts +28 -0
- package/dist/types/fields/types/date.d.ts +6 -6
- package/dist/types/fields/types/decimal.d.ts +40 -0
- package/dist/types/global/errors.d.ts +3 -0
- package/dist/types/global/index.d.ts +2 -0
- package/dist/types/global/normalize-dates.d.ts +11 -0
- package/dist/types/global/state.d.ts +2 -0
- package/dist/types/global/transaction.d.ts +10 -13
- package/dist/types/index.d.ts +2 -0
- package/dist/types/meta/create-table-once.d.ts +15 -0
- package/dist/types/meta/snapshot.d.ts +10 -0
- package/dist/types/meta/upsert.d.ts +16 -0
- package/dist/types/migrations/diff.d.ts +25 -2
- package/dist/types/models/constraints.d.ts +27 -0
- package/dist/types/relations/pivot-schema.d.ts +1 -1
- package/dist/types/schema/alter-column.d.ts +46 -0
- package/dist/types/schema/build-column.d.ts +11 -0
- package/dist/types/schema/index.d.ts +1 -0
- package/dist/types/schema/introspect-indexes.d.ts +9 -0
- package/dist/types/schema/normalize-dates.d.ts +41 -0
- package/dist/types/transaction/after-commit.d.ts +42 -0
- package/dist/types/transaction/context.d.ts +39 -0
- package/dist/types/uow/entity.d.ts +39 -29
- package/dist/types/uow/hooks.d.ts +6 -1
- package/dist/types/uow/lifecycle.d.ts +82 -0
- package/dist/types/uow/unit-of-work.d.ts +11 -7
- package/package.json +8 -5
- package/src/client/model-handle.js +14 -4
- package/src/client/orm-client.js +10 -5
- package/src/connection.js +53 -7
- package/src/crud/aggregate-filter.js +8 -2
- package/src/crud/aggregate-spec.js +2 -2
- package/src/crud/aggregate.js +16 -5
- package/src/crud/chunk.js +10 -0
- package/src/crud/create-many.js +52 -29
- package/src/crud/database-errors.js +107 -0
- package/src/crud/errors.js +14 -0
- package/src/crud/fast-path.js +449 -0
- package/src/crud/index.js +4 -1
- package/src/crud/insert-many.js +42 -7
- package/src/crud/map-filter.js +2 -1
- package/src/crud/order.js +59 -9
- package/src/crud/repository.js +106 -38
- package/src/crud/row-mapping.js +32 -7
- package/src/crud/upsert.js +203 -0
- package/src/crud/value.js +71 -0
- package/src/dialect/index.js +1 -0
- package/src/dialect/transaction-guard.js +254 -0
- package/src/domain/compile.js +85 -12
- package/src/dto/field-schema.js +5 -0
- package/src/fields/default-registry.js +3 -1
- package/src/fields/filter-value.js +87 -0
- package/src/fields/registry.js +1 -0
- package/src/fields/storage.js +50 -0
- package/src/fields/types/date.js +16 -3
- package/src/fields/types/decimal.js +147 -0
- package/src/fields/types/integer.js +7 -0
- package/src/global/connect.js +25 -1
- package/src/global/create-model.js +59 -57
- package/src/global/errors.js +1 -1
- package/src/global/index.js +2 -0
- package/src/global/normalize-dates.js +15 -0
- package/src/global/state.js +3 -0
- package/src/global/transaction.js +12 -14
- package/src/index.js +2 -0
- package/src/meta/create-table-once.js +23 -0
- package/src/meta/schema.js +15 -6
- package/src/meta/snapshot.js +5 -0
- package/src/meta/upsert.js +28 -0
- package/src/migrations/describe.js +49 -0
- package/src/migrations/diff.js +50 -7
- package/src/migrations/generate.js +38 -2
- package/src/migrations/render.js +30 -12
- package/src/migrations/runner.js +40 -6
- package/src/models/constraints.js +96 -0
- package/src/models/define-model.js +4 -0
- package/src/models/inheritance.js +4 -1
- package/src/models/registry.js +2 -1
- package/src/relations/attach-detach.js +49 -18
- package/src/relations/cascade-delete.js +32 -7
- package/src/relations/eager-load.js +75 -51
- package/src/relations/pivot-schema.js +24 -3
- package/src/reports/report-handle.js +2 -1
- package/src/schema/alter-column.js +219 -0
- package/src/schema/build-column.js +28 -2
- package/src/schema/default-column-builders.js +16 -2
- package/src/schema/index.js +1 -0
- package/src/schema/introspect-indexes.js +22 -0
- package/src/schema/normalize-dates.js +58 -0
- package/src/schema/sync.js +16 -2
- package/src/transaction/after-commit.js +142 -0
- package/src/transaction/context.js +84 -0
- package/src/uow/entity.js +133 -133
- package/src/uow/hooks.js +9 -0
- package/src/uow/lifecycle.js +162 -0
- package/src/uow/unit-of-work.js +55 -60
- package/src/uow/with-unit-of-work.js +2 -1
package/src/fields/types/date.js
CHANGED
|
@@ -73,7 +73,8 @@ function parseString(field, raw) {
|
|
|
73
73
|
return format(y, m, d);
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
/** A Date built from local components (the pg driver's parse of a stored `date`) -> that local day. */
|
|
77
|
+
function fromLocalDateObject(dt) {
|
|
77
78
|
if (Number.isNaN(dt.getTime())) return null;
|
|
78
79
|
return format(dt.getFullYear(), dt.getMonth() + 1, dt.getDate());
|
|
79
80
|
}
|
|
@@ -93,6 +94,10 @@ const DAY_MS = 86_400_000;
|
|
|
93
94
|
* wrote it, so the local day is the right one.
|
|
94
95
|
* An instant at exactly UTC midnight is read as that UTC day, one at exactly local midnight as
|
|
95
96
|
* that local day; anything else (a date carrying a time) falls back to the UTC day.
|
|
97
|
+
*
|
|
98
|
+
* A Date passed in as a value uses the same rule (since 0.2.0): a date picker's
|
|
99
|
+
* `new Date(2024, 0, 1)` is the 1st in every time zone (Tokyo: 2023-12-31T15:00Z is local
|
|
100
|
+
* midnight), and `new Date("2024-01-01")` is the 1st too (UTC midnight).
|
|
96
101
|
*/
|
|
97
102
|
function fromEpochMs(ms) {
|
|
98
103
|
if (!Number.isFinite(ms)) return null;
|
|
@@ -101,12 +106,20 @@ function fromEpochMs(ms) {
|
|
|
101
106
|
const utcDay = format(dt.getUTCFullYear(), dt.getUTCMonth() + 1, dt.getUTCDate());
|
|
102
107
|
if (((ms % DAY_MS) + DAY_MS) % DAY_MS === 0) return utcDay;
|
|
103
108
|
const isLocalMidnight = dt.getHours() === 0 && dt.getMinutes() === 0 && dt.getSeconds() === 0 && dt.getMilliseconds() === 0;
|
|
104
|
-
return isLocalMidnight ?
|
|
109
|
+
return isLocalMidnight ? fromLocalDateObject(dt) : utcDay;
|
|
105
110
|
}
|
|
106
111
|
|
|
107
112
|
export const dateType = {
|
|
108
113
|
name: "date",
|
|
109
114
|
|
|
115
|
+
/**
|
|
116
|
+
* A stored Postgres `date` arrives as a Date the pg driver built at LOCAL midnight of that day,
|
|
117
|
+
* so it is read back with local getters - unlike a Date passed in, which means its UTC day.
|
|
118
|
+
*/
|
|
119
|
+
fromStorage(field, value, dialect) {
|
|
120
|
+
return dialect === "postgres" && value instanceof Date ? fromLocalDateObject(value) ?? value : value;
|
|
121
|
+
},
|
|
122
|
+
|
|
110
123
|
// validate stays strict: it only accepts the canonical stored form.
|
|
111
124
|
validate(field, value) {
|
|
112
125
|
const ok =
|
|
@@ -127,7 +140,7 @@ export const dateType = {
|
|
|
127
140
|
cast(field, value) {
|
|
128
141
|
let result = null;
|
|
129
142
|
if (typeof value === "string") result = parseString(field, value);
|
|
130
|
-
else if (value instanceof Date) result =
|
|
143
|
+
else if (value instanceof Date) result = fromEpochMs(value.getTime()); // same rule as epoch ms (since 0.2.0)
|
|
131
144
|
else if (typeof value === "number") result = fromEpochMs(value);
|
|
132
145
|
|
|
133
146
|
if (result === null) {
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { CastError } from "../errors.js";
|
|
2
|
+
import { DialectValue } from "../storage.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `decimal` - an exact base-10 number, for money, prices, rates and quantities (since 0.2.0).
|
|
6
|
+
*
|
|
7
|
+
* price: { type: "decimal", precision: 12, scale: 2 } // up to 9,999,999,999.99
|
|
8
|
+
*
|
|
9
|
+
* Its value is always a string in canonical form - "1234.50", "-0.05", "0.00" - exactly `scale`
|
|
10
|
+
* decimal places, never a JavaScript number, so nothing is ever rounded behind your back. Do
|
|
11
|
+
* arithmetic with a decimal library (decimal.js, big.js) or in SQL (atomic updates, sums).
|
|
12
|
+
*
|
|
13
|
+
* Input:
|
|
14
|
+
* - a string is exact: "12.5" becomes "12.50"; more decimal places than `scale` is an error;
|
|
15
|
+
* - a JavaScript number is approximate already (0.1 + 0.2 is 0.30000000000000004), so it is
|
|
16
|
+
* rounded to `scale` places, half away from zero;
|
|
17
|
+
* - a bigint is a whole number.
|
|
18
|
+
*
|
|
19
|
+
* Storage:
|
|
20
|
+
* - Postgres: `numeric(precision, scale)` - exact, and the driver returns it as text.
|
|
21
|
+
* - SQLite has no exact decimal type (a DECIMAL column silently stores floating point), so the
|
|
22
|
+
* value is stored as an integer scaled by 10^scale: "1234.50" with scale 2 is stored as 123450.
|
|
23
|
+
* Exact, sorts and compares correctly, and SUM() stays exact. The ORM converts on the way in
|
|
24
|
+
* (every write and every filter value, through DialectValue) and on the way out.
|
|
25
|
+
*
|
|
26
|
+
* Limits: `precision` (total significant digits) 1-15 and `scale` 0-precision. Fifteen digits is
|
|
27
|
+
* what a SQLite integer read back by the driver keeps exactly (JavaScript numbers are exact up to
|
|
28
|
+
* 2^53); with scale 2 that is 9,999,999,999,999.99. Defaults: precision 15, scale 2.
|
|
29
|
+
*/
|
|
30
|
+
export const MAX_DECIMAL_PRECISION = 15;
|
|
31
|
+
|
|
32
|
+
const shape = (field) => ({ precision: field.precision ?? MAX_DECIMAL_PRECISION, scale: field.scale ?? 2 });
|
|
33
|
+
|
|
34
|
+
const DECIMAL_TEXT = /^\s*([+-]?)(\d*)(?:\.(\d*))?\s*$/;
|
|
35
|
+
|
|
36
|
+
/** Canonical text with exactly `scale` places from sign, integer digits and fraction digits. */
|
|
37
|
+
function canonical(sign, int, frac, scale) {
|
|
38
|
+
const intDigits = int.replace(/^0+(?=\d)/, "") || "0";
|
|
39
|
+
const fracDigits = scale > 0 ? frac.padEnd(scale, "0").slice(0, scale) : "";
|
|
40
|
+
const isZero = /^0+$/.test(intDigits + fracDigits);
|
|
41
|
+
return `${sign === "-" && !isZero ? "-" : ""}${intDigits}${scale > 0 ? `.${fracDigits}` : ""}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function fromString(field, text) {
|
|
45
|
+
const { scale } = shape(field);
|
|
46
|
+
const match = DECIMAL_TEXT.exec(text);
|
|
47
|
+
if (!match || (match[2] === "" && (match[3] ?? "") === "")) return null;
|
|
48
|
+
const [, sign, int, frac = ""] = match;
|
|
49
|
+
if (frac.replace(/0+$/, "").length > scale) {
|
|
50
|
+
throw new CastError(`${JSON.stringify(text)} has more than ${scale} decimal place${scale === 1 ? "" : "s"}`, { fieldType: "decimal", value: text });
|
|
51
|
+
}
|
|
52
|
+
return canonical(sign, int, frac, scale);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function fromNumber(field, value) {
|
|
56
|
+
if (!Number.isFinite(value)) return null;
|
|
57
|
+
const { scale } = shape(field);
|
|
58
|
+
// Half away from zero, on the decimal text JavaScript would print, not on the binary value:
|
|
59
|
+
// 1.005 prints as "1.005" and rounds to "1.01" (toFixed(2) would give "1.00").
|
|
60
|
+
const text = Math.abs(value).toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 });
|
|
61
|
+
const [int, frac = ""] = text.split(".");
|
|
62
|
+
let digits = BigInt(int + frac.padEnd(scale, "0").slice(0, scale));
|
|
63
|
+
if (frac.length > scale && Number(frac[scale]) >= 5) digits += 1n;
|
|
64
|
+
return fromScaledInteger(value < 0 ? -digits : digits, scale);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The integer `digits` divided by 10^scale, as canonical text. */
|
|
68
|
+
function fromScaledInteger(digits, scale) {
|
|
69
|
+
const negative = digits < 0n;
|
|
70
|
+
const text = (negative ? -digits : digits).toString().padStart(scale + 1, "0");
|
|
71
|
+
const int = scale > 0 ? text.slice(0, -scale) : text;
|
|
72
|
+
const frac = scale > 0 ? text.slice(-scale) : "";
|
|
73
|
+
return canonical(negative ? "-" : "", int, frac, scale);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Canonical text -> the integer SQLite stores (exact: at most 15 digits, under 2^53). */
|
|
77
|
+
export function toScaledInteger(text, scale) {
|
|
78
|
+
const [int, frac = ""] = text.replace("-", "").split(".");
|
|
79
|
+
const n = Number(int + frac.padEnd(scale, "0"));
|
|
80
|
+
return text.startsWith("-") ? -n : n;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const decimalType = {
|
|
84
|
+
name: "decimal",
|
|
85
|
+
|
|
86
|
+
validateOptions(field) {
|
|
87
|
+
const errors = [];
|
|
88
|
+
const { precision, scale } = shape(field);
|
|
89
|
+
if (!Number.isInteger(precision) || precision < 1 || precision > MAX_DECIMAL_PRECISION) {
|
|
90
|
+
errors.push(`decimal field \`precision\` must be an integer from 1 to ${MAX_DECIMAL_PRECISION} (the digits SQLite keeps exactly)`);
|
|
91
|
+
}
|
|
92
|
+
if (!Number.isInteger(scale) || scale < 0 || scale > precision) {
|
|
93
|
+
errors.push("decimal field `scale` must be an integer from 0 to `precision`");
|
|
94
|
+
}
|
|
95
|
+
for (const bound of ["min", "max"]) {
|
|
96
|
+
if (field[bound] !== undefined) {
|
|
97
|
+
try {
|
|
98
|
+
if (decimalType.cast(field, field[bound]) === undefined) throw new Error();
|
|
99
|
+
} catch {
|
|
100
|
+
errors.push(`decimal field \`${bound}\` must be a decimal value (a string like "0.00", or a number)`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return errors;
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
validate(field, value) {
|
|
108
|
+
const { precision, scale } = shape(field);
|
|
109
|
+
if (typeof value !== "string" || !DECIMAL_TEXT.test(value)) {
|
|
110
|
+
return [`expected a decimal value like "12.50", got ${JSON.stringify(value)}`];
|
|
111
|
+
}
|
|
112
|
+
const errors = [];
|
|
113
|
+
const intDigits = value.replace("-", "").split(".")[0].replace(/^0+/, "");
|
|
114
|
+
if (intDigits.length > precision - scale) {
|
|
115
|
+
errors.push(`must have at most ${precision - scale} digit${precision - scale === 1 ? "" : "s"} before the decimal point (precision ${precision}, scale ${scale})`);
|
|
116
|
+
}
|
|
117
|
+
const asNumber = (text) => toScaledInteger(decimalType.cast(field, text), scale);
|
|
118
|
+
if (field.min !== undefined && asNumber(value) < asNumber(field.min)) errors.push(`must be >= ${decimalType.cast(field, field.min)} (got ${value})`);
|
|
119
|
+
if (field.max !== undefined && asNumber(value) > asNumber(field.max)) errors.push(`must be <= ${decimalType.cast(field, field.max)} (got ${value})`);
|
|
120
|
+
return errors;
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
cast(field, value) {
|
|
124
|
+
let result = null;
|
|
125
|
+
if (typeof value === "string") result = fromString(field, value);
|
|
126
|
+
else if (typeof value === "number") result = fromNumber(field, value);
|
|
127
|
+
else if (typeof value === "bigint") result = fromScaledInteger(value * 10n ** BigInt(shape(field).scale), shape(field).scale);
|
|
128
|
+
if (result === null) {
|
|
129
|
+
throw new CastError(`cannot cast ${typeof value === "bigint" ? `${value}n` : JSON.stringify(value)} to decimal`, { fieldType: "decimal", value });
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
/** The value as the database stores it - resolved per dialect when the query is bound. */
|
|
135
|
+
toStorage(field, value) {
|
|
136
|
+
const { scale } = shape(field);
|
|
137
|
+
return new DialectValue((dialect) => (dialect === "sqlite" ? toScaledInteger(value, scale) : value));
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
/** The stored value back to canonical text: SQLite gives the scaled integer, Postgres text. */
|
|
141
|
+
fromStorage(field, value, dialect) {
|
|
142
|
+
const { scale } = shape(field);
|
|
143
|
+
if (dialect === "sqlite" && typeof value === "number") return fromScaledInteger(BigInt(Math.round(value)), scale);
|
|
144
|
+
if (dialect === "sqlite" && typeof value === "bigint") return fromScaledInteger(value, scale);
|
|
145
|
+
return value;
|
|
146
|
+
},
|
|
147
|
+
};
|
|
@@ -32,6 +32,13 @@ export const integerType = {
|
|
|
32
32
|
errors.push(`expected an integer, got ${JSON.stringify(value)}`);
|
|
33
33
|
return errors;
|
|
34
34
|
}
|
|
35
|
+
// Past 2^53 a JavaScript number can't hold every whole number, so the value written may not be
|
|
36
|
+
// the one given (since 0.2.0). Note: a Postgres `integer` column holds 32 bits; a larger value
|
|
37
|
+
// fails there with OutOfRangeError.
|
|
38
|
+
if (!Number.isSafeInteger(value)) {
|
|
39
|
+
errors.push(`must be between ${Number.MIN_SAFE_INTEGER} and ${Number.MAX_SAFE_INTEGER} (got ${value})`);
|
|
40
|
+
return errors;
|
|
41
|
+
}
|
|
35
42
|
if (field.min !== undefined && value < field.min) {
|
|
36
43
|
errors.push(`must be >= ${field.min} (got ${value})`);
|
|
37
44
|
}
|
package/src/global/connect.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createConnection, closeConnection } from "../connection.js";
|
|
2
|
+
import { instrumentConnection } from "../dialect/transaction-guard.js";
|
|
2
3
|
import { state } from "./state.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -18,10 +19,32 @@ import { state } from "./state.js";
|
|
|
18
19
|
* @returns {import('knex').Knex}
|
|
19
20
|
*/
|
|
20
21
|
export function connect(configOrConnection) {
|
|
21
|
-
|
|
22
|
+
// A pool connect() built itself from a config is closed when it is replaced (before 0.1.7 it was
|
|
23
|
+
// left open: calling connect() again leaked it, and a leaked Postgres pool keeps the process
|
|
24
|
+
// alive). A Knex instance the app passed in is the app's to close, so it is left alone.
|
|
25
|
+
const previous = state.ownsConnection ? state.connection : null;
|
|
26
|
+
const ownsNew = typeof configOrConnection !== "function";
|
|
27
|
+
const next = ownsNew ? createConnection(configOrConnection) : instrumentConnection(configOrConnection);
|
|
28
|
+
state.connection = next;
|
|
29
|
+
state.ownsConnection = ownsNew;
|
|
30
|
+
if (previous && previous !== next) closeWhenIdle(previous);
|
|
22
31
|
return state.connection;
|
|
23
32
|
}
|
|
24
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Closes a replaced pool in the background (connect() is synchronous) once nothing is using it:
|
|
36
|
+
* destroying it right away would abort queries and transactions still running on it.
|
|
37
|
+
*/
|
|
38
|
+
function closeWhenIdle(db) {
|
|
39
|
+
const pool = db.client?.pool;
|
|
40
|
+
const busy = () => pool && (pool.numUsed() > 0 || pool.numPendingAcquires() > 0 || pool.numPendingCreates() > 0);
|
|
41
|
+
const attempt = () => {
|
|
42
|
+
if (busy()) setTimeout(attempt, 50).unref?.();
|
|
43
|
+
else closeConnection(db).catch(() => {});
|
|
44
|
+
};
|
|
45
|
+
attempt();
|
|
46
|
+
}
|
|
47
|
+
|
|
25
48
|
/**
|
|
26
49
|
* Returns the default connection set by `connect()`. Throws a clear
|
|
27
50
|
* error if `connect()` hasn't been called yet, rather than failing
|
|
@@ -45,5 +68,6 @@ export async function disconnect() {
|
|
|
45
68
|
if (state.connection) {
|
|
46
69
|
await closeConnection(state.connection);
|
|
47
70
|
state.connection = null;
|
|
71
|
+
state.ownsConnection = false;
|
|
48
72
|
}
|
|
49
73
|
}
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
diffEntity,
|
|
5
5
|
mergeRecordIntoEntity,
|
|
6
6
|
ENTITY_META,
|
|
7
|
+
originalValue,
|
|
7
8
|
} from "../uow/entity.js";
|
|
8
9
|
import { withPrimaryKey } from "../crud/select.js";
|
|
9
10
|
import { paginateWith } from "../crud/paginate.js";
|
|
@@ -14,6 +15,7 @@ import {
|
|
|
14
15
|
detachRelation,
|
|
15
16
|
} from "../relations/attach-detach.js";
|
|
16
17
|
import { createRecords } from "../crud/create-many.js";
|
|
18
|
+
import { upsertRecords } from "../crud/upsert.js";
|
|
17
19
|
import { assertPrimaryKeyUntouched } from "../crud/prepare-write.js";
|
|
18
20
|
import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
|
|
19
21
|
import { getConnection } from "./connect.js";
|
|
@@ -21,6 +23,8 @@ import { state } from "./state.js";
|
|
|
21
23
|
import { currentIdentityMap } from "./identity-scope.js";
|
|
22
24
|
import { primaryKeyOf } from "../models/primary-key.js";
|
|
23
25
|
import { SaveDeletedError } from "./errors.js";
|
|
26
|
+
import { resolveDb } from "../transaction/context.js";
|
|
27
|
+
import { saveEntityLifecycle, deleteEntityLifecycle } from "../uow/lifecycle.js";
|
|
24
28
|
|
|
25
29
|
const assertKnownHooks = (name, hooks) => {
|
|
26
30
|
for (const hookName of Object.keys(hooks)) {
|
|
@@ -104,11 +108,11 @@ function addMixinHooks(mixinName, hooks) {
|
|
|
104
108
|
* @returns {Model}
|
|
105
109
|
*/
|
|
106
110
|
export function extendModel(name, extension = {}) {
|
|
107
|
-
const { fields, relations, mixins, hooks, origin } = extension;
|
|
111
|
+
const { fields, relations, mixins, hooks, origin, constraints } = extension;
|
|
108
112
|
const targetIsMixin = state.registry.isAbstract(name);
|
|
109
113
|
if (hooks && !targetIsMixin) assertKnownHooks(name, hooks); // before anything is registered
|
|
110
114
|
state.registry.define(
|
|
111
|
-
{ extend: name, fields, relations, mixins },
|
|
115
|
+
{ extend: name, fields, relations, mixins, constraints },
|
|
112
116
|
{ origin },
|
|
113
117
|
);
|
|
114
118
|
if (targetIsMixin) addMixinHooks(name, hooks);
|
|
@@ -147,9 +151,9 @@ export function extendModel(name, extension = {}) {
|
|
|
147
151
|
* @param {string} [definition.origin]
|
|
148
152
|
*/
|
|
149
153
|
export function defineMixin(name, definition) {
|
|
150
|
-
const { fields, relations, mixins, hooks, origin } = definition;
|
|
154
|
+
const { fields, relations, mixins, hooks, origin, constraints, primaryKey } = definition;
|
|
151
155
|
state.registry.define(
|
|
152
|
-
{ name, abstract: true, fields, relations, mixins },
|
|
156
|
+
{ name, abstract: true, fields, relations, mixins, constraints, primaryKey },
|
|
153
157
|
{ origin },
|
|
154
158
|
);
|
|
155
159
|
addMixinHooks(name, hooks);
|
|
@@ -215,11 +219,11 @@ export function defineMixin(name, definition) {
|
|
|
215
219
|
* @returns {Model}
|
|
216
220
|
*/
|
|
217
221
|
export function createModel(name, schema) {
|
|
218
|
-
const { fields, relations, hooks, table, mixins, origin } = schema;
|
|
222
|
+
const { fields, relations, hooks, table, mixins, origin, constraints, primaryKey } = schema;
|
|
219
223
|
// Returns null (rather than throwing) if `mixins` names a model that doesn't exist yet: the
|
|
220
224
|
// model then simply waits for it. Either way the Model below works once everything is defined.
|
|
221
225
|
const descriptorNow = state.registry.define(
|
|
222
|
-
{ name, table, fields, relations, mixins },
|
|
226
|
+
{ name, table, fields, relations, mixins, constraints, primaryKey },
|
|
223
227
|
{ origin },
|
|
224
228
|
);
|
|
225
229
|
|
|
@@ -302,7 +306,7 @@ function getOrCreateModelHandle(name) {
|
|
|
302
306
|
// models; each one is wrapped by its own model's wrapper.
|
|
303
307
|
function createRuntime(options) {
|
|
304
308
|
return {
|
|
305
|
-
db: options.trx
|
|
309
|
+
db: resolveDb(getConnection(), options.trx),
|
|
306
310
|
modelRegistry: state.registry,
|
|
307
311
|
fieldTypeRegistry: defaultFieldTypeRegistry,
|
|
308
312
|
hooks: state.hooks,
|
|
@@ -311,58 +315,31 @@ function getOrCreateModelHandle(name) {
|
|
|
311
315
|
};
|
|
312
316
|
}
|
|
313
317
|
|
|
318
|
+
// Both shared with UnitOfWork (uow/lifecycle.js): hooks + the write as one atomic unit.
|
|
314
319
|
async function saveDocument(entity, options = {}) {
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
"beforeUpdate",
|
|
326
|
-
entity,
|
|
327
|
-
dirty,
|
|
328
|
-
originalSnapshot,
|
|
329
|
-
);
|
|
330
|
-
await state.hooks.run(
|
|
331
|
-
name,
|
|
332
|
-
"beforeSave",
|
|
333
|
-
entity,
|
|
334
|
-
dirty,
|
|
335
|
-
originalSnapshot,
|
|
336
|
-
);
|
|
337
|
-
const result = await repo().update(
|
|
338
|
-
{ [primaryKeyOf(descriptor())]: original[primaryKeyOf(descriptor())] },
|
|
339
|
-
dirty,
|
|
340
|
-
options,
|
|
341
|
-
);
|
|
342
|
-
if (!result)
|
|
343
|
-
throw new SaveDeletedError("save() did not affect any rows.");
|
|
344
|
-
} catch (err) {
|
|
345
|
-
for (const key of Object.keys(dirty)) entity[key] = original[key];
|
|
346
|
-
throw err;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
for (const [key, value] of Object.entries(dirty)) {
|
|
350
|
-
entity[key] = value;
|
|
351
|
-
original[key] = value;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
await state.hooks.run(name, "afterUpdate", entity, dirty, originalSnapshot);
|
|
355
|
-
await state.hooks.run(name, "afterSave", entity, dirty, originalSnapshot);
|
|
356
|
-
return entity;
|
|
320
|
+
const key = primaryKeyOf(descriptor());
|
|
321
|
+
const id = originalValue(entity, key);
|
|
322
|
+
return saveEntityLifecycle({
|
|
323
|
+
entity,
|
|
324
|
+
model: descriptor(),
|
|
325
|
+
modelName: name,
|
|
326
|
+
hooks: state.hooks,
|
|
327
|
+
db: resolveDb(getConnection(), options.trx),
|
|
328
|
+
write: (conn, changes) => repo().update({ [key]: id }, changes, { ...options, trx: conn.isTransaction ? conn : options.trx }),
|
|
329
|
+
});
|
|
357
330
|
}
|
|
358
331
|
|
|
359
332
|
async function deleteDocument(entity, options = {}) {
|
|
360
|
-
const original = entity[ENTITY_META].original;
|
|
361
|
-
await state.hooks.run(name, "beforeDelete", entity);
|
|
362
333
|
const key = primaryKeyOf(descriptor());
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
334
|
+
const id = originalValue(entity, key);
|
|
335
|
+
await deleteEntityLifecycle({
|
|
336
|
+
entity,
|
|
337
|
+
modelName: name,
|
|
338
|
+
hooks: state.hooks,
|
|
339
|
+
db: resolveDb(getConnection(), options.trx),
|
|
340
|
+
write: (conn) => repo().delete({ [key]: id }, { ...options, trx: conn.isTransaction ? conn : options.trx }),
|
|
341
|
+
});
|
|
342
|
+
currentIdentityMap()?.delete(identityKey(id));
|
|
366
343
|
return true;
|
|
367
344
|
}
|
|
368
345
|
|
|
@@ -410,6 +387,31 @@ function getOrCreateModelHandle(name) {
|
|
|
410
387
|
);
|
|
411
388
|
},
|
|
412
389
|
|
|
390
|
+
/**
|
|
391
|
+
* Inserts the document, or updates the row with the same `conflict` key - one atomic
|
|
392
|
+
* statement (since 0.2.0). `conflict` must be a unique key; `update` picks the fields
|
|
393
|
+
* overwritten on an existing row (default: those passed; `false` = insert if missing).
|
|
394
|
+
*
|
|
395
|
+
* await User.upsert({ email, name }, { conflict: ["email"] });
|
|
396
|
+
*
|
|
397
|
+
* @param {Record<string, unknown>} data
|
|
398
|
+
* @param {{ conflict: string[]|string, update?: string[]|false, trx?: import('knex').Knex.Transaction }} options
|
|
399
|
+
*/
|
|
400
|
+
async upsert(data, options = {}) {
|
|
401
|
+
const [document] = await upsertRecords(createRuntime(options), descriptor(), [data], { ...options, labels: [""] });
|
|
402
|
+
return document;
|
|
403
|
+
},
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* upsert() for many rows: one INSERT ... ON CONFLICT per chunk, all-or-nothing.
|
|
407
|
+
*
|
|
408
|
+
* @param {Record<string, unknown>[]} dataList
|
|
409
|
+
* @param {{ conflict: string[]|string, update?: string[]|false, trx?: import('knex').Knex.Transaction, chunkSize?: number }} options
|
|
410
|
+
*/
|
|
411
|
+
async upsertMany(dataList, options = {}) {
|
|
412
|
+
return upsertRecords(createRuntime(options), descriptor(), dataList, options);
|
|
413
|
+
},
|
|
414
|
+
|
|
413
415
|
/**
|
|
414
416
|
* `select` limits the fields read; the primary key is always included so the document can
|
|
415
417
|
* save itself and take part in the identity map. `with` takes names, paths or
|
|
@@ -511,7 +513,7 @@ function getOrCreateModelHandle(name) {
|
|
|
511
513
|
|
|
512
514
|
/** @param {{ trx?: import('knex').Knex.Transaction }} [options] */
|
|
513
515
|
async attach(source, relationName, targetIds, options = {}) {
|
|
514
|
-
const db = options.trx
|
|
516
|
+
const db = resolveDb(getConnection(), options.trx);
|
|
515
517
|
return attachRelation(
|
|
516
518
|
db,
|
|
517
519
|
descriptor(),
|
|
@@ -530,13 +532,13 @@ function getOrCreateModelHandle(name) {
|
|
|
530
532
|
* @param {{ trx?: import('knex').Knex.Transaction }} [options]
|
|
531
533
|
*/
|
|
532
534
|
async attachMany(relationName, links, options = {}) {
|
|
533
|
-
const db = options.trx
|
|
535
|
+
const db = resolveDb(getConnection(), options.trx);
|
|
534
536
|
return attachManyRelation(db, descriptor(), name, relationName, links);
|
|
535
537
|
},
|
|
536
538
|
|
|
537
539
|
/** @param {{ trx?: import('knex').Knex.Transaction }} [options] */
|
|
538
540
|
async detach(source, relationName, targetIds, options = {}) {
|
|
539
|
-
const db = options.trx
|
|
541
|
+
const db = resolveDb(getConnection(), options.trx);
|
|
540
542
|
return detachRelation(
|
|
541
543
|
db,
|
|
542
544
|
descriptor(),
|
package/src/global/errors.js
CHANGED
package/src/global/index.js
CHANGED
|
@@ -2,6 +2,7 @@ export { connect, getConnection, disconnect } from "./connect.js";
|
|
|
2
2
|
export { createModel, extendModel, defineMixin } from "./create-model.js";
|
|
3
3
|
export { loadModels } from "./load-models.js";
|
|
4
4
|
export { syncModels } from "./sync-models.js";
|
|
5
|
+
export { normalizeDates } from "./normalize-dates.js";
|
|
5
6
|
export { syncSequences } from "./sequences.js";
|
|
6
7
|
export { createReport } from "./create-report.js";
|
|
7
8
|
export { detectNPlusOne, assertNoNPlusOne, watchNPlusOne } from "./n-plus-one.js";
|
|
@@ -10,3 +11,4 @@ export { withIdentityMap } from "./identity-scope.js";
|
|
|
10
11
|
export { diffModels, migrateModels, getDefaultModelRegistry } from "./migrate.js";
|
|
11
12
|
export { generateModelDTOs, generateAllModelDTOs, generateModelJSDoc } from "./dto.js";
|
|
12
13
|
export { __resetGlobalStateForTests } from "./state.js";
|
|
14
|
+
export { SaveDeletedError } from "./errors.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { normalizeDateColumns } from "../schema/normalize-dates.js";
|
|
2
|
+
import { getConnection } from "./connect.js";
|
|
3
|
+
import { state } from "./state.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Rewrites `date` values written by 0.1.0-0.1.2 (epoch milliseconds on SQLite) as "YYYY-MM-DD"
|
|
7
|
+
* text, for every model created with createModel() - or only `options.models`. Since 0.1.7.
|
|
8
|
+
* See normalizeDateColumns() for the details; on Postgres it does nothing and returns [].
|
|
9
|
+
*
|
|
10
|
+
* @param {{ models?: string[] }} [options]
|
|
11
|
+
* @returns {Promise<import('../schema/normalize-dates.js').NormalizedDateColumn[]>}
|
|
12
|
+
*/
|
|
13
|
+
export async function normalizeDates(options = {}) {
|
|
14
|
+
return normalizeDateColumns(getConnection(), state.registry, options);
|
|
15
|
+
}
|
package/src/global/state.js
CHANGED
|
@@ -23,6 +23,8 @@ import { HookRegistry } from "../uow/hooks.js";
|
|
|
23
23
|
*/
|
|
24
24
|
export const state = {
|
|
25
25
|
connection: null,
|
|
26
|
+
/** Whether connect() built `connection` from a config (so it may close it when replaced). */
|
|
27
|
+
ownsConnection: false,
|
|
26
28
|
registry: new ModelRegistry(),
|
|
27
29
|
hooks: new HookRegistry(),
|
|
28
30
|
// modelName -> (record) => document. Filled in by createModel() so a
|
|
@@ -51,6 +53,7 @@ export const state = {
|
|
|
51
53
|
*/
|
|
52
54
|
export function __resetGlobalStateForTests() {
|
|
53
55
|
state.connection = null;
|
|
56
|
+
state.ownsConnection = false;
|
|
54
57
|
state.registry = new ModelRegistry();
|
|
55
58
|
state.hooks = new HookRegistry();
|
|
56
59
|
state.wrappers = new Map();
|
|
@@ -1,26 +1,24 @@
|
|
|
1
1
|
import { getConnection } from "./connect.js";
|
|
2
|
+
import { resolveDb } from "../transaction/context.js";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
|
-
* Runs `fn` inside a transaction on the default connection
|
|
5
|
-
* the transaction object through so it can be handed to any Model
|
|
6
|
-
* method's `{ trx }` option (`Order.create(data, { trx })`) to
|
|
7
|
-
* include it in the same atomic unit. Every `Model` method - `create`,
|
|
8
|
-
* `find`, `findOne`, `updateMany`, `deleteMany`, `attach`, `detach`,
|
|
9
|
-
* and a document's own `save()`/`delete()` - accepts `{ trx }` for
|
|
10
|
-
* exactly this reason.
|
|
5
|
+
* Runs `fn` inside a transaction on the default connection.
|
|
11
6
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* `
|
|
15
|
-
* with no way to roll every step back together if a later one fails.
|
|
7
|
+
* Since 0.2.0 every model call made while `fn` runs joins the transaction on its own - in `fn`,
|
|
8
|
+
* in a helper it calls, in a hook - so `{ trx }` no longer has to be passed along (it still works,
|
|
9
|
+
* and `fn` still receives the transaction for raw Knex queries: `trx("table")...`).
|
|
16
10
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
11
|
+
* Called while a transaction is already open in this async flow, it opens a savepoint inside it:
|
|
12
|
+
* if `fn` throws, only the savepoint's work is undone and the error propagates to the outer code.
|
|
13
|
+
*
|
|
14
|
+
* Writes and their before/after hooks commit or roll back together. `afterCommit` hooks run once
|
|
15
|
+
* the outermost transaction has committed, before this promise resolves (an error there rejects it,
|
|
16
|
+
* though the data stays committed).
|
|
19
17
|
*
|
|
20
18
|
* @template T
|
|
21
19
|
* @param {(trx: import('knex').Knex.Transaction) => Promise<T>} fn
|
|
22
20
|
* @returns {Promise<T>}
|
|
23
21
|
*/
|
|
24
22
|
export async function transaction(fn) {
|
|
25
|
-
return getConnection().transaction(fn);
|
|
23
|
+
return resolveDb(getConnection()).transaction(fn);
|
|
26
24
|
}
|
package/src/index.js
CHANGED
|
@@ -14,3 +14,5 @@ export * from "./uow/index.js";
|
|
|
14
14
|
export * from "./client/index.js";
|
|
15
15
|
export * from "./global/index.js";
|
|
16
16
|
export * from "./dto/index.js";
|
|
17
|
+
export { afterCommit } from "./transaction/after-commit.js";
|
|
18
|
+
export { resolveDb, ambientTransaction } from "./transaction/context.js";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates one of the ORM's own bookkeeping tables (`_meta_models`, `_meta_fields`,
|
|
3
|
+
* `_meta_migrations`) if it doesn't exist yet.
|
|
4
|
+
*
|
|
5
|
+
* "Check, then create" races when two processes start on a fresh database together (two app
|
|
6
|
+
* instances running `migrate:up` or `syncModels()` on their first deploy): both see no table,
|
|
7
|
+
* and the slower CREATE fails with "already exists" (before 0.1.7 that failed the whole run).
|
|
8
|
+
* The losing CREATE is now ignored when the table turns out to exist after all - the other
|
|
9
|
+
* process made it, with the same definition.
|
|
10
|
+
*
|
|
11
|
+
* @param {import('knex').Knex} db
|
|
12
|
+
* @param {string} name
|
|
13
|
+
* @param {(table: import('knex').Knex.CreateTableBuilder) => void} define
|
|
14
|
+
*/
|
|
15
|
+
export async function createTableOnce(db, name, define) {
|
|
16
|
+
if (await db.schema.hasTable(name)) return;
|
|
17
|
+
try {
|
|
18
|
+
await db.schema.createTable(name, define);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (await db.schema.hasTable(name)) return;
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
package/src/meta/schema.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
|
|
2
|
+
import { createTableOnce } from "./create-table-once.js";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Creates the two internal metadata tables if they don't already
|
|
@@ -18,21 +19,29 @@ import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
|
|
|
18
19
|
* @param {import('knex').Knex} db
|
|
19
20
|
*/
|
|
20
21
|
export async function ensureMetaTables(db) {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
await db.schema.createTable(META_MODELS_TABLE, (table) => {
|
|
22
|
+
{
|
|
23
|
+
await createTableOnce(db, META_MODELS_TABLE, (table) => {
|
|
24
24
|
table.increments("id");
|
|
25
25
|
table.string("name", 255).notNullable().unique();
|
|
26
26
|
table.string("table_name", 255).notNullable().unique();
|
|
27
27
|
table.timestamp("created_at").notNullable();
|
|
28
28
|
table.timestamp("updated_at").notNullable();
|
|
29
29
|
table.timestamp("removed_at").nullable();
|
|
30
|
+
table.text("constraints").nullable();
|
|
30
31
|
});
|
|
32
|
+
// Since 0.2.0: the model's multi-field constraints (models/constraints.js), so migrations can
|
|
33
|
+
// tell which were added or removed. Tables made by 0.1.x get the column here; NULL = none recorded.
|
|
34
|
+
if (!(await db.schema.hasColumn(META_MODELS_TABLE, "constraints"))) {
|
|
35
|
+
try {
|
|
36
|
+
await db.schema.alterTable(META_MODELS_TABLE, (table) => table.text("constraints").nullable());
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (!(await db.schema.hasColumn(META_MODELS_TABLE, "constraints"))) throw error; // another process added it
|
|
39
|
+
}
|
|
40
|
+
}
|
|
31
41
|
}
|
|
32
42
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
await db.schema.createTable(META_FIELDS_TABLE, (table) => {
|
|
43
|
+
{
|
|
44
|
+
await createTableOnce(db, META_FIELDS_TABLE, (table) => {
|
|
36
45
|
table.increments("id");
|
|
37
46
|
table
|
|
38
47
|
.integer("model_id")
|