@lines-db/studio 0.16.5 → 0.16.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @lines-db/studio
2
2
 
3
+ ## 0.16.7
4
+
5
+ ### Patch Changes
6
+
7
+ - 1a510a8: An inserted row's field the validation schema transforms is now written to the JSONL file as it was given, not as the schema made it. With a schema that turns the `code` `"1"` into `"ORD-1"` (a TailorDB `create` hook does this), `insert('orders', { id: 3, code: '1' })` used to write `"ORD-1"`, and the next load of the file turned it into `"ORD-ORD-1"`. It now writes `"1"`, as `update` already did, so the file holds the side a seed file holds and the schema applies its transformation once, on load. This applies to `insert` and `batchInsert` when `writeFilledValues` is `'primaryKey'` (the studio's default), except for fields named in `writeBackFields` and foreign-key columns a `CASCADE` or `SET NULL` action can change, and values a line cannot hold, such as a bigint, which are still written as the database has them; with `'all'` every value the schema gives is still written.
8
+
9
+ `findWithDefaults()` now also returns `input` for each row: the row as its line holds it, the values before the schema transformed them, without the fields the schema filled in. The studio's rows response carries it as `inputs`, and the studio can show each value as its input, its output (read-only), or both, the input marked `in` above the output marked `out`; the input is what a cell and the form edit.
10
+
11
+ Updating one field of a row no longer rewrites the other fields of its line with the values the schema made of them: with the line `{"id":1,"code":"a","note":"n"}`, changing only `note` used to write `"code":"ORD-a"`, which the schema turned into `"ORD-ORD-a"` on the next load. With `writeFilledValues: 'primaryKey'`, a field the line holds and nothing set now keeps the line's value; `'all'` still writes the value the schema gives.
12
+
13
+ A write-back finds the line of a row again by the primary key the schema makes of it, so a table whose schema transforms its primary key keeps the keys its lines hold, and a table without a primary key, and a row whose primary key was changed, find it by the position its line had when the file was read, kept up to date as rows are added and removed. The studio edits a column whose lines hold another type than the schema makes in its Input view, and every new row, as text when the lines hold strings and as JSON otherwise. A rowid change made by an ON UPDATE CASCADE, or by raw SQL, carries the row's recorded position with it, and a row with a recorded position keeps its line even when its key moves onto another row's old key.
14
+
15
+ A line's fields that the schema does not know, and the fields a migration `transform` set, now stay with their own row when a table's integer primary keys are not in order in the file: with the lines `{"id":3,"extra":"x3"}` and `{"id":1,"extra":"x1"}`, updating row 1 used to swap the two `extra` values.
16
+
17
+ A row whose key changes while a write-back of its table is in progress keeps its line, and the log of rowid changes works with the SQLite that Bun ships, which refuses a qualified table name in a trigger.
18
+
19
+ `update` now stores what the validation schema makes of each value it is given, as `insert` does: updating `code` to `"b"` used to leave `"b"` in the database, so the studio's Output view and `find()` showed `"b"` instead of `"ORD-b"` until the file was loaded again. The line still holds `"b"`.
20
+ - Updated dependencies [1a510a8]
21
+ - lines-db@0.19.2
22
+
23
+ ## 0.16.6
24
+
25
+ ### Patch Changes
26
+
27
+ - 4bfd4b7: Read the files a schema file imports anew when one of them changed, so an edit to a project file the schema imports, such as a table definition, is validated against instead of the version first loaded. Once the first read has recorded the imports, a file is evaluated again only when it or a file it imports changed, except after a read that failed, so reading the tables again many times does not grow memory with the number of files. A package from `node_modules`, and a file of another package, such as one linked from a workspace, stay one module. A runtime without synchronous module hooks still reads only the schema file itself again, and CommonJS schemas (`.schema.cts`) keep their first evaluation, as before.
28
+
29
+ `hasExternalChanges()` and `findExternalChanges()` now report an edit to, or the removal of, a project file the schemas imported, so the studio reloads when only a table definition changed. `listSchemaDependencies()` lists the project files a database's schemas imported. With synchronous module hooks, a relative import of a file that was not there when the tables were read is tracked too, so creating the file is reported as a change. Calling `initialize()` again in the same process before an earlier call has finished can leave `hasExternalChanges()` reporting no change for a file edited while the earlier call was reading; the studio reads the tables one reload at a time and is not affected. The studio watches the imported files too, so an open page is told as soon as one of them is edited or created, even when it is outside the watched directories; a file that is not there yet is watched through the directory that would hold it, or the nearest one that exists.
30
+ - Updated dependencies [4bfd4b7]
31
+ - lines-db@0.19.1
32
+
3
33
  ## 0.16.5
