@kiri-orm/core 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiri-orm/core",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "main": "./src/index.js",
6
6
  "types": "./dist/types/index.d.ts",
@@ -11,7 +11,7 @@
11
11
  }
12
12
  },
13
13
  "dependencies": {
14
- "knex": "^3.1.0"
14
+ "knex": "^3.2.0"
15
15
  },
16
16
  "peerDependencies": {
17
17
  "better-sqlite3": "^11.0.0",
@@ -1,6 +1,6 @@
1
1
  import { fromRow, toRow } from "./row-mapping.js";
2
2
  import { primaryKeyOf } from "../models/primary-key.js";
3
- import { advanceSequence } from "./sequence.js";
3
+ import { advanceSequence, isPostgres } from "./sequence.js";
4
4
 
5
5
  /**
6
6
  * Per-statement limits, by dialect family.
@@ -194,7 +194,7 @@ export async function insertRecords(
194
194
  );
195
195
  const returned = await db(model.tableName).insert(rows).returning("*");
196
196
  const records = returned.map((row) =>
197
- fromRow(model, row, fieldTypeRegistry),
197
+ fromRow(model, row, fieldTypeRegistry, { jsonParsed: isPostgres(db) }),
198
198
  );
199
199
  results.push(...alignToInput(model, chunk, records));
200
200
  }
@@ -17,6 +17,7 @@ import { translateDeleteError } from "../relations/foreign-keys.js";
17
17
  import { createRecords } from "./create-many.js";
18
18
  import { RelationError } from "../relations/errors.js";
19
19
  import { serializeJsonFields } from "./insert-many.js";
20
+ import { isPostgres } from "./sequence.js";
20
21
 
21
22
  /**
22
23
  * The CRUD surface for a single model. Every method speaks in field
@@ -186,6 +187,7 @@ export class Repository {
186
187
  const records = rows.map((row) =>
187
188
  fromRow(this.model, row, this.fieldTypeRegistry, {
188
189
  computed: plan.computed,
190
+ jsonParsed: isPostgres(this.db),
189
191
  }),
190
192
  );
191
193
 
@@ -25,10 +25,17 @@ export const PARTIAL = Symbol("partialRecord");
25
25
  * (a string is technically valid JSON too), so the string case is
26
26
  * parsed here first, before the value ever reaches castValue().
27
27
  *
28
+ * That extra parse must only happen where the driver hands back JSON *text*. On Postgres the
29
+ * driver has already parsed the column, so a string there IS the stored value - a JSON string
30
+ * scalar like `"hello"` or `"123"`. Parsing it a second time turned `"123"` into the number 123
31
+ * and made `"hello"` throw, breaking every read of the table (fixed in 0.1.6). Callers inside the
32
+ * ORM pass `jsonParsed: isPostgres(db)`; a caller that omits it gets the SQLite behavior.
33
+ *
28
34
  * @param {import('../models/define-model.js').ModelDescriptor} model
29
35
  * @param {Record<string, unknown>} row
30
36
  * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
31
- * @param {{ computed?: Set<string>|null }} [options] - `computed`: which computed fields to define
37
+ * @param {{ computed?: Set<string>|null, jsonParsed?: boolean }} [options] - `jsonParsed`: the driver already
38
+ * parsed json columns (Postgres), so a string value is a JSON string, not JSON text. `computed`: which computed fields to define
32
39
  * (default: all). A row read with `select` only defines the ones whose dependencies it carries; the
33
40
  * choice is remembered under PARTIAL so an entity built from the record can make the same one.
34
41
  * @returns {Record<string, unknown>}
@@ -42,7 +49,7 @@ export function fromRow(model, row, fieldTypeRegistry = defaultFieldTypeRegistry
42
49
 
43
50
  let value = row[columnName];
44
51
  if (value !== null && value !== undefined) {
45
- if (field.type === "json" && typeof value === "string") {
52
+ if (field.type === "json" && typeof value === "string" && !options.jsonParsed) {
46
53
  value = JSON.parse(value);
47
54
  }
48
55
  value = castValue(field, value, fieldTypeRegistry);
@@ -5,8 +5,8 @@ import { isPostgres } from "../crud/sequence.js";
5
5
  * month, quarter or year, so rows can be grouped by period.
6
6
  *
7
7
  * Postgres and SQLite spell this completely differently (`date_trunc` vs `strftime`), and
8
- * store dates differently (a real `timestamptz`/`date` vs epoch milliseconds in an integer
9
- * column), so the SQL lives here, once, behind one function. Both return the bucket the
8
+ * store dates differently (a real `timestamptz`/`date` vs epoch milliseconds or "YYYY-MM-DD"
9
+ * text - see sqliteBucket()), so the SQL lives here, once, behind one function. Both return the bucket the
10
10
  * same way - an ISO-8601 UTC string, `2024-03-01T00:00:00Z` - which the caller turns
11
11
  * into a Date. Returning a string instead of letting each driver hand back its own
12
12
  * timestamp type is what keeps the result identical on both databases.
@@ -51,30 +51,37 @@ function postgresBucket(column, bucket, fieldType) {
51
51
  }
52
52
 
53
53
  function sqliteBucket(column, bucket) {
54
- // Dates are stored as epoch milliseconds; strftime wants seconds. `/ 1000.0` keeps pre-1970 values correct.
55
- const t = "??/1000.0, 'unixepoch'";
54
+ // SQLite has no date type, and a column can hold either of two storage forms:
55
+ // - epoch milliseconds (an integer): every `datetime`, which Knex's SQLite client writes as
56
+ // Date#valueOf(), and `date` values written by 0.1.0-0.1.2;
57
+ // - text: `date` values written by 0.1.3+, as "YYYY-MM-DD".
58
+ // Before 0.1.6 only the first form was handled, so text dates all fell into 1970-01-01.
59
+ // Normalizing to SQLite's own "YYYY-MM-DD HH:MM:SS" text first handles both (and a mix of both
60
+ // in one column); `/ 1000.0` keeps pre-1970 values correct. Each use of `t` binds the column 3 times.
61
+ const t = "(CASE WHEN typeof(??) IN ('integer', 'real') THEN datetime(??/1000.0, 'unixepoch') ELSE ?? END)";
62
+ const uses = (n) => Array(3 * n).fill(column);
56
63
  const fmt = (pattern, ...extra) => `strftime('${pattern}', ${t}${extra.length ? `, ${extra.join(", ")}` : ""})`;
57
64
 
58
65
  switch (bucket) {
59
66
  case "hour":
60
- return { sql: fmt("%Y-%m-%dT%H:00:00Z"), bindings: [column] };
67
+ return { sql: fmt("%Y-%m-%dT%H:00:00Z"), bindings: uses(1) };
61
68
  case "day":
62
- return { sql: fmt("%Y-%m-%dT00:00:00Z"), bindings: [column] };
69
+ return { sql: fmt("%Y-%m-%dT00:00:00Z"), bindings: uses(1) };
63
70
  case "month":
64
- return { sql: fmt("%Y-%m-01T00:00:00Z"), bindings: [column] };
71
+ return { sql: fmt("%Y-%m-01T00:00:00Z"), bindings: uses(1) };
65
72
  case "year":
66
- return { sql: fmt("%Y-01-01T00:00:00Z"), bindings: [column] };
73
+ return { sql: fmt("%Y-01-01T00:00:00Z"), bindings: uses(1) };
67
74
  case "week":
68
75
  // Step back to Monday: %w is 0 (Sunday)..6, so (%w + 6) % 7 days since Monday.
69
76
  return {
70
77
  sql: fmt("%Y-%m-%dT00:00:00Z", `'-' || ((CAST(strftime('%w', ${t}) AS INTEGER) + 6) % 7) || ' days'`),
71
- bindings: [column, column],
78
+ bindings: uses(2),
72
79
  };
73
80
  case "quarter":
74
81
  // First month of the quarter: 1, 4, 7 or 10.
75
82
  return {
76
83
  sql: `${fmt("%Y-")} || printf('%02d', ((CAST(strftime('%m', ${t}) AS INTEGER) - 1) / 3) * 3 + 1) || '-01T00:00:00Z'`,
77
- bindings: [column, column],
84
+ bindings: uses(2),
78
85
  };
79
86
  default:
80
87
  throw new TypeError(`Unhandled bucket ${bucket}`); // unreachable: checked above
@@ -21,7 +21,8 @@ function jsdocType(propertySchema) {
21
21
  if (propertySchema.enum) {
22
22
  return propertySchema.enum.map((v) => JSON.stringify(v)).join("|");
23
23
  }
24
- if (propertySchema.type === "string" && propertySchema.format === "date") return "Date";
24
+ // A `date` field's value is a "YYYY-MM-DD" string since 0.1.3 (0.1.6 fixed this to match).
25
+ if (propertySchema.type === "string" && propertySchema.format === "date") return "string";
25
26
  if (propertySchema.type === "string" && propertySchema.format === "date-time") return "Date";
26
27
  return JSON_SCHEMA_TO_JSDOC_TYPE[propertySchema.type] ?? "*";
27
28
  }
@@ -78,6 +78,32 @@ function fromDateObject(dt) {
78
78
  return format(dt.getFullYear(), dt.getMonth() + 1, dt.getDate());
79
79
  }
80
80
 
81
+ const DAY_MS = 86_400_000;
82
+
83
+ /**
84
+ * Epoch milliseconds -> "YYYY-MM-DD". This is how 0.1.0-0.1.2 stored `date` fields on SQLite
85
+ * (they were Date objects then, and Knex's SQLite client binds a Date as its valueOf()), so
86
+ * these rows must keep reading after an upgrade - from 0.1.3 to 0.1.5 they threw
87
+ * "cannot cast 1706832000000 to date" instead.
88
+ *
89
+ * Which calendar day a stored instant meant depends on how the old Date was built:
90
+ * - from a date string (`new Date("2024-03-01")`, the common case - JSON input) it is UTC
91
+ * midnight, so the UTC day is the right one;
92
+ * - from local components (`new Date(2024, 2, 1)`) it is local midnight on the server that
93
+ * wrote it, so the local day is the right one.
94
+ * An instant at exactly UTC midnight is read as that UTC day, one at exactly local midnight as
95
+ * that local day; anything else (a date carrying a time) falls back to the UTC day.
96
+ */
97
+ function fromEpochMs(ms) {
98
+ if (!Number.isFinite(ms)) return null;
99
+ const dt = new Date(ms);
100
+ if (Number.isNaN(dt.getTime())) return null;
101
+ const utcDay = format(dt.getUTCFullYear(), dt.getUTCMonth() + 1, dt.getUTCDate());
102
+ if (((ms % DAY_MS) + DAY_MS) % DAY_MS === 0) return utcDay;
103
+ const isLocalMidnight = dt.getHours() === 0 && dt.getMinutes() === 0 && dt.getSeconds() === 0 && dt.getMilliseconds() === 0;
104
+ return isLocalMidnight ? fromDateObject(dt) : utcDay;
105
+ }
106
+
81
107
  export const dateType = {
82
108
  name: "date",
83
109
 
@@ -102,6 +128,7 @@ export const dateType = {
102
128
  let result = null;
103
129
  if (typeof value === "string") result = parseString(field, value);
104
130
  else if (value instanceof Date) result = fromDateObject(value);
131
+ else if (typeof value === "number") result = fromEpochMs(value);
105
132
 
106
133
  if (result === null) {
107
134
  throw new CastError(`cannot cast ${JSON.stringify(value)} to date`, {
@@ -13,6 +13,7 @@ import { diffSchema } from "./diff.js";
13
13
  import { describePlan } from "./describe.js";
14
14
  import { renderMigrationSource } from "./render.js";
15
15
  import { MigrationSafetyError, MigrationStateError } from "./errors.js";
16
+ import { dialectOf } from "../schema/introspect-foreign-keys.js";
16
17
 
17
18
  /** Applied-migration history. `_meta_` is a reserved prefix, so no model's table can collide with it. */
18
19
  export const MIGRATIONS_TABLE = "_meta_migrations";
@@ -93,6 +94,44 @@ function helpers(options) {
93
94
  return { buildColumn, columnBuilderRegistry: options.columnBuilderRegistry ?? defaultColumnBuilderRegistry };
94
95
  }
95
96
 
97
+ /**
98
+ * Runs one migration's work in a transaction that is safe on SQLite.
99
+ *
100
+ * SQLite can't alter most of a table in place, so Knex rebuilds it: create a copy, copy the
101
+ * rows, DROP the original, rename the copy. With `PRAGMA foreign_keys` ON, that DROP runs an
102
+ * implicit `DELETE FROM` first - which fires ON DELETE CASCADE / SET NULL on every child
103
+ * table. Knex switches the pragma off around a rebuild, but SQLite ignores the pragma inside
104
+ * a transaction, and every migration here runs in one. Result before 0.1.6: dropping a column
105
+ * from a parent table deleted the rows of its cascading children.
106
+ *
107
+ * The fix is Knex's `enforceForeignCheck: false` (Knex >= 3.2): the pragma is switched off
108
+ * BEFORE `BEGIN`, `PRAGMA foreign_key_check` runs before `COMMIT` (any violation rolls the
109
+ * migration back), and the pragma is restored afterwards. The pragma is then re-read inside the
110
+ * transaction: if it is still on (an older Knex passed to connect(), or migrations started from
111
+ * inside an outer transaction, where the pragma can't change), the migration is refused rather
112
+ * than run with the risk of deleting rows.
113
+ *
114
+ * Postgres alters tables in place and needs none of this.
115
+ */
116
+ async function inMigrationTransaction(db, work) {
117
+ if (dialectOf(db) !== "sqlite") return db.transaction(work);
118
+ return db.transaction(
119
+ async (trx) => {
120
+ const [row] = await trx.raw("PRAGMA foreign_keys");
121
+ if (Number(row?.foreign_keys) === 1) {
122
+ throw new MigrationStateError(
123
+ "Refusing to run a migration on SQLite with foreign key enforcement still on inside the migration's " +
124
+ "transaction: rebuilding a table (dropColumn, dropForeign, renames, ...) would then delete or null out " +
125
+ "rows of every table that references it through ON DELETE CASCADE / SET NULL. Either Knex is older than " +
126
+ "3.2 (upgrade it), or the migration was started inside another transaction (run it on the connection itself)."
127
+ );
128
+ }
129
+ return work(trx);
130
+ },
131
+ { enforceForeignCheck: false }
132
+ );
133
+ }
134
+
96
135
  /**
97
136
  * Applies pending migrations, oldest first. Each one runs in its own
98
137
  * transaction together with its metadata update and its history row,
@@ -117,7 +156,7 @@ export async function migrateUp(db, options) {
117
156
  const applied = [];
118
157
  for (const entry of toApply) {
119
158
  const migration = await loadMigration(entry);
120
- await db.transaction(async (trx) => {
159
+ await inMigrationTransaction(db, async (trx) => {
121
160
  await migration.up(trx, helpers(options));
122
161
  for (const [modelName, snapshots] of Object.entries(migration.meta ?? {})) {
123
162
  await restoreModelMeta(trx, modelName, snapshots.after);
@@ -168,7 +207,7 @@ export async function migrateDown(db, options) {
168
207
  const rolledBack = [];
169
208
  for (const row of toRollBack) {
170
209
  const migration = await loadMigration(files.get(row.name));
171
- await db.transaction(async (trx) => {
210
+ await inMigrationTransaction(db, async (trx) => {
172
211
  await migration.down(trx, helpers(options));
173
212
  for (const [modelName, snapshots] of Object.entries(migration.meta ?? {})) {
174
213
  await restoreModelMeta(trx, modelName, snapshots.before);
@@ -1,4 +1,5 @@
1
1
  import { fromRow } from "../crud/row-mapping.js";
2
+ import { isPostgres } from "../crud/sequence.js";
2
3
  import { planSelect, stripHidden } from "../crud/select.js";
3
4
  import { RelationError } from "./errors.js";
4
5
  import { resolveLocalKey } from "./keys.js";
@@ -57,7 +58,7 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
57
58
  const table = relatedModel.tableName;
58
59
  const windowed = node.limit !== undefined || node.offset !== undefined;
59
60
 
60
- const toRecords = (rows, plan) => rows.map((row) => fromRow(relatedModel, row, fieldTypeRegistry, { computed: plan.computed }));
61
+ const toRecords = (rows, plan) => rows.map((row) => fromRow(relatedModel, row, fieldTypeRegistry, { computed: plan.computed, jsonParsed: isPostgres(db) }));
61
62
 
62
63
  /** ORDER BY for the related rows: the requested order, then the primary key so ties (and a limit) are deterministic. */
63
64
  const orderFor = (prefix) => {