masterrecord 0.3.68 → 1.0.1

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.
Files changed (103) hide show
  1. package/.claude/settings.local.json +3 -1
  2. package/CHANGES.md +31 -2
  3. package/Cache/QueryCache.js +10 -4
  4. package/Cache/RedisQueryCache.js +3 -2
  5. package/Entity/entityModel.js +1 -1
  6. package/Entity/entityModelBuilder.js +2 -2
  7. package/Entity/entityTrackerModel.js +3 -3
  8. package/Entity/fieldTransformer.js +1 -1
  9. package/FOREIGN_KEY_STRING_FIX.md +2 -2
  10. package/MasterRecord.js +6 -43
  11. package/Migrations/cli.js +44 -113
  12. package/Migrations/dependencyGraph.js +1 -1
  13. package/Migrations/migrationMySQLQuery.js +1 -1
  14. package/Migrations/migrationPostgresQuery.js +1 -1
  15. package/Migrations/migrationSQLiteQuery.js +1 -1
  16. package/Migrations/migrationTemplate.js +8 -39
  17. package/Migrations/migrations.js +16 -14
  18. package/Migrations/pathUtils.js +2 -5
  19. package/Migrations/pathUtils.test.js +33 -49
  20. package/Migrations/schema.js +52 -89
  21. package/QueryLanguage/queryMethods.js +4 -4
  22. package/QueryLanguage/queryParameters.js +1 -1
  23. package/QueryLanguage/queryScript.js +4 -3
  24. package/SQLLiteEngine.js +30 -8
  25. package/Tools.js +10 -8
  26. package/context.js +43 -42
  27. package/deleteManager.js +2 -2
  28. package/docs/MIGRATIONS_GUIDE.md +237 -532
  29. package/docs/POSTGRESQL_SETUP.md +4 -4
  30. package/docs/QUERY_CACHING_GUIDE.md +8 -7
  31. package/eslint.config.js +40 -0
  32. package/insertManager.js +28 -20
  33. package/mySQLConnect.js +2 -2
  34. package/mySQLEngine.js +161 -16
  35. package/package.json +34 -5
  36. package/postgresEngine.js +74 -26
  37. package/postgresSyncConnect.js +5 -3
  38. package/prettier.config.js +22 -0
  39. package/readme.md +35 -27
  40. package/test/context-errors.test.js +43 -0
  41. package/test/count-chained-where.test.js +136 -0
  42. package/test/esm-imports.test.js +110 -0
  43. package/test/fixtures/count-chained-where/config/environments/env.countchained.json +1 -0
  44. package/test/fixtures/count-chained-where/db/countctx.sqlite +0 -0
  45. package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +1 -0
  46. package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
  47. package/test/fixtures/query-builder-parity/config/environments/env.parity.json +1 -0
  48. package/test/fixtures/query-builder-parity/db/parityctx.sqlite +0 -0
  49. package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +1 -0
  50. package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
  51. package/test/migration-template.test.js +47 -0
  52. package/test/new-setter-large-string.test.js +191 -0
  53. package/test/pool-key.test.js +43 -0
  54. package/test/query-builder-parity.test.js +260 -0
  55. package/test/sqlite-lifecycle.test.js +76 -0
  56. package/.eslintrc.js +0 -290
  57. package/.prettierrc.js +0 -109
  58. package/test/anyCommaStringTest.js +0 -237
  59. package/test/anyMethodTest.js +0 -176
  60. package/test/attachDetached.test.js +0 -303
  61. package/test/bulk-operations-test.js +0 -235
  62. package/test/cache-toObject-test.js +0 -105
  63. package/test/cacheIntegration.test.js +0 -319
  64. package/test/config-glob-pattern-test.js +0 -232
  65. package/test/double-where-bug-test.js +0 -71
  66. package/test/ensure-ready-test.js +0 -251
  67. package/test/entity-deduplication-test.js +0 -174
  68. package/test/entity-methods-test.js +0 -269
  69. package/test/findByIdTest.js +0 -227
  70. package/test/foreign-key-string-value-test.js +0 -406
  71. package/test/global-model-registry-test.js +0 -538
  72. package/test/id-setting-validation.js +0 -202
  73. package/test/includesFeatureTest.js +0 -183
  74. package/test/includesTransformTest.js +0 -110
  75. package/test/index-bug-fix-test.js +0 -188
  76. package/test/insert-return-test.js +0 -39
  77. package/test/lifecycle-hooks-test.js +0 -258
  78. package/test/multiContextCache.test.js +0 -230
  79. package/test/new-entity-migration-test.js +0 -162
  80. package/test/newMethodTest.js +0 -330
  81. package/test/newMethodUnitTest.js +0 -320
  82. package/test/optInCache.test.js +0 -221
  83. package/test/parameterizedPlaceholderTest.js +0 -159
  84. package/test/pool-registry-test.js +0 -303
  85. package/test/post-insert-tracking-test.js +0 -258
  86. package/test/postgresEngineTest.js +0 -463
  87. package/test/postgresIntegrationTest.js +0 -381
  88. package/test/promise-detection-test.js +0 -290
  89. package/test/qa-context-pattern-test.js +0 -319
  90. package/test/query-helpers-test.js +0 -258
  91. package/test/query-isolation-test.js +0 -59
  92. package/test/queryCache.test.js +0 -148
  93. package/test/securityTest.js +0 -268
  94. package/test/seed-data-test.js +0 -212
  95. package/test/seed-deduplication-test.js +0 -313
  96. package/test/seed-features-integration-test.js +0 -418
  97. package/test/seed-migration-template-test.js +0 -220
  98. package/test/singleDollarPlaceholderTest.js +0 -238
  99. package/test/tablePrefixTest.js +0 -100
  100. package/test/transformerTest.js +0 -287
  101. package/test/v0.3.34-bug-fixes-test.js +0 -428
  102. package/test/validation-test.js +0 -302
  103. package/test/whereChainingTest.js +0 -88
