@kiri-orm/core 0.1.1 → 0.1.3
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 +48 -3
- package/package.json +12 -1
- package/src/connection.js +1 -1
- package/src/crud/insert-many.js +1 -1
- package/src/crud/repository.js +9 -1
- package/src/fields/types/date.js +100 -19
package/README.md
CHANGED
|
@@ -27,7 +27,6 @@ const post = await Post.create({ title: "Hello" });
|
|
|
27
27
|
`_meta_models` / `_meta_fields` (an idea borrowed from Odoo). Migrations diff against that
|
|
28
28
|
_recorded_ schema instead of guessing from live introspection, and the CLI and the DTO
|
|
29
29
|
generators read from it too.
|
|
30
|
-
- **Plain JavaScript.** No TypeScript type system involved, no generated client.
|
|
31
30
|
- **The database enforces your relations.** Every `belongsTo` becomes a real `FOREIGN KEY` with
|
|
32
31
|
its `ON DELETE` action, so deleting a row is one statement however many tables point at it.
|
|
33
32
|
- **Relations load without N+1.** `with: [...]` costs one extra query per relation, however many
|
|
@@ -212,6 +211,26 @@ const page = await Post.paginate(
|
|
|
212
211
|
|
|
213
212
|
`aggregate()` handles grouping and several figures at once, all in one statement in the database.
|
|
214
213
|
|
|
214
|
+
```js
|
|
215
|
+
await Order.aggregate(
|
|
216
|
+
[
|
|
217
|
+
["status", "!=", "cancelled"],
|
|
218
|
+
["revenue", ">", 1000],
|
|
219
|
+
],
|
|
220
|
+
{
|
|
221
|
+
groupBy: ["customerId", "placedAt:month"],
|
|
222
|
+
aggregates: {
|
|
223
|
+
orders: "count",
|
|
224
|
+
revenue: { sum: "total" },
|
|
225
|
+
biggest: { max: "total" },
|
|
226
|
+
},
|
|
227
|
+
orderBy: "-revenue",
|
|
228
|
+
limit: 10,
|
|
229
|
+
},
|
|
230
|
+
);
|
|
231
|
+
// [{ customerId: 7, placedAt_month: Date(2024-02-01), orders: 12, revenue: 5400, biggest: 900 }, …]
|
|
232
|
+
```
|
|
233
|
+
|
|
215
234
|
## Transactions
|
|
216
235
|
|
|
217
236
|
Every method accepts `{ trx }`. If the callback throws, nothing in it is committed.
|
|
@@ -331,6 +350,34 @@ different objects. Opt in with `withIdentityMap(fn)` when you want one.
|
|
|
331
350
|
## Also included
|
|
332
351
|
|
|
333
352
|
- **Reports:** `createReport()` defines a read-only, aggregated model for dashboards and exports.
|
|
353
|
+
|
|
354
|
+
```js
|
|
355
|
+
import { createReport } from "@kiri-orm/core";
|
|
356
|
+
|
|
357
|
+
export const SalesByCustomer = createReport("salesByCustomer", {
|
|
358
|
+
from: "order", // the model it reads
|
|
359
|
+
where: [["status", "!=", "cancelled"]], // always applied
|
|
360
|
+
fields: {
|
|
361
|
+
customerId: true, // a plain field of `order`
|
|
362
|
+
customerName: "customer.name", // a field through a to-one path
|
|
363
|
+
month: { from: "placedAt", bucket: "month" },
|
|
364
|
+
orders: { agg: "count" },
|
|
365
|
+
revenue: { agg: "sum", of: "total" },
|
|
366
|
+
itemsSold: { agg: "sum", of: "items.qty" }, // across a to-many relation
|
|
367
|
+
avgOrder: {
|
|
368
|
+
// plain JavaScript over the finished row
|
|
369
|
+
compute: (row) => row.revenue / row.orders,
|
|
370
|
+
depends: ["orders", "revenue"],
|
|
371
|
+
},
|
|
372
|
+
},
|
|
373
|
+
orderBy: "-revenue", // the default; override per call
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
await SalesByCustomer.find([["revenue", ">", 1000]], { limit: 10 });
|
|
377
|
+
await SalesByCustomer.findOne([["customerName", "=", "Ada"]]);
|
|
378
|
+
await SalesByCustomer.count();
|
|
379
|
+
```
|
|
380
|
+
|
|
334
381
|
- **DTO generation:** `generateModelDTOs("post")` returns create / update / read JSON Schemas
|
|
335
382
|
built from the same field definitions.
|
|
336
383
|
- **N+1 detection:** the ORM can flag a query that is repeated per row.
|
|
@@ -338,8 +385,6 @@ different objects. Opt in with `withIdentityMap(fn)` when you want one.
|
|
|
338
385
|
|
|
339
386
|
## Good to know
|
|
340
387
|
|
|
341
|
-
- **Plain JavaScript.** The package ships no `.d.ts` files. `orm generate:dto` produces JSDoc
|
|
342
|
-
typedefs and JSON Schemas from your models if you want editor hints.
|
|
343
388
|
- **No silent schema changes.** A field that disappears from your code is flagged in the
|
|
344
389
|
metadata rather than dropped, and changing a field's `type` is never auto-migrated.
|
|
345
390
|
- **SQLite and Postgres only.** Other databases are not supported.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kiri-orm/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./src/index.js",
|
|
6
6
|
"types": "./dist/types/index.d.ts",
|
|
@@ -42,6 +42,17 @@
|
|
|
42
42
|
"publishConfig": {
|
|
43
43
|
"access": "public"
|
|
44
44
|
},
|
|
45
|
+
"keywords": [
|
|
46
|
+
"orm",
|
|
47
|
+
"automatic",
|
|
48
|
+
"migrations",
|
|
49
|
+
"fast orm",
|
|
50
|
+
"data",
|
|
51
|
+
"framwork",
|
|
52
|
+
"postgres",
|
|
53
|
+
"sqlite",
|
|
54
|
+
"backend"
|
|
55
|
+
],
|
|
45
56
|
"scripts": {
|
|
46
57
|
"build": "echo \"no build step - plain JS\"",
|
|
47
58
|
"test:unit": "vitest run test/unit",
|
package/src/connection.js
CHANGED
|
@@ -24,7 +24,7 @@ const DIALECTS = /** @type {const} */ (["sqlite", "postgres"]);
|
|
|
24
24
|
export function createConnection(config) {
|
|
25
25
|
if (!config || !DIALECTS.includes(config.dialect)) {
|
|
26
26
|
throw new Error(
|
|
27
|
-
`Unsupported or missing dialect. Expected one of: ${DIALECTS.join(", ")}
|
|
27
|
+
`Unsupported or missing dialect. Expected one of: ${DIALECTS.join(", ")}`,
|
|
28
28
|
);
|
|
29
29
|
}
|
|
30
30
|
|
package/src/crud/insert-many.js
CHANGED
|
@@ -146,7 +146,7 @@ export function alignToInput(model, valuesList, records) {
|
|
|
146
146
|
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
147
147
|
* @param {Record<string, unknown>} values
|
|
148
148
|
*/
|
|
149
|
-
function serializeJsonFields(model, values) {
|
|
149
|
+
export function serializeJsonFields(model, values) {
|
|
150
150
|
let serialized = null;
|
|
151
151
|
for (const [fieldName, field] of Object.entries(model.fields)) {
|
|
152
152
|
if (field.type !== "json") continue;
|
package/src/crud/repository.js
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
import { translateDeleteError } from "../relations/foreign-keys.js";
|
|
17
17
|
import { createRecords } from "./create-many.js";
|
|
18
18
|
import { RelationError } from "../relations/errors.js";
|
|
19
|
+
import { serializeJsonFields } from "./insert-many.js";
|
|
19
20
|
|
|
20
21
|
/**
|
|
21
22
|
* The CRUD surface for a single model. Every method speaks in field
|
|
@@ -399,6 +400,13 @@ export class Repository {
|
|
|
399
400
|
* @throws {ValidationError}
|
|
400
401
|
*/
|
|
401
402
|
async update(filter, data, options = {}) {
|
|
403
|
+
if (isEmptyFilter(filter)) {
|
|
404
|
+
throw new ValidationError(this.model.name, {
|
|
405
|
+
_: [
|
|
406
|
+
"update() requires a non-empty filter - use a filter that matches everything explicitly if that's really intended",
|
|
407
|
+
],
|
|
408
|
+
});
|
|
409
|
+
}
|
|
402
410
|
assertPrimaryKeyUntouched(this.model, data);
|
|
403
411
|
const { errors, values } = prepareWrite(
|
|
404
412
|
this.model,
|
|
@@ -421,7 +429,7 @@ export class Repository {
|
|
|
421
429
|
this.fieldTypeRegistry,
|
|
422
430
|
this.modelRegistry,
|
|
423
431
|
);
|
|
424
|
-
const row = toRow(this.model, values);
|
|
432
|
+
const row = toRow(this.model, serializeJsonFields(this.model, values));
|
|
425
433
|
return this.#queryBuilder(options.trx).where(where).update(row);
|
|
426
434
|
}
|
|
427
435
|
|
package/src/fields/types/date.js
CHANGED
|
@@ -1,33 +1,114 @@
|
|
|
1
1
|
import { CastError } from "../errors.js";
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
// year first; separators must match; optional time part with optional zone
|
|
4
|
+
const DATE_RE =
|
|
5
|
+
/^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)?)?$/i;
|
|
6
|
+
|
|
7
|
+
function isLeap(y) {
|
|
8
|
+
return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function daysInMonth(y, m) {
|
|
12
|
+
if (m === 2) return isLeap(y) ? 29 : 28;
|
|
13
|
+
return m === 4 || m === 6 || m === 9 || m === 11 ? 30 : 31;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function isRealCalendarDate(y, m, d) {
|
|
17
|
+
return m >= 1 && m <= 12 && d >= 1 && d <= daysInMonth(y, m);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function format(y, m, d) {
|
|
21
|
+
return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function normalizeOffset(z) {
|
|
25
|
+
if (z.toUpperCase() === "Z") return "Z";
|
|
26
|
+
const sign = z[0];
|
|
27
|
+
const digits = z.slice(1).replace(":", "");
|
|
28
|
+
const hh = digits.slice(0, 2);
|
|
29
|
+
const mm = digits.slice(2) || "00";
|
|
30
|
+
return `${sign}${hh}:${mm}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Calendar day of an instant in a given IANA timezone.
|
|
34
|
+
function dayInZone(instant, timeZone) {
|
|
35
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
36
|
+
timeZone,
|
|
37
|
+
year: "numeric",
|
|
38
|
+
month: "numeric",
|
|
39
|
+
day: "numeric",
|
|
40
|
+
}).formatToParts(instant);
|
|
41
|
+
const get = (t) => Number(parts.find((p) => p.type === t).value);
|
|
42
|
+
return format(get("year"), get("month"), get("day"));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseString(field, raw) {
|
|
46
|
+
const match = DATE_RE.exec(raw.trim());
|
|
47
|
+
if (!match) return null;
|
|
48
|
+
|
|
49
|
+
const y = Number(match[1]);
|
|
50
|
+
const m = Number(match[3]);
|
|
51
|
+
const d = Number(match[4]);
|
|
52
|
+
if (!isRealCalendarDate(y, m, d)) return null;
|
|
53
|
+
|
|
54
|
+
const hasTime = match[5] !== undefined;
|
|
55
|
+
if (hasTime) {
|
|
56
|
+
const [hh, mi, ss] = [match[5], match[6], match[7] ?? "0"].map(Number);
|
|
57
|
+
if (hh > 23 || mi > 59 || ss > 59) return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const offset = match[8];
|
|
61
|
+
if (hasTime && offset && field?.timeZone) {
|
|
62
|
+
// The string is an instant: convert it to a day in the field's zone.
|
|
63
|
+
const iso =
|
|
64
|
+
`${format(y, m, d)}T${match[5]}:${match[6]}:${String(match[7] ?? "0").padStart(2, "0")}` +
|
|
65
|
+
normalizeOffset(offset);
|
|
66
|
+
const instant = new Date(iso);
|
|
67
|
+
return Number.isNaN(instant.getTime())
|
|
68
|
+
? null
|
|
69
|
+
: dayInZone(instant, field.timeZone);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Default: the date exactly as written; time and offset are ignored.
|
|
73
|
+
return format(y, m, d);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function fromDateObject(dt) {
|
|
77
|
+
if (Number.isNaN(dt.getTime())) return null;
|
|
78
|
+
return format(dt.getFullYear(), dt.getMonth() + 1, dt.getDate());
|
|
5
79
|
}
|
|
6
80
|
|
|
7
|
-
/**
|
|
8
|
-
* A calendar date (no time component, though the canonical runtime
|
|
9
|
-
* representation is still a JS Date - the schema-sync layer in a later
|
|
10
|
-
* phase is what maps this to a DATE vs DATETIME column per dialect).
|
|
11
|
-
*/
|
|
12
81
|
export const dateType = {
|
|
13
82
|
name: "date",
|
|
14
83
|
|
|
84
|
+
// validate stays strict: it only accepts the canonical stored form.
|
|
15
85
|
validate(field, value) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
86
|
+
const ok =
|
|
87
|
+
typeof value === "string" &&
|
|
88
|
+
/^\d{4}-\d{2}-\d{2}$/.test(value) &&
|
|
89
|
+
isRealCalendarDate(
|
|
90
|
+
+value.slice(0, 4),
|
|
91
|
+
+value.slice(5, 7),
|
|
92
|
+
+value.slice(8, 10),
|
|
93
|
+
);
|
|
94
|
+
return ok
|
|
95
|
+
? []
|
|
96
|
+
: [
|
|
97
|
+
`expected a real calendar date as "YYYY-MM-DD", got ${JSON.stringify(value)}`,
|
|
98
|
+
];
|
|
20
99
|
},
|
|
21
100
|
|
|
22
101
|
cast(field, value) {
|
|
23
|
-
|
|
24
|
-
if (typeof value === "string"
|
|
25
|
-
|
|
26
|
-
|
|
102
|
+
let result = null;
|
|
103
|
+
if (typeof value === "string") result = parseString(field, value);
|
|
104
|
+
else if (value instanceof Date) result = fromDateObject(value);
|
|
105
|
+
|
|
106
|
+
if (result === null) {
|
|
107
|
+
throw new CastError(`cannot cast ${JSON.stringify(value)} to date`, {
|
|
108
|
+
fieldType: "date",
|
|
109
|
+
value,
|
|
110
|
+
});
|
|
27
111
|
}
|
|
28
|
-
|
|
29
|
-
fieldType: "date",
|
|
30
|
-
value,
|
|
31
|
-
});
|
|
112
|
+
return result;
|
|
32
113
|
},
|
|
33
114
|
};
|