4
34
 
5
35
  ### Patch Changes
package/README.ja.md CHANGED
@@ -35,6 +35,8 @@ JSONオブジェクトはキーごと、配列は要素ごとに入力欄を表
35
35
 
36
36
  保存するのは、明示的に指定したフィールドと生成された主キーです。それ以外のスキーマの既定値はファイルに書きません。既定値も含めて保存するには`--write-filled-values all`を使います。詳しくは[書き戻しの挙動](https://github.com/toiroakr/lines-db/blob/main/lib/README.ja.md#スキーマが補う値)を参照してください。
37
37
 
38
+ スキーマが値を変換する場合(`create`フックが`"1"`を`"ORD-1"`にするなど)、グリッドに**Input / Output / Both**の切り替えが出ます。既定のInputはファイルが持つ値で、セルで編集できます。Outputはスキーマが変換した値で、編集できません。ファイルの値が、スキーマが作る値と別の型の列(真偽値の列の`"yes"`など)は、Input表示では、ファイルの値が文字列ならテキストとして、数値やオブジェクトなど文字列以外を含むならJSONとして編集します。新しい行は、表示に関わらず、この入力側の型で入力します。スキーマが名前を変える(`backward`)か捨てるために、ファイルにだけある列は、Input表示に**file only**として、スキーマがほかの列から作る列は**made by the schema**として表示し、既存の行ではどちらも編集できません。新しい行には、file only の列を含めてファイルが持つ列を入力し、スキーマが作る列は入力しません。Bothは、編集できる入力に**in**、その下に出力を**out**の印を付けて縦に並べます。既定の`--write-filled-values primaryKey`では保存で入力を書きます。ただし`writeBackFields`で指定したフィールド、`CASCADE`や`SET NULL`で変わりうる外部キー列、bigintのように行に書けない値は、データベースの値を書きます。`all`では変換後の値を書きます。
39
+
38
40
  ### 検証エラーのある行を直す
39
41
 
40
42
  検証エラーのあるテーブルは、元のファイルの内容を表示し、該当する行とセルに印を付けます。修正を保存すると、その行を検証して1行だけを書き換えます。他の行は変更しません。全行の検証が通ると、通常のテーブルとして読み込みます。
@@ -69,7 +71,7 @@ npx lines-db studio --data-dir seed/data --data-dir seed/data/cogs --schema-dir
69
71
 
70
72
  ## 他のツールでファイルを変更した場合
71
73
 
72
- Studioはディスク上のファイルを監視します。未保存の編集がなければ変更後のデータを読み直し、編集が残っていれば通知を表示します。
74
+ Studioはディスク上のファイルを監視します。スキーマがimportするテーブル定義などのプロジェクト内ファイルも対象です。未保存の編集がなければ変更後のデータを読み直し、編集が残っていれば通知を表示します。
73
75
 
74
76
  保存前にスキーマの変更を確認し、変更されていれば読み直して検証します。書き込み対象のファイルが変更されていた場合は、何も書き込まずに保存を中止します。ファイル名を表示し、テーブルを読み直します。`CASCADE`や`SET NULL`などの外部キーの操作で変更されるテーブルも対象です。無関係なテーブルのファイルの変更では保存を中止しません。
75
77
 
package/README.md CHANGED
@@ -35,6 +35,8 @@ Values supplied by the schema are dimmed and marked **default**. **Remove field*
35
35
 
36
36
  By default, saves write explicitly supplied fields and generated primary keys. Other schema defaults remain omitted. Use `--write-filled-values all` to write every value, including defaults. See [write-back behavior](https://github.com/toiroakr/lines-db/blob/main/lib/README.md#values-the-schema-fills-in) for details.
37
37
 
38
+ When the schema transforms a value (a `create` hook turning `"1"` into `"ORD-1"`), the grid shows an **Input / Output / Both** switch. Input, the default, is what the file holds and what a cell edits; Output is what the schema makes of it and is read-only; a column whose lines hold values of another type than the schema makes (such as `"yes"` for a boolean) is edited in the Input view as text when the lines hold strings, and as JSON when they hold other values, such as numbers or objects; a new row is always filled in by these input types; a field only the lines hold, which the schema renames (a `backward` transformation) or removes, is shown in the Input view marked **file only**, and a field the schema makes from others is marked **made by the schema**, both read-only for a row of the file; a new row is given the fields the file holds, file only ones included, and not those the schema makes; Both shows the editable input marked **in** with the output marked **out** under it. With the default `--write-filled-values primaryKey`, a save writes the input, except for fields named in `writeBackFields`, foreign-key columns a `CASCADE` or `SET NULL` action can change, and values a line cannot hold, such as a bigint, which are written as the database has them; with `all` it writes the transformed value.
39
+
38
40
  ### Fix invalid rows
39
41
 
40
42
  When a table contains rows that fail validation, Studio displays the original file and marks the affected rows and cells. Saving a correction validates the row and rewrites only that line. Other lines remain unchanged. Once every row passes validation, Studio loads the table normally.
@@ -69,7 +71,7 @@ Updates and deletions go back to each row's source file. In **Add record**, choo
69
71
 
70
72
  ## Changes made outside Studio
71
73
 
72
- Studio watches the files on disk. With no pending edits, it reloads changed data automatically. With pending edits, it shows a notice.
74
+ Studio watches the files on disk, including the project files the schemas import, such as a table definition. With no pending edits, it reloads changed data automatically. With pending edits, it shows a notice.
73
75
 
74
76
  Before saving, Studio reloads changed schemas and validates against them. If a file that the save would write has changed, the save stops, names the file, and reloads the tables without writing. This includes tables affected by foreign key actions such as `CASCADE` or `SET NULL`. Changes to unrelated table files do not stop the save.
75
77
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA8BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA+BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { existsSync } from "node:fs";
3
4
  import { readFile, realpath, stat, writeFile } from "node:fs/promises";
4
5
  import { createServer } from "node:http";
5
6
  import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
6
7
  import { fileURLToPath, pathToFileURL } from "node:url";
7
8
  import { watch } from "zygiella";
8
9
  import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
9
- import { hashJsonlContent, replaceFile } from "lines-db/internal";
10
+ import { createSchemaImports, hashJsonlContent, replaceFile } from "lines-db/internal";
10
11
  // src/declared-columns.ts
11
12
  const CORSA_NULL = 8;
12
13
  const CORSA_UNION = 134217728;
@@ -277,7 +278,14 @@ async function startStudioServer(options) {
277
278
  const uiDir = options.uiDir ?? shippedUiDir();
278
279
  const token = randomBytes(24).toString("base64url");
279
280
  const writeFilledValues = options.writeFilledValues ?? "primaryKey";
280
- const load = () => loadSnapshot(dataDirs, options.schemaDir, writeFilledValues);
281
+ let failedDependencies = [];
282
+ const load = async () => {
283
+ const loaded = await loadSnapshot(dataDirs, options.schemaDir, writeFilledValues, (files) => {
284
+ failedDependencies = files;
285
+ });
286
+ failedDependencies = [];
287
+ return loaded;
288
+ };
281
289
  let snapshot = await load();
282
290
  let queue = Promise.resolve();
283
291
  const serialize = (fn) => {
@@ -288,7 +296,11 @@ async function startStudioServer(options) {
288
296
  /** Reload the tables when a JSONL file no longer holds what they were read from; true if it did */
289
297
  const reloadUnlocked = async () => {
290
298
  const previous = snapshot;
291
- snapshot = await load();
299
+ try {
300
+ snapshot = await load();
301
+ } finally {
302
+ watchDependencies();
303
+ }
292
304
  await previous.db.close();
293
305
  };
294
306
  const reloadIfChangedUnlocked = async () => {
@@ -349,18 +361,19 @@ async function startStudioServer(options) {
349
361
  };
350
362
  const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
351
363
  let watchTimer;
364
+ const scheduleReload = () => {
365
+ clearTimeout(watchTimer);
366
+ watchTimer = setTimeout(() => {
367
+ reloadIfChanged().catch(notifyChanged);
368
+ }, 100);
369
+ };
352
370
  const watchers = (await Promise.all([.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].map(async (dir) => {
353
371
  try {
354
372
  const watcher = watch(dir, {
355
373
  ignoreInitial: true,
356
374
  depth: 0
357
375
  });
358
- watcher.on("all", () => {
359
- clearTimeout(watchTimer);
360
- watchTimer = setTimeout(() => {
361
- reloadIfChanged().catch(notifyChanged);
362
- }, 100);
363
- });
376
+ watcher.on("all", scheduleReload);
364
377
  watcher.on("error", (error) => {
365
378
  console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
366
379
  watcher.close();
@@ -377,6 +390,40 @@ async function startStudioServer(options) {
377
390
  return [];
378
391
  }
379
392
  }))).flat();
393
+ const existingPathOf = (file) => {
394
+ let path = file;
395
+ while (!existsSync(path) && dirname(path) !== path) path = dirname(path);
396
+ return path;
397
+ };
398
+ let dependencyWatcher;
399
+ let watchedDependencies = [];
400
+ const watchDependencies = () => {
401
+ const wanted = [...new Set([...snapshot.db.listSchemaDependencies(), ...failedDependencies].map(existingPathOf))];
402
+ if (!dependencyWatcher) {
403
+ if (wanted.length === 0) return;
404
+ try {
405
+ const created = watch(wanted, {
406
+ ignoreInitial: true,
407
+ depth: 0
408
+ });
409
+ created.on("all", scheduleReload);
410
+ created.on("error", (error) => {
411
+ console.warn(`Live reload is off for the files the schemas import: ${errorMessage(error)}`);
412
+ created.close();
413
+ if (dependencyWatcher === created) dependencyWatcher = void 0;
414
+ });
415
+ dependencyWatcher = created;
416
+ } catch (error) {
417
+ console.warn(`Live reload is off for the files the schemas import: ${errorMessage(error)}`);
418
+ return;
419
+ }
420
+ } else {
421
+ dependencyWatcher.unwatch(watchedDependencies.filter((file) => !wanted.includes(file)));
422
+ dependencyWatcher.add(wanted.filter((file) => !watchedDependencies.includes(file)));
423
+ }
424
+ watchedDependencies = wanted;
425
+ };
426
+ watchDependencies();
380
427
  const server = createServer((req, res) => {
381
428
  handle(req, res).catch((error) => sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }));
382
429
  });
@@ -538,7 +585,8 @@ async function startStudioServer(options) {
538
585
  const rows = unwrap(await snapshot.db.findWithDefaults(tableName));
539
586
  sendJson(res, 200, {
540
587
  rows: rows.map(({ row }) => row),
541
- defaulted: rows.map(({ defaulted }) => defaulted)
588
+ defaulted: rows.map(({ defaulted }) => defaulted),
589
+ inputs: rows.map(({ input }) => input)
542
590
  });
543
591
  return;
544
592
  }
@@ -697,10 +745,11 @@ async function startStudioServer(options) {
697
745
  const outcome = await serialize(async () => {
698
746
  const changedFiles = unwrap(await snapshot.db.findExternalChanges());
699
747
  if (changedFiles.length > 0) {
748
+ const tableImports = snapshot.db.listSchemaDependencies(tableName);
700
749
  await reloadUnlocked();
701
750
  reloaded = true;
702
751
  if (write.kind === "check") changedFiles.length = 0;
703
- const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`));
752
+ const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`) || tableImports.includes(file));
704
753
  if (ownFile) return {
705
754
  status: 409,
706
755
  body: { message: `${relative(dataDir, ownFile) || ownFile} changed on disk, so the tables were reloaded. Check the rows and try again.` },
@@ -796,7 +845,7 @@ async function startStudioServer(options) {
796
845
  });
797
846
  });
798
847
  } catch (error) {
799
- await Promise.all(watchers.map((watcher) => watcher.close()));
848
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
800
849
  await snapshot.db.close();
801
850
  throw error;
802
851
  }
@@ -805,7 +854,7 @@ async function startStudioServer(options) {
805
854
  url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
806
855
  token,
807
856
  close: async () => {
808
- await Promise.all(watchers.map((watcher) => watcher.close()));
857
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
809
858
  clearTimeout(watchTimer);
810
859
  server.closeAllConnections();
811
860
  await new Promise((resolve) => server.close(() => resolve()));
@@ -816,7 +865,7 @@ async function startStudioServer(options) {
816
865
  async function replaceUnchangedFile(file, next, expected) {
817
866
  await replaceFile(file, (temporary) => writeFile(temporary, next, "utf8"), expected);
818
867
  }
819
- async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
868
+ async function loadSnapshot(dataDir, schemaDir, writeFilledValues, onFailure) {
820
869
  const db = LinesDB.create({
821
870
  dataDir,
822
871
  schemaDir,
@@ -830,6 +879,7 @@ async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
830
879
  const baseDir = [dataDir].flat()[0];
831
880
  const loaded = await db.initialize({ detailedValidate: true });
832
881
  if (!loaded.ok) {
882
+ onFailure(db.listSchemaDependencies());
833
883
  await db.close();
834
884
  if (loaded.error.name === "JsonlParseError") {
835
885
  const { file, line, message } = loaded.error;
@@ -907,7 +957,7 @@ async function foreignKeysInFile(dataDir, tableName) {
907
957
  const schemaPath = await findSchemaFile(dataDir, tableName);
908
958
  if (!schemaPath) return [];
909
959
  try {
910
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
960
+ const module = await createSchemaImports().import(schemaPath);
911
961
  return (module.schema ?? module.default)?.foreignKeys ?? module.foreignKeys ?? [];
912
962
  } catch {
913
963
  return [];