package/postgresEngine.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // Version 0.1.0 - Complete PostgreSQL implementation with pg 8.16.3
2
- const tools = require('./Tools');
3
- const FieldTransformer = require('./Entity/fieldTransformer');
4
- const { Pool } = require('pg');
2
+ import tools from './Tools.js';
3
+ import FieldTransformer from './Entity/fieldTransformer.js';
4
+ import pg from 'pg';
5
+
6
+ const { Pool } = pg;
5
7
 
6
8
  class postgresEngine {
7
9
 
@@ -196,8 +198,10 @@ class postgresEngine {
196
198
  query.count = "none";
197
199
  }
198
200
  const entityAlias = this.getEntity(entity.__name, query.entityMap);
201
+ // Include buildAnd so chained .and() calls survive into the
202
+ // COUNT SQL. Without this they were silently dropped.
199
203
  queryString = {
200
- query: `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)}`,
204
+ query: `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`,
201
205
  params: query.parameters ? query.parameters.getParams() : []
202
206
  };
203
207
  }
@@ -258,7 +262,9 @@ class postgresEngine {
258
262
  const entityStr = this.getEntity(entity.__name, query.entityMap);
259
263
  const params = query.parameters ? query.parameters.getParams() : [];
260
264
 
261
- const sql = `SELECT ${this.buildSelectString(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)} ${this.buildLimit(query)} ${this.buildSkip(query)} ${this.buildOrderBy(query, entity)}`;
265
+ // Standard SQL clause order: SELECT ... FROM ... WHERE ... AND ... ORDER BY ... LIMIT ... OFFSET ...
266
+ // The previous order placed LIMIT/OFFSET before ORDER BY, which Postgres rejects as a syntax error.
267
+ const sql = `SELECT ${this.buildSelectString(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)} ${this.buildOrderBy(query, entity)} ${this.buildLimit(query)} ${this.buildSkip(query)}`;
262
268
 
263
269
  return {
264
270
  query: sql,
@@ -266,9 +272,16 @@ class postgresEngine {
266
272
  };
267
273
  }
268
274
 
275
+ /**
276
+ * Build the column list after SELECT. If the user called `.select()`,
277
+ * `query.select` is a cachedExpr object with `selectFields` (not a string)
278
+ * — the previous implementation returned the object directly, which
279
+ * stringified to "[object Object]" and broke the query.
280
+ */
269
281
  buildSelectString(query, entity) {
270
- if (query.select) {
271
- return query.select;
282
+ if (query.select && query.select.selectFields && query.select.selectFields.length > 0) {
283
+ const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
284
+ return query.select.selectFields.map(f => `${alias}.${f}`).join(', ');
272
285
  }
273
286
  return `${tools.convertEntityToSelectParameterString(entity)}`;
274
287
  }
@@ -412,23 +425,39 @@ class postgresEngine {
412
425
  return "";
413
426
  }
414
427
 
428
+ /**
429
+ * Build ORDER BY clause from query.orderBy or query.orderByDesc.
430
+ * Both are objects shaped like `{ selectFields: ['col1', 'col2'], ... }`
431
+ * (see QueryLanguage/queryScript.js buildScript()). The previous
432
+ * implementation treated `query.orderBy` as a plain string and silently
433
+ * dropped the clause because the fluent API never produces that shape.
434
+ */
415
435
  buildOrderBy(query, entity) {
416
- if (query.orderBy) {
417
- // Security: Validate field exists in entity
418
- if (entity && !entity[query.orderBy]) {
419
- throw new Error(`Invalid ORDER BY field: ${query.orderBy} not found in ${entity.__name || 'entity'}`);
420
- }
421
- const entityStr = this.getEntity(query.parentName, query.entityMap);
422
- return `ORDER BY ${entityStr}.${query.orderBy} ASC`;
423
- } else if (query.orderByDescending) {
424
- // Security: Validate field exists in entity
425
- if (entity && !entity[query.orderByDescending]) {
426
- throw new Error(`Invalid ORDER BY field: ${query.orderByDescending} not found in ${entity.__name || 'entity'}`);
436
+ let orderByType = "ASC";
437
+ let orderByEntity = query.orderBy;
438
+ if (orderByEntity === false || orderByEntity === undefined) {
439
+ orderByType = "DESC";
440
+ orderByEntity = query.orderByDesc;
441
+ }
442
+ if (!orderByEntity) return "";
443
+
444
+ // Security: Validate field exists in entity before interpolating into SQL.
445
+ if (entity && orderByEntity.selectFields) {
446
+ for (const item in orderByEntity.selectFields) {
447
+ const field = orderByEntity.selectFields[item];
448
+ if (!entity[field]) {
449
+ throw new Error(`Invalid ORDER BY field: ${field} not found in ${entity.__name || 'entity'}`);
450
+ }
427
451
  }
428
- const entityStr = this.getEntity(query.parentName, query.entityMap);
429
- return `ORDER BY ${entityStr}.${query.orderByDescending} DESC`;
430
452
  }
431
- return "";
453
+
454
+ const entityStr = this.getEntity(query.parentName, query.entityMap);
455
+ const fieldList = [];
456
+ for (const item in orderByEntity.selectFields) {
457
+ fieldList.push(`${entityStr}.${orderByEntity.selectFields[item]}`);
458
+ }
459
+ if (fieldList.length === 0) return "";
460
+ return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
432
461
  }
433
462
 
434
463
  getEntity(name, list) {
@@ -572,9 +601,23 @@ class postgresEngine {
572
601
  params.push(model["_" + dirtyFields[column]]);
573
602
  break;
574
603
 
575
- default:
604
+ default: {
605
+ // Covers `text` and any other column type without a dedicated
606
+ // case above. Run the toDatabase transformer here too so that
607
+ // fields with a serializer (e.g. JSONB/text columns) get their
608
+ // object values turned into scalars before they reach pg.
609
+ let rawValue = model["_" + dirtyFields[column]];
610
+ if (rawValue === undefined) {
611
+ rawValue = model[dirtyFields[column]];
612
+ }
613
+ try {
614
+ rawValue = FieldTransformer.toDatabase(rawValue, model.__entity[dirtyFields[column]], model.__entity.__name, dirtyFields[column]);
615
+ } catch (transformError) {
616
+ throw new Error(`UPDATE failed: ${transformError.message}`);
617
+ }
576
618
  sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
577
- params.push(model["_" + dirtyFields[column]]);
619
+ params.push(rawValue);
620
+ }
578
621
  }
579
622
  }
580
623
 
@@ -603,14 +646,19 @@ class postgresEngine {
603
646
  fieldColumn = fields[modelEntity[column].foreignKey];
604
647
  }
605
648
 
606
- if ((fieldColumn !== undefined && fieldColumn !== null) && typeof(fieldColumn) !== "object") {
607
- // Apply toDatabase transformer
649
+ if (fieldColumn !== undefined && fieldColumn !== null) {
650
+ // 🔥 Apply toDatabase transformer FIRST — transformers may turn
651
+ // objects into scalars (e.g. JSON.stringify) so running them
652
+ // before the type check is essential for fields that use a
653
+ // custom serializer on top of a text/json column.
608
654
  try {
609
655
  fieldColumn = FieldTransformer.toDatabase(fieldColumn, modelEntity[column], modelEntity.__name, column);
610
656
  } catch (transformError) {
611
657
  throw new Error(`INSERT failed: ${transformError.message}`);
612
658
  }
659
+ }
613
660
 
661
+ if ((fieldColumn !== undefined && fieldColumn !== null) && typeof(fieldColumn) !== "object") {
614
662
  // Validate and coerce type
615
663
  try {
616
664
  fieldColumn = $that._validateAndCoerceFieldType(fieldColumn, modelEntity[column], modelEntity.__name, column);
@@ -804,4 +852,4 @@ class postgresEngine {
804
852
  }
805
853
  }
806
854
 
807
- module.exports = postgresEngine;
855
+ export default postgresEngine;
@@ -1,6 +1,8 @@
1
1
  // Version 1.0.0 - PostgreSQL connection helper for pg 8.16.3
2
- const { Pool } = require('pg');
3
- const postgresEngine = require('./postgresEngine');
2
+ import pg from 'pg';
3
+ import postgresEngine from './postgresEngine.js';
4
+
5
+ const { Pool } = pg;
4
6
 
5
7
  /**
6
8
  * PostgreSQL connection manager for MasterRecord
@@ -206,4 +208,4 @@ class PostgresSyncConnect {
206
208
  }
207
209
  }
208
210
 
209
- module.exports = PostgresSyncConnect;
211
+ export default PostgresSyncConnect;
@@ -0,0 +1,22 @@
1
+ export default {
2
+ printWidth: 100,
3
+ tabWidth: 4,
4
+ useTabs: false,
5
+ semi: true,
6
+ singleQuote: true,
7
+ quoteProps: 'as-needed',
8
+ trailingComma: 'es5',
9
+ bracketSpacing: true,
10
+ bracketSameLine: false,
11
+ arrowParens: 'avoid',
12
+ endOfLine: 'lf',
13
+ proseWrap: 'preserve',
14
+ htmlWhitespaceSensitivity: 'css',
15
+ singleAttributePerLine: false,
16
+ overrides: [
17
+ { files: '*.md', options: { printWidth: 80, proseWrap: 'always' } },
18
+ { files: '*.json', options: { tabWidth: 2 } },
19
+ { files: ['*.yml', '*.yaml'], options: { tabWidth: 2 } },
20
+ { files: 'package.json', options: { tabWidth: 2 } },
21
+ ],
22
+ };
package/readme.md CHANGED
@@ -3,6 +3,8 @@
3
3
  [![npm version](https://img.shields.io/npm/v/masterrecord.svg)](https://www.npmjs.com/package/masterrecord)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
+ > **ESM only.** As of v1.0, MasterRecord is a pure ESM package. Requires **Node.js 20+** and a host project with `"type": "module"` in `package.json`. There is no CommonJS build.
7
+
6
8
  **MasterRecord** is a lightweight, code-first ORM for Node.js with a fluent query API, comprehensive migrations, and multi-database support. Build type-safe queries with lambda expressions, manage schema changes with CLI-driven migrations, and work seamlessly across MySQL, PostgreSQL, and SQLite.
7
9
 
8
10
  ## Key Features
@@ -231,9 +233,9 @@ await db.saveChanges(); // ✅ Batch save
231
233
 
232
234
  ```javascript
233
235
  // app/models/context.js
234
- const context = require('masterrecord/context');
235
- const User = require('./User');
236
- const Post = require('./Post');
236
+ import context from 'masterrecord/context';
237
+ import User from './User.js';
238
+ import Post from './Post.js';
237
239
 
238
240
  class AppContext extends context {
239
241
  constructor() {
@@ -255,7 +257,7 @@ class AppContext extends context {
255
257
  }
256
258
  }
257
259
 
258
- module.exports = AppContext;
260
+ export default AppContext;
259
261
  ```
260
262
 
261
263
  ### 2. Define Entities
@@ -272,7 +274,7 @@ class User {
272
274
  }
273
275
  }
274
276
 
275
- module.exports = User;
277
+ export default User;
276
278
  ```
277
279
 
278
280
  ### 3. Run Migrations
@@ -291,7 +293,7 @@ masterrecord update-database AppContext
291
293
  ### 4. Query Your Data
292
294
 
293
295
  ```javascript
294
- const AppContext = require('./app/models/context');
296
+ import AppContext from './app/models/context.js';
295
297
  const db = new AppContext();
296
298
 
297
299
  // Create (Active Record style)
@@ -731,7 +733,7 @@ masterrecord update-database-all # Apply all pending migrations
731
733
 
732
734
  ```javascript
733
735
  // db/migrations/20250111_143052_CreateUser.js
734
- const masterrecord = require('masterrecord');
736
+ import masterrecord from 'masterrecord';
735
737
 
736
738
  class CreateUser extends masterrecord.schema {
737
739
  constructor(context) {
@@ -740,9 +742,9 @@ class CreateUser extends masterrecord.schema {
740
742
 
741
743
  // IMPORTANT: Migrations must be async
742
744
  async up(table) {
743
- this.init(table);
745
+ await this.init(table);
744
746
 
745
- // Create table (requires await)
747
+ // Create table
746
748
  await this.createTable(table.User);
747
749
 
748
750
  // Seed initial data
@@ -754,14 +756,14 @@ class CreateUser extends masterrecord.schema {
754
756
  }
755
757
 
756
758
  async down(table) {
757
- this.init(table);
759
+ await this.init(table);
758
760
 
759
761
  // Rollback
760
- this.dropTable(table.User);
762
+ await this.dropTable(table.User);
761
763
  }
762
764
  }
763
765
 
764
- module.exports = CreateUser;
766
+ export default CreateUser;
765
767
  ```
766
768
 
767
769
  ### Migration Operations
@@ -818,28 +820,34 @@ class MyMigration extends masterrecord.schema {
818
820
  ### Seed Data
819
821
 
820
822
  ```javascript
821
- module.exports = {
822
- up: function(table, schema) {
823
- schema.createTable(table.User);
823
+ import masterrecord from 'masterrecord';
824
+
825
+ class SeedUsers extends masterrecord.schema {
826
+ async up(table) {
827
+ await this.init(table);
828
+ await this.createTable(table.User);
824
829
 
825
830
  // Single record
826
- schema.seed('User', {
831
+ this.seed('User', {
827
832
  name: 'Admin',
828
833
  email: 'admin@example.com'
829
834
  });
830
835
 
831
836
  // Multiple records (efficient bulk insert)
832
- schema.bulkSeed('User', [
837
+ this.bulkSeed('User', [
833
838
  { name: 'Alice', email: 'alice@example.com', age: 25 },
834
839
  { name: 'Bob', email: 'bob@example.com', age: 30 },
835
840
  { name: 'Charlie', email: 'charlie@example.com', age: 35 }
836
841
  ]);
837
- },
842
+ }
838
843
 
839
- down: function(table, schema) {
840
- schema.dropTable(table.User);
844
+ async down(table) {
845
+ await this.init(table);
846
+ await this.dropTable(table.User);
841
847
  }
842
- };
848
+ }
849
+
850
+ export default SeedUsers;
843
851
  ```
844
852
 
845
853
  **Seed data is idempotent** - re-running migrations won't create duplicates:
@@ -913,7 +921,7 @@ class AppContext extends context {
913
921
  ### Transactions (PostgreSQL)
914
922
 
915
923
  ```javascript
916
- const { PostgresSyncConnect } = require('masterrecord/postgresSyncConnect');
924
+ import PostgresSyncConnect from 'masterrecord/postgresSyncConnect';
917
925
 
918
926
  const connection = new PostgresSyncConnect();
919
927
  await connection.connect(config);
@@ -1082,8 +1090,8 @@ db.setQueryCacheEnabled(true);
1082
1090
  For multi-process or clustered deployments, use Redis:
1083
1091
 
1084
1092
  ```javascript
1085
- const redis = require('redis');
1086
- const RedisQueryCache = require('masterrecord/Cache/RedisQueryCache');
1093
+ import { createClient } from 'redis';
1094
+ import RedisQueryCache from 'masterrecord/Cache/RedisQueryCache';
1087
1095
 
1088
1096
  class AppContext extends context {
1089
1097
  constructor() {
@@ -1689,7 +1697,7 @@ Add lifecycle hooks to your entity definitions to execute logic before/after dat
1689
1697
  **Example:**
1690
1698
 
1691
1699
  ```javascript
1692
- const bcrypt = require('bcrypt');
1700
+ import bcrypt from 'bcrypt';
1693
1701
 
1694
1702
  class User {
1695
1703
  constructor() {
@@ -2512,7 +2520,7 @@ for (const record of factoryRecords) {
2512
2520
 
2513
2521
  **Faker Integration (Optional):**
2514
2522
  ```javascript
2515
- const { faker } = require('@faker-js/faker');
2523
+ import { faker } from '@faker-js/faker';
2516
2524
 
2517
2525
  this.dbset(User).seedFactory(100, i => ({
2518
2526
  name: faker.person.fullName(),
@@ -3027,7 +3035,7 @@ schema.bulkSeed(tableName, dataArray)
3027
3035
  ### Complete CRUD Example
3028
3036
 
3029
3037
  ```javascript
3030
- const AppContext = require('./app/models/context');
3038
+ import AppContext from './app/models/context.js';
3031
3039
 
3032
3040
  async function demo() {
3033
3041
  const db = new AppContext();
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Verifies the custom error classes exported from context.js
3
+ * behave correctly (inheritance, name, context metadata).
4
+ */
5
+
6
+ import { test } from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import {
9
+ ContextError,
10
+ ConfigurationError,
11
+ DatabaseConnectionError,
12
+ EntityValidationError,
13
+ } from '../context.js';
14
+
15
+ test('ContextError is a subclass of Error', () => {
16
+ const err = new ContextError('test', { foo: 'bar' });
17
+ assert.ok(err instanceof Error);
18
+ assert.ok(err instanceof ContextError);
19
+ assert.equal(err.name, 'ContextError');
20
+ assert.equal(err.message, 'test');
21
+ assert.deepEqual(err.context, { foo: 'bar' });
22
+ });
23
+
24
+ test('ConfigurationError inherits from ContextError', () => {
25
+ const err = new ConfigurationError('bad config');
26
+ assert.ok(err instanceof ContextError);
27
+ assert.ok(err instanceof ConfigurationError);
28
+ assert.equal(err.name, 'ConfigurationError');
29
+ });
30
+
31
+ test('DatabaseConnectionError attaches dbType to context', () => {
32
+ const err = new DatabaseConnectionError('cannot connect', 'mysql', { host: 'localhost' });
33
+ assert.ok(err instanceof ContextError);
34
+ assert.equal(err.context.dbType, 'mysql');
35
+ assert.equal(err.context.host, 'localhost');
36
+ });
37
+
38
+ test('EntityValidationError attaches entityName to context', () => {
39
+ const err = new EntityValidationError('invalid', 'User', { field: 'email' });
40
+ assert.ok(err instanceof ContextError);
41
+ assert.equal(err.context.entityName, 'User');
42
+ assert.equal(err.context.field, 'email');
43
+ });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Verifies chained .where() calls are actually applied to COUNT queries,
3
+ * not silently dropped. Related to the "missing AND clause" family of bugs.
4
+ */
5
+
6
+ import { test } from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ process.env.master = 'countchained';
13
+
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ const fixturesDir = path.join(__dirname, 'fixtures', 'count-chained-where');
16
+ const envDir = path.join(fixturesDir, 'config', 'environments');
17
+ const dbDir = path.join(fixturesDir, 'db');
18
+ const dbFile = path.join(dbDir, 'countctx.sqlite');
19
+
20
+ fs.mkdirSync(envDir, { recursive: true });
21
+ fs.mkdirSync(dbDir, { recursive: true });
22
+ if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
23
+
24
+ fs.writeFileSync(
25
+ path.join(envDir, 'env.countchained.json'),
26
+ JSON.stringify({
27
+ CountCtx: {
28
+ type: 'better-sqlite3',
29
+ connection: dbDir + path.sep,
30
+ },
31
+ })
32
+ );
33
+
34
+ const { default: context } = await import('../context.js');
35
+ const { default: MySQLEngine } = await import('../mySQLEngine.js');
36
+ const { default: PostgresEngine } = await import('../postgresEngine.js');
37
+
38
+ class Lead {
39
+ id(db) { db.integer().primary().auto(); }
40
+ stage(db) { db.string(); }
41
+ score(db) { db.integer(); }
42
+ }
43
+
44
+ class CountCtx extends context {
45
+ constructor() {
46
+ super();
47
+ this.env(envDir);
48
+ this.dbset(Lead);
49
+ }
50
+ }
51
+
52
+ // Seed 5 rows: 3 stage="New", 2 stage="Won". Of the 3 New, 2 have score > 10.
53
+ {
54
+ const ctx = new CountCtx();
55
+ ctx._SQLEngine.db.exec(`
56
+ CREATE TABLE IF NOT EXISTS Lead (
57
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
58
+ stage TEXT,
59
+ score INTEGER
60
+ );
61
+ `);
62
+ const insert = ctx._SQLEngine.db.prepare('INSERT INTO Lead (stage, score) VALUES (?, ?)');
63
+ insert.run('New', 5);
64
+ insert.run('New', 15);
65
+ insert.run('New', 20);
66
+ insert.run('Won', 30);
67
+ insert.run('Won', 40);
68
+ await ctx.close();
69
+ }
70
+
71
+ test('SQLite: chained .where() before .count() applies both conditions', async () => {
72
+ const ctx = new CountCtx();
73
+ // stage == 'New' AND score > 10 → rows 2 and 3 → count 2
74
+ const n = await ctx.Lead
75
+ .where('l => l.stage == $$', 'New')
76
+ .where('l => l.score > $$', 10)
77
+ .count();
78
+ assert.equal(n, 2, 'only Leads with stage=New AND score>10 counted');
79
+ await ctx.close();
80
+ });
81
+
82
+ test('SQLite: single .where() before .count() still works (sanity)', async () => {
83
+ const ctx = new CountCtx();
84
+ const n = await ctx.Lead.where('l => l.stage == $$', 'New').count();
85
+ assert.equal(n, 3);
86
+ await ctx.close();
87
+ });
88
+
89
+ function buildScript(chainFn) {
90
+ const ctx = new CountCtx();
91
+ const builder = chainFn(ctx.Lead);
92
+ const script = builder.__queryObject.script;
93
+ const entity = ctx.Lead.__entity;
94
+ ctx.close();
95
+ return { script, entity };
96
+ }
97
+
98
+ // Smoke test MySQL/Postgres engines' count query path — we can't run them
99
+ // against a real DB, but we can verify the generated SQL contains both
100
+ // predicate columns when chained .where() is used.
101
+ //
102
+ // NOTE: MySQL's getCount and Postgres's getCount build the COUNT SQL inline
103
+ // (they don't delegate to buildQuery), so these are separate code paths that
104
+ // also need to emit the AND clause.
105
+ test('MySQL engine should emit chained-AND predicate columns in count SQL', async () => {
106
+ const { script, entity } = buildScript((Lead) =>
107
+ Lead.where('l => l.stage == $$', 'New').where('l => l.score > $$', 10)
108
+ );
109
+ script.count = 'none';
110
+ const engine = new MySQLEngine();
111
+ // Emulate what getCount now builds inline.
112
+ const sql = `SELECT ${engine.buildCount(script, entity)} ${engine.buildFrom(script, entity)} ${engine.buildWhere(script, entity)} ${engine.buildAnd(script, entity)}`;
113
+ assert.match(sql, /\bstage\b/i, 'first predicate column present');
114
+ assert.match(sql, /\bscore\b/i, 'second predicate column present');
115
+ assert.match(sql, /^SELECT COUNT\(\*\)/, 'starts with SELECT COUNT(*)');
116
+ });
117
+
118
+ test('MySQL buildCount: SELECT COUNT(*) when no column specified', () => {
119
+ const { script, entity } = buildScript((Lead) =>
120
+ Lead.where('l => l.stage == $$', 'New')
121
+ );
122
+ script.count = 'none';
123
+ const engine = new MySQLEngine();
124
+ assert.equal(engine.buildCount(script, entity), 'COUNT(*)');
125
+ });
126
+
127
+ test('Postgres engine COUNT path should include chained-AND predicate columns', () => {
128
+ const { script, entity } = buildScript((Lead) =>
129
+ Lead.where('l => l.stage == $$', 'New').where('l => l.score > $$', 10)
130
+ );
131
+ script.count = 'none';
132
+ const engine = new PostgresEngine();
133
+ const sql = `SELECT ${engine.buildCount(script, entity)} ${engine.buildFrom(script, entity)} ${engine.buildWhere(script, entity)} ${engine.buildAnd(script, entity)}`;
134
+ assert.match(sql, /\bstage\b/i);
135
+ assert.match(sql, /\bscore\b/i, 'second .where() predicate must survive into the COUNT SQL');
136
+ });
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Verifies that every public entry point in the exports map loads cleanly
3
+ * as ESM and produces the expected default export shape.
4
+ */
5
+
6
+ import { test } from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+
9
+ test('MasterRecord.js default export has context and schema', async () => {
10
+ const mr = (await import('../MasterRecord.js')).default;
11
+ assert.ok(mr, 'default export exists');
12
+ assert.ok(mr.context, 'has context');
13
+ assert.ok(mr.schema, 'has schema');
14
+ });
15
+
16
+ test('context.js exports default class and named error classes', async () => {
17
+ const mod = await import('../context.js');
18
+ assert.equal(typeof mod.default, 'function', 'default is a class');
19
+ assert.equal(typeof mod.ContextError, 'function');
20
+ assert.equal(typeof mod.ConfigurationError, 'function');
21
+ assert.equal(typeof mod.DatabaseConnectionError, 'function');
22
+ assert.equal(typeof mod.EntityValidationError, 'function');
23
+ assert.equal(typeof mod._poolKey, 'function');
24
+ });
25
+
26
+ test('Tools.js loads as default export', async () => {
27
+ const Tools = (await import('../Tools.js')).default;
28
+ assert.equal(typeof Tools, 'function');
29
+ assert.equal(typeof Tools.capitalize, 'function');
30
+ });
31
+
32
+ test('QueryCache loads and instantiates', async () => {
33
+ const QueryCache = (await import('../Cache/QueryCache.js')).default;
34
+ const cache = new QueryCache({ ttl: 1000, maxSize: 10 });
35
+ assert.ok(cache);
36
+ assert.equal(typeof cache.generateKey, 'function');
37
+ });
38
+
39
+ test('Entity/entityModel loads', async () => {
40
+ const EntityModel = (await import('../Entity/entityModel.js')).default;
41
+ const em = new EntityModel('test');
42
+ assert.equal(em.obj.name, 'test');
43
+ });
44
+
45
+ test('Entity/entityModelBuilder loads', async () => {
46
+ const { default: EMB } = await import('../Entity/entityModelBuilder.js');
47
+ assert.equal(typeof EMB, 'function');
48
+ });
49
+
50
+ test('Entity/entityTrackerModel loads', async () => {
51
+ const { default: ETM } = await import('../Entity/entityTrackerModel.js');
52
+ assert.equal(typeof ETM, 'function');
53
+ });
54
+
55
+ test('Entity/fieldTransformer loads', async () => {
56
+ const { default: FT } = await import('../Entity/fieldTransformer.js');
57
+ assert.equal(typeof FT.hasTransformer, 'function');
58
+ });
59
+
60
+ test('QueryLanguage modules load', async () => {
61
+ const qm = (await import('../QueryLanguage/queryMethods.js')).default;
62
+ const qp = (await import('../QueryLanguage/queryParameters.js')).default;
63
+ const qs = (await import('../QueryLanguage/queryScript.js')).default;
64
+ assert.equal(typeof qm, 'function');
65
+ assert.equal(typeof qp, 'function');
66
+ assert.equal(typeof qs, 'function');
67
+ });
68
+
69
+ test('SQL engines load', async () => {
70
+ const { default: SQLiteEngine } = await import('../SQLLiteEngine.js');
71
+ const { default: MySQLEngine } = await import('../mySQLEngine.js');
72
+ const { default: PostgresEngine } = await import('../postgresEngine.js');
73
+ assert.equal(typeof SQLiteEngine, 'function');
74
+ assert.equal(typeof MySQLEngine, 'function');
75
+ assert.equal(typeof PostgresEngine, 'function');
76
+ });
77
+
78
+ test('Connection clients load', async () => {
79
+ const { default: MySQLAsyncClient } = await import('../mySQLConnect.js');
80
+ const { default: PostgresSyncConnect } = await import('../postgresSyncConnect.js');
81
+ assert.equal(typeof MySQLAsyncClient, 'function');
82
+ assert.equal(typeof PostgresSyncConnect, 'function');
83
+ });
84
+
85
+ test('insertManager and deleteManager load', async () => {
86
+ const { default: InsertManager } = await import('../insertManager.js');
87
+ const { default: DeleteManager } = await import('../deleteManager.js');
88
+ assert.equal(typeof InsertManager, 'function');
89
+ assert.equal(typeof DeleteManager, 'function');
90
+ });
91
+
92
+ test('Migrations/schema loads', async () => {
93
+ const { default: schema } = await import('../Migrations/schema.js');
94
+ assert.equal(typeof schema, 'function');
95
+ });
96
+
97
+ test('Migrations/migrations loads', async () => {
98
+ const { default: Migrations } = await import('../Migrations/migrations.js');
99
+ assert.equal(typeof Migrations, 'function');
100
+ });
101
+
102
+ test('Migrations/migrationTemplate loads', async () => {
103
+ const { default: MT } = await import('../Migrations/migrationTemplate.js');
104
+ assert.equal(typeof MT, 'function');
105
+ });
106
+
107
+ test('Migrations/dependencyGraph loads', async () => {
108
+ const { default: DG } = await import('../Migrations/dependencyGraph.js');
109
+ assert.equal(typeof DG, 'function');
110
+ });
@@ -0,0 +1 @@
1
+ {"CountCtx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/count-chained-where/db/"}}