@jskit-ai/database-runtime 0.1.264 → 0.1.266

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
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `countQueries(knex, work)` and `countRuntimeQueries(work)` count only the statements `work` sends, with those of the async work it starts (they run it in an `AsyncLocalStorage` scope): another test, or a background loop, sending through the same Knex or runtime meanwhile is left out, where its statements counted too and could make a flat path look as if it grew. A loop started before `work` that sends on its behalf is left out as well. A count nested in another counts for both, as before.
5
6
  - `./server/testDatabases` exports `createPackageTestKnex(t, { environment })`, the Knex a package's own data test runs on when it creates its tables in the test: an in-memory SQLite database, or on a `DB_CLIENT=pg` run a schema of the test's own in `TEST_DB_NAME` (on DB_HOST, DB_PORT, DB_USER and DB_PASSWORD), in UTC, with a pool of up to eight connections for concurrent transactions, dropped with everything in it after the test. It refuses `NODE_ENV=production`, and a pg run without `TEST_DB_NAME` fails (`TestDatabaseMissingError`).
6
7
  - `listForeignKeys(knex)` (`./server/foreignKeyMigrations`) answers every foreign key of the connected database's tables in one statement, each with its table, its columns in order and the table and columns it references, on MySQL, MariaDB, PostgreSQL (the current schema) and SQLite (whose keys have no name). `testDatabaseRun` takes `checkDatabase(knex)`, run once on the prepared `TEST_DB_NAME` before any test file: its answer joins the summary and a throw fails the run.
7
8
  - `@jskit-ai/database-runtime-mysql` and `@jskit-ai/database-runtime-postgres` take `@jskit-ai/database-runtime` as a required peer at the same version, where it was a dependency, as `@jskit-ai/resource-runtime` and `@jskit-ai/crud-core` do: the application declares it beside its driver (`npm install @jskit-ai/database-runtime @jskit-ai/database-runtime-mysql`) and holds its one copy. npm installs a required peer as it installed the dependency.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/database-runtime",
3
- "version": "0.1.264",
3
+ "version": "0.1.266",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -82,6 +82,6 @@
82
82
  }
83
83
  },
84
84
  "peerDependencies": {
85
- "@jskit-ai/kernel": "0.2.15"
85
+ "@jskit-ai/kernel": "0.2.17"
86
86
  }
87
87
  }
@@ -22,6 +22,7 @@
22
22
  // of a server the test booted, countRuntimeQueries(); expectFlatQueries() in @jskit-ai/resource-runtime/test compares
23
23
  // those counts at a few rows and at many. A data test never skips: requireTestDatabase() fails it when TEST_DB_NAME is
24
24
  // not set.
25
+ import { AsyncLocalStorage } from "node:async_hooks";
25
26
  import { createHash, randomBytes } from "node:crypto";
26
27
  import diagnosticsChannel from "node:diagnostics_channel";
27
28
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -524,8 +525,13 @@ async function testDatabaseRun({ knexConfig, environment, count, schema, appRoot
524
525
  };
525
526
  }
526
527
 
528
+ // The recordings open in the current async context, outermost first: a statement counts for each recording whose work
529
+ // (or work it started) sends it, and for no other, so a test or a loop running beside the work is left out.
530
+ const openRecordings = new AsyncLocalStorage();
531
+
527
532
  /**
528
533
  * Runs `work` while `listen` hands each statement to the recorder it is given, and stops listening when `work` ends.
534
+ * The recorder keeps only the statements sent from `work`'s own async context, and from the async work it starts.
529
535
  * @template T
530
536
  * @param {(record: (query: { sql: string }) => void) => () => void} listen Starts listening; returns how to stop.
531
537
  * @param {() => Promise<T> | T} work
@@ -533,11 +539,14 @@ async function testDatabaseRun({ knexConfig, environment, count, schema, appRoot
533
539
  */
534
540
  async function recordStatements(listen, work) {
535
541
  const queries = [];
542
+ const recording = Symbol("recording");
536
543
  const stop = listen((query) => {
537
- queries.push(String(query.sql));
544
+ if (openRecordings.getStore()?.includes(recording)) queries.push(String(query.sql));
538
545
  });
539
546
  try {
540
- const result = await work();
547
+ // Awaited inside the scope: work may answer a lazy thenable, such as a Knex builder or app.inject()'s chain, that
548
+ // sends its statement only once it is awaited.
549
+ const result = await openRecordings.run([...(openRecordings.getStore() || []), recording], async () => await work());
541
550
  return { result, count: queries.length, queries };
542
551
  } finally {
543
552
  stop();
@@ -547,7 +556,9 @@ async function recordStatements(listen, work) {
547
556
  /**
548
557
  * Runs `work` and records the SQL of every statement `knex` sends meanwhile, its transactions' included (their BEGIN
549
558
  * and COMMIT among them), for a test that compares a path's statements at a few rows and at many. Pass the Knex
550
- * instance or transaction the work runs on; statements anything else sends through it meanwhile count too.
559
+ * instance or transaction the work runs on. Only the statements `work` sends count, with those of the async work it
560
+ * starts: another test or a background loop sending through the same Knex meanwhile is left out, and so is a loop
561
+ * started before `work` that sends on its behalf.
551
562
  * @template T
552
563
  * @param {import("knex").Knex | import("knex").Knex.Transaction} knex
553
564
  * @param {() => Promise<T> | T} work
@@ -565,7 +576,8 @@ async function countQueries(knex, work) {
565
576
  * Runs `work` and records the SQL of every statement the application runtime's own database sends meanwhile: the
566
577
  * `runtime.database` Knex of each server this process booted, as a test that creates the server with `createServer()`
567
578
  * and calls a route with `app.inject()` does, its transactions' included. A Knex the test made itself is not counted,
568
- * and neither is a server in another process. Statements the runtime sends for anything else meanwhile count too.
579
+ * and neither is a server in another process. Only the statements `work` sends count, as countQueries() counts them:
580
+ * the runtime's statements for anything else meanwhile, such as a background loop's, are left out.
569
581
  * @template T
570
582
  * @param {() => Promise<T> | T} work
571
583
  * @returns {Promise<{ result: T, count: number, queries: string[] }>} `work`'s result, how many statements the runtime
@@ -148,6 +148,17 @@ test("countQueries() records each statement a piece of work sends, so a read per
148
148
  assert.deepEqual(inTransaction.result, { title: "Book 1" });
149
149
  assert.deepEqual(inTransaction.queries, ["BEGIN;", "select `title` from `books` where `id` = ? limit ?", "COMMIT;"]);
150
150
 
151
+ // Only the work's own statements count: work running beside it, such as another test or a background loop, is
152
+ // left out, even while the work waits for it.
153
+ let wake;
154
+ const beside = new Promise((resolve) => { wake = resolve; }).then(() => knex("books").count({ books: "*" }));
155
+ const alone = await countQueries(knex, async () => {
156
+ wake();
157
+ await beside;
158
+ return knex("books").where({ id: ids[0] }).first("title");
159
+ });
160
+ assert.deepEqual(alone.queries, ["select `title` from `books` where `id` = ? limit ?"]);
161
+
151
162
  // Counting ends with the work, failed work included.
152
163
  const listeners = knex.listenerCount("query");
153
164
  await assert.rejects(countQueries(knex, async () => {