@kiri-orm/core 0.1.1 → 0.1.2

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 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.1",
3
+ "version": "0.1.2",
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
 
@@ -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;
@@ -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