masterrecord 1.3.1 → 1.3.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/CHANGES.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.3.3 — `.toList()` no longer silently caps at 1000 rows
4
+
5
+ **Bug (high — silent data loss):** `.toList()` injected a default `LIMIT 1000` whenever the caller hadn't chained `.take()`. Any query matching more than 1000 rows silently returned only the first 1000 — no error, no warning, undocumented. Aggregates derived from the result (counts, sums, "does X exist?") were silently wrong. The cap was also gated on `entityMap.length === 0`, so an `.include()` query was **not** capped while the same query without an include **was** — identical-looking calls behaved differently. (EF/LINQ's `ToList()`, which this API mirrors, returns everything.)
6
+
7
+ **Fix:**
8
+ - Removed the implicit cap in `toList()` — it now returns **all** matching rows. `.take(n)` still limits explicitly, and `.include()` / non-include queries now behave identically.
9
+ - Removing the cap exposed a latent bug it had been masking: SQLite and MySQL reject a bare `OFFSET` with no `LIMIT`, so `.skip()` **without** `.take()` would have produced invalid SQL. `buildSkip()` now emits valid pagination on every engine:
10
+ - **SQLite** — `LIMIT -1 OFFSET n` (`-1` = no upper bound)
11
+ - **MySQL** — `LIMIT 18446744073709551615 OFFSET n` (max `BIGINT UNSIGNED`, the documented "all rows from offset" sentinel)
12
+ - **Postgres** — `OFFSET n` (a bare `OFFSET` is already valid; left as-is)
13
+
14
+ New test: `test/tolist-no-implicit-limit.test.js` — SQLite executes 1500-row `toList()` (returns all), `where().toList()` (> 1000), `.take()` still limits, bare `.skip()` pages to the end, `.skip().take()` windows; plus `buildSkip()` SQL-shape assertions for all three engines. A gated cross-engine integration test seeds 1500 rows and asserts `toList()`/bare-`.skip()` against live MySQL/Postgres. Full suite green (0 fail); 0 lint errors.
15
+
16
+ ## v1.3.2 — migration CLI auto-creates a missing MySQL/Postgres database
17
+
18
+ **Bug (critical for first deploys):** `update-database` printed *"Instantiating Context (this will create the database if it doesn't exist)…"*, but it `await`ed the raw `context._initPromise` directly. When the target database didn't exist, that promise rejected with `Unknown database 'X'` (MySQL) / `database "X" does not exist` (Postgres), and the catch block merely reported failure and exited — it **never invoked the auto-create** (`_createDatabaseFromConfig` + retry) that lives in `schema._ensureReady()`. So a first-time deploy against an empty server failed with a confusing error despite the CLI claiming it would create the database. (Confirmed present through 1.3.1.)
19
+
20
+ **Fix:**
21
+ - New shared bootstrap `Migrations/contextInit.js` → `instantiateReadyContext(ContextCtor)` routes context construction through `schema._ensureReady()`, which auto-creates a missing MySQL/Postgres database and retries the connection. It marks the returned context `_ready` so later `_execute()`/`query()` calls don't re-await the now-settled (rejected) original init promise. SQLite is unaffected (the driver creates the file on open).
22
+ - `update-database`, `update-database-restart`, and `update-database-all` now use it. `update-database-restart`/`-all` additionally never awaited async MySQL/Postgres init at all — also fixed.
23
+
24
+ **Deep-dive findings (fixed in the same release):**
25
+ - `context.query()` blindly awaited `_initPromise`, so after the auto-create retry swapped in a live engine it could still re-throw the stale rejection. It now goes through `_ensureReady()` (short-circuits on `_ready`).
26
+ - `add-migration-all` constructed contexts **without** `MASTERRECORD_SCHEMA_ONLY`, unlike the single `add-migration` — so generating migrations for all contexts needlessly required a reachable database (and hit the missing-DB init path on MySQL/Postgres). Now schema-only, matching `add-migration`.
27
+ - Reviewed the remaining construction sites: `ensure-database` (dedicated create — correct), per-migration `new Migration(ContextCtor)` (each runs `schema._ensureReady()` internally — correct), and the rollback commands `update-database-down`/`-target` (auto-create is intentionally **not** applied — you can't roll back a database that was never created; `-down` already awaits init, `-target` never queries its bootstrap context).
28
+
29
+ New tests: `test/cli-context-init.test.js` (SQLite: bootstrap returns a ready, queryable context) and a gated `[engine] migration bootstrap AUTO-CREATES a missing database` integration test (drops a throwaway DB, bootstraps, asserts it was created and is queryable). Full suite green (0 fail); 0 lint errors. The live auto-create assertion runs in CI against the MySQL/Postgres service containers.
30
+
3
31
  ## v1.3.1 — portable snapshots + heterogeneous batch inserts
4
32
 
5
33
  **Fixed — Windows-generated migration snapshots broke Linux deploys (critical).**
package/Migrations/cli.js CHANGED
@@ -11,6 +11,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
11
11
  import { globSync } from 'glob';
12
12
  import { resolveMigrationsDirectory, toPosixPath } from './pathUtils.js';
13
13
  import Migration from './migrations.js';
14
+ import { instantiateReadyContext } from './contextInit.js';
14
15
 
15
16
  const __filename = fileURLToPath(import.meta.url);
16
17
  const __dirname = path.dirname(__filename);
@@ -473,12 +474,12 @@ program.option('-V', 'output the version');
473
474
  console.log(`\n🔍 Instantiating Context (this will create the database if it doesn't exist)...`);
474
475
 
475
476
  try{
476
- contextInstance = new ContextCtor();
477
- // MySQL/Postgres initialize asynchronously — wait for the pool
478
- // before we can run any migration queries against it.
479
- if (contextInstance && contextInstance._initPromise) {
480
- await contextInstance._initPromise;
481
- }
477
+ // Route through the schema layer so a missing MySQL/Postgres
478
+ // database is AUTO-CREATED (and the connection retried) before any
479
+ // migration runs — honoring the message printed just above. Awaiting
480
+ // the raw _initPromise here used to just report "Unknown database"
481
+ // and exit without ever creating it.
482
+ contextInstance = await instantiateReadyContext(ContextCtor);
482
483
  }catch(err){
483
484
  console.error(`\n❌ Error - Failed to instantiate Context`);
484
485
  console.error(`\nContext file: ${contextAbs}`);
@@ -792,7 +793,9 @@ program.option('-V', 'output the version');
792
793
  }
793
794
  var contextInstance;
794
795
  try{
795
- contextInstance = new ContextCtor();
796
+ // Auto-create a missing MySQL/Postgres database (and await async
797
+ // init) via the schema layer before applying migrations.
798
+ contextInstance = await instantiateReadyContext(ContextCtor);
796
799
  }catch(err){
797
800
  console.error(`\n❌ Error - Failed to construct Context from '${contextAbs}'`);
798
801
  console.error(`\nThis usually happens when:`);
@@ -1030,9 +1033,16 @@ program.option('-V', 'output the version');
1030
1033
  }
1031
1034
  let contextInstance;
1032
1035
  try{
1036
+ // Generating a migration only needs entity metadata, not a live DB.
1037
+ // Schema-only mode skips connection/init — matching `add-migration`
1038
+ // (without it, add-migration-all needlessly required a reachable
1039
+ // database and would hit the missing-DB init path on MySQL/Postgres).
1040
+ process.env.MASTERRECORD_SCHEMA_ONLY = '1';
1033
1041
  contextInstance = new ContextCtor();
1042
+ delete process.env.MASTERRECORD_SCHEMA_ONLY;
1034
1043
  contextInstances.push(contextInstance);
1035
1044
  }catch(err){
1045
+ delete process.env.MASTERRECORD_SCHEMA_ONLY;
1036
1046
  console.error(`⚠️ Skipping ${path.basename(contextAbs)}: failed to construct Context`);
1037
1047
  console.error(` Details: ${err.message}`);
1038
1048
  continue;
@@ -1147,7 +1157,9 @@ program.option('-V', 'output the version');
1147
1157
  }
1148
1158
  var contextInstance;
1149
1159
  try{
1150
- contextInstance = new ContextCtor();
1160
+ // Auto-create a missing MySQL/Postgres database (and await async
1161
+ // init) via the schema layer before applying migrations.
1162
+ contextInstance = await instantiateReadyContext(ContextCtor);
1151
1163
  contextInstances.push(contextInstance);
1152
1164
  }catch(err){
1153
1165
  console.error(`⚠️ Skipping ${entry.ctxName}: failed to construct Context`);
@@ -0,0 +1,39 @@
1
+ // version 1.3.2 - ESM only
2
+ import schema from './schema.js';
3
+
4
+ /**
5
+ * Instantiate a user context and ensure its database is reachable for
6
+ * migrations, AUTO-CREATING a missing MySQL/Postgres database (and retrying the
7
+ * connection) via the schema layer — the same path `ensure-database` uses.
8
+ *
9
+ * Why this exists: the migration CLI used to await the raw
10
+ * `context._initPromise` directly. When the target database didn't exist yet,
11
+ * that promise rejected with "Unknown database 'X'" (MySQL) /
12
+ * `database "X" does not exist` (Postgres), and the CLI's catch block merely
13
+ * reported failure and exited — it never invoked the auto-create that lives in
14
+ * `schema._ensureReady()` (`_createDatabaseFromConfig` + retry). So the CLI's
15
+ * own message "this will create the database if it doesn't exist" was a lie for
16
+ * a first-time deploy against an empty server. Routing through
17
+ * `schema._ensureReady()` makes that promise real.
18
+ *
19
+ * SQLite is unaffected (the driver creates the file on open); for SQLite this
20
+ * is just a normal construct-and-connect.
21
+ *
22
+ * @param {Function} ContextCtor - The user's context class (constructor)
23
+ * @returns {Promise<object>} A ready context whose engine/pool is live
24
+ * @throws Propagates a genuine connection/config failure (not "db missing")
25
+ */
26
+ export async function instantiateReadyContext(ContextCtor) {
27
+ const initSchema = new schema(ContextCtor);
28
+ await initSchema._ensureReady();
29
+ const ctx = initSchema.context;
30
+ // After _ensureReady() the engine/pool is live — including the
31
+ // create-database-then-retry path, which swaps in a fresh engine/pool but
32
+ // leaves the original (now-settled, possibly rejected) _initPromise in
33
+ // place. Mark the context ready so later context._execute() calls
34
+ // short-circuit context._ensureReady() instead of re-awaiting that promise.
35
+ ctx._ready = true;
36
+ return ctx;
37
+ }
38
+
39
+ export default instantiateReadyContext;
@@ -534,9 +534,6 @@ class queryMethods{
534
534
  async toList(){
535
535
  if(this.__queryObject.script.entityMap.length === 0){
536
536
  this.__queryObject.skipClause( this.__entity.__name);
537
- if(!this.__queryObject.script.take || this.__queryObject.script.take === 0){
538
- this.__queryObject.script.take = 1000;
539
- }
540
537
  }
541
538
 
542
539
  // Generate cache key
package/SQLLiteEngine.js CHANGED
@@ -374,7 +374,12 @@ class SQLLiteEngine {
374
374
 
375
375
  buildSkip(query){
376
376
  if(query.skip){
377
- return `OFFSET ${query.skip}`
377
+ // SQLite requires a LIMIT before OFFSET. When the caller paginated
378
+ // with .skip() but no .take(), emit `LIMIT -1` (SQLite's documented
379
+ // "no upper bound") so the OFFSET is valid SQL instead of a syntax
380
+ // error. Now that .toList() no longer injects a default LIMIT 1000,
381
+ // this is the path a bare .skip() takes.
382
+ return query.take ? `OFFSET ${query.skip}` : `LIMIT -1 OFFSET ${query.skip}`;
378
383
  }
379
384
  else{
380
385
  return "";
package/context.js CHANGED
@@ -2118,7 +2118,12 @@ class context {
2118
2118
  * await ctx.execute('UPDATE Step SET run_id = ? WHERE id = ?', ['run_x', 1]); // sqlite/mysql
2119
2119
  */
2120
2120
  async query(sql, params = []) {
2121
- if (this._initPromise) { await this._initPromise; } // MySQL/Postgres async init
2121
+ // Honor the readiness flag rather than blindly awaiting _initPromise:
2122
+ // after the migration auto-create path swaps in a live engine, the
2123
+ // original _initPromise may be settled-rejected, and re-awaiting it
2124
+ // would throw even though the connection is healthy. _ensureReady()
2125
+ // short-circuits on _ready and validates the engine.
2126
+ await this._ensureReady();
2122
2127
  if (!this._SQLEngine) {
2123
2128
  throw new DatabaseConnectionError(
2124
2129
  'Cannot run query: database engine not initialized. Ensure you have awaited env() before querying.',
@@ -54,7 +54,7 @@ context.User.where(u => $$.includes(u.id), [1, 2, 3]).toList();
54
54
  | `.take(n)` | Limit results | `.take(10)` |
55
55
  | `.skip(n)` | Offset results | `.skip(20)` |
56
56
  | `.search({ in, query })` | Full-text search (see [FULL_TEXT_SEARCH.md](FULL_TEXT_SEARCH.md)) | `context.MemoryDoc.search({ in: ['title','body'], query: 'auth login' })` |
57
- | `.toList()` | Execute and return array | `.where(...).toList()` |
57
+ | `.toList()` | Execute and return **all** matching rows as an array (no implicit limit — use `.take(n)`/`.skip(n)` to page) | `.where(...).toList()` |
58
58
  | `.single()` | Execute and return one | `.where(...).single()` |
59
59
  | `.first()` | Execute and return first | `.where(...).first()` |
60
60
  | `.include(lambda)` | Eager load relationships | `.include(u => u.Posts)` |
package/mySQLEngine.js CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.3.1",
3
+ "version": "1.3.3",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",
package/postgresEngine.js CHANGED
@@ -611,6 +611,8 @@ class postgresEngine {
611
611
 
612
612
  buildSkip(query) {
613
613
  if (query.skip) {
614
+ // Unlike SQLite/MySQL, Postgres accepts a bare OFFSET with no LIMIT,
615
+ // so a .skip() without .take() is valid as-is — no sentinel needed.
614
616
  return `OFFSET ${query.skip}`;
615
617
  }
616
618
  return "";
package/readme.md CHANGED
@@ -636,6 +636,10 @@ const users = await db.User
636
636
 
637
637
  ### Pagination
638
638
 
639
+ `.toList()` returns **all** matching rows — there is no implicit row limit (it
640
+ mirrors EF/LINQ `ToList()`). Use `.take(n)` to cap results and `.skip(n)` to
641
+ offset; a bare `.skip(n)` with no `.take()` pages to the end of the result set.
642
+
639
643
  ```javascript
640
644
  // Skip 20, take 10 (requires await)
641
645
  const users = await db.User
@@ -651,6 +655,12 @@ const users = await db.User
651
655
  .skip(page * pageSize)
652
656
  .take(pageSize)
653
657
  .toList();
658
+
659
+ // Everything after an offset (no upper bound)
660
+ const rest = await db.User.orderBy(u => u.id).skip(100).toList();
661
+
662
+ // Every row (no limit)
663
+ const everyone = await db.User.toList();
654
664
  ```
655
665
 
656
666
  ### Counting