masterrecord 1.28.0 → 1.30.0
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 +84 -0
- package/Migrations/cli.js +53 -58
- package/Migrations/migrationTemplate.js +13 -7
- package/Migrations/migrations.js +7 -2
- package/QueryLanguage/queryMethods.js +27 -21
- package/package.json +2 -2
- package/postgresEngine.js +16 -4
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,89 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.30.0 — the snapshot belongs to authoring, as in EF Core (migrations now replay from empty)
|
|
4
|
+
|
|
5
|
+
**Behaviour change. Read this before upgrading a project with existing migrations.**
|
|
6
|
+
|
|
7
|
+
EF Core writes the model snapshot when a migration is *authored*: `dotnet ef migrations add`
|
|
8
|
+
regenerates `ModelSnapshot`, and `dotnet ef database update` never touches it. That is what
|
|
9
|
+
makes every migration a delta between authored states, and it is why a fresh database can
|
|
10
|
+
replay them in order.
|
|
11
|
+
|
|
12
|
+
masterrecord did the opposite. The snapshot was written by `update-database`,
|
|
13
|
+
`update-database-all`, `-down`, `-restart`, `-target`, so it recorded **applied database
|
|
14
|
+
state**. Any schema created outside migrations — a bootstrap script, a hand-made table, a
|
|
15
|
+
half-applied run — got baked into the snapshot, and the next `add-migration` then generated
|
|
16
|
+
a migration that *assumed* schema no migration creates. Those migrations worked in the
|
|
17
|
+
environment they were authored in and failed on a fresh database. Two `add-migration` calls
|
|
18
|
+
in a row also emitted the same change twice, because nothing advanced the snapshot between
|
|
19
|
+
them.
|
|
20
|
+
|
|
21
|
+
- **`add-migration` now advances the snapshot** (and records `latestMigration`).
|
|
22
|
+
- **No apply-time command writes the snapshot any more.** Applying only writes the history
|
|
23
|
+
table. The snapshot's writers are now exactly EF's: `add-migration`,
|
|
24
|
+
`enable-migrations`, `enable-migrations-all`, `remove-migration`.
|
|
25
|
+
- **`alterColumn` migrations are self-contained.** They emitted `alterColumn(table.X)`,
|
|
26
|
+
resolved against a diff computed at apply time, so they only worked while the snapshot
|
|
27
|
+
lagged. The column definition is now inlined, as `addColumn`/`dropColumn` already did —
|
|
28
|
+
and `down` restores the **old** definition instead of re-applying the new one, which was
|
|
29
|
+
a silent no-op revert.
|
|
30
|
+
- This also removes the snapshot churn at its root: `update-database` and
|
|
31
|
+
`update-database-all` can no longer rewrite each other's snapshots, because neither writes.
|
|
32
|
+
|
|
33
|
+
**Upgrading:** your existing snapshots currently describe applied state, which is the same
|
|
34
|
+
starting point `add-migration` already diffs against — so the next migration you generate is
|
|
35
|
+
unchanged. From then on the snapshot advances at authoring time. If a project has schema that
|
|
36
|
+
no migration creates (a bootstrap script), author catch-up migrations for it and
|
|
37
|
+
`masterrecord baseline <context> --all` against the databases that already have it, then
|
|
38
|
+
delete the bootstrap — otherwise a fresh database still cannot reach the same schema.
|
|
39
|
+
|
|
40
|
+
New tests: `test/snapshot-authoring-semantics.test.js` — the snapshot advances on authoring
|
|
41
|
+
and not on applying, a second `add-migration` with no model change emits nothing, migrations
|
|
42
|
+
replay onto an empty database, and `alterColumn` inlines its definitions.
|
|
43
|
+
|
|
44
|
+
## v1.29.0 — count() returns a number on Postgres; one snapshot shape across every command
|
|
45
|
+
|
|
46
|
+
Both found by running against a live PostgreSQL 16.15 server. Neither was a regression —
|
|
47
|
+
both predate the 1.2x series — but both are real.
|
|
48
|
+
|
|
49
|
+
- **Fix: `count()` was engine-dependent.** Postgres `count(*)` is `bigint`, and
|
|
50
|
+
node-postgres returns `int8` as a **string** so a count past 2^53 cannot silently lose
|
|
51
|
+
precision. Un-cast, `count()` returned `"0"` on Postgres and `0` on SQLite: `n === 0`
|
|
52
|
+
was never true, `n + 1` produced `"01"`, and `>` still worked by coercion — so it failed
|
|
53
|
+
*selectively*, which is the worst kind. Fixed the way EF Core's Npgsql provider fixes
|
|
54
|
+
it — **cast in SQL**, `count(*)::int`, so the driver returns a native integer rather
|
|
55
|
+
than repairing the value in the client. `COUNT` inside `groupBy().aggregate()` is cast
|
|
56
|
+
too; `SUM`/`AVG` are deliberately not, since they can be fractional. (As in EF, whose
|
|
57
|
+
`Count()` is an int32, this overflows past ~2.1 billion rows; EF's answer there is
|
|
58
|
+
`LongCount()`.) `sum`/`avg`/`min`/`max` already coerced correctly — `count()` was the gap.
|
|
59
|
+
- **Fix: the two migration commands wrote different snapshots.** `update-database`
|
|
60
|
+
recorded `latestMigration` but omitted `contextSeedConfig`; `update-database-all` did
|
|
61
|
+
the reverse — so running one after the other rewrote the same files back and forth, and
|
|
62
|
+
the batch command recorded `latestMigration: null` even after applying migrations. All
|
|
63
|
+
commands now build the snapshot through one helper, and `latestMigration` comes from the
|
|
64
|
+
**history table** (what actually applied) rather than the last file on disk, so a
|
|
65
|
+
partially-failed run cannot claim a migration it never ran. Verified on live Postgres:
|
|
66
|
+
`update-database` -> `update-database-all` -> `update-database` now produce byte-identical
|
|
67
|
+
snapshots.
|
|
68
|
+
|
|
69
|
+
New tests: `test/count-returns-number.test.js` (generated SQL per engine + behaviour), plus
|
|
70
|
+
a `count()` type assertion in the live cross-engine suite.
|
|
71
|
+
|
|
72
|
+
## v1.28.1 — the package no longer contradicts its own engine requirement
|
|
73
|
+
|
|
74
|
+
- **Fix:** `package.json` declared `engines.node: ">=20.0.0"` while depending on
|
|
75
|
+
`commander@^15`, which itself requires `>=22.12.0`. Every Node 20 consumer got an
|
|
76
|
+
`EBADENGINE` warning on install, and the promise of Node 20 support was not actually
|
|
77
|
+
backed by the dependency tree. Pinned to `commander@^14.0.3`, whose own requirement is
|
|
78
|
+
`>=20` — matching what masterrecord claims. No API changes: the CLI uses only
|
|
79
|
+
`command/option/action/alias/description/version/parse`, stable across both majors.
|
|
80
|
+
|
|
81
|
+
Also validated in this release cycle, against a live PostgreSQL 16.15 server rather than
|
|
82
|
+
SQLite: `update-database-all` (the production deploy path) applying a migration and being
|
|
83
|
+
a no-op on re-run, `migrations-status`, `update-database-down` (transactional since 1.26.0
|
|
84
|
+
— table dropped and history row removed), correct Postgres column types including
|
|
85
|
+
`boolean` and temporal columns as `TEXT`, and the history table carrying `product_version`.
|
|
86
|
+
|
|
3
87
|
## v1.28.0 — `ensureCreated()` actually works on MySQL/Postgres (found by live testing)
|
|
4
88
|
|
|
5
89
|
The first live run of the cross-engine suite, against a real PostgreSQL 16.15 server,
|
package/Migrations/cli.js
CHANGED
|
@@ -104,6 +104,34 @@ async function __resolveMigrationPlan(contextFileName){
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
// Helper to cleanup context and exit
|
|
107
|
+
/**
|
|
108
|
+
* The snapshot shape EVERY command writes.
|
|
109
|
+
*
|
|
110
|
+
* `update-database` used to record `latestMigration` but not `contextSeedConfig`, while
|
|
111
|
+
* `update-database-all` did the reverse — so running one after the other rewrote the same
|
|
112
|
+
* files back and forth, and the batch command recorded `latestMigration: null` even after
|
|
113
|
+
* applying migrations. `latestMigration` now comes from the history table (what actually
|
|
114
|
+
* applied) rather than the last file on disk, so a partially-failed run cannot claim a
|
|
115
|
+
* migration it never ran.
|
|
116
|
+
*/
|
|
117
|
+
async function __buildSnapshot({ contextInstance, contextAbs, executedLocation, cleanEntities, contextFileName }){
|
|
118
|
+
let latestMigration = null;
|
|
119
|
+
try {
|
|
120
|
+
const applied = await contextInstance.database.getAppliedMigrations();
|
|
121
|
+
latestMigration = applied.length ? applied[applied.length - 1] : null;
|
|
122
|
+
} catch (_) { /* no history table yet — leave null */ }
|
|
123
|
+
return {
|
|
124
|
+
file: contextAbs,
|
|
125
|
+
executedLocation,
|
|
126
|
+
context: contextInstance,
|
|
127
|
+
contextEntities: cleanEntities,
|
|
128
|
+
contextSeedData: contextInstance.__contextSeedData || {},
|
|
129
|
+
contextSeedConfig: contextInstance.__contextSeedConfig || {},
|
|
130
|
+
contextFileName,
|
|
131
|
+
latestMigration,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
107
135
|
async function __cleanupAndExit(contextInstance, exitCode = 0) {
|
|
108
136
|
try {
|
|
109
137
|
if (contextInstance && typeof contextInstance.close === 'function') {
|
|
@@ -367,14 +395,25 @@ program.hook('preAction', () => {
|
|
|
367
395
|
}
|
|
368
396
|
const migrationDate = Date.now();
|
|
369
397
|
const outputFile = `${migBase}/${migrationDate}_${name}_migration.js`
|
|
370
|
-
fs.
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
398
|
+
fs.writeFileSync(outputFile, newEntity, 'utf8');
|
|
399
|
+
console.log(`✓ Migration '${name}' created successfully at ${outputFile}`);
|
|
400
|
+
|
|
401
|
+
// EF semantics: the snapshot advances when a migration is AUTHORED, not when it
|
|
402
|
+
// is applied (`dotnet ef migrations add` regenerates ModelSnapshot; `database
|
|
403
|
+
// update` never touches it). That is what makes each migration a delta between
|
|
404
|
+
// authored states, so a fresh database can replay them in order. It also means
|
|
405
|
+
// two add-migrations in a row no longer emit the same change twice.
|
|
406
|
+
migration.createSnapShot({
|
|
407
|
+
file: contextAbs,
|
|
408
|
+
executedLocation,
|
|
409
|
+
context: contextInstance,
|
|
410
|
+
contextEntities: cleanEntities,
|
|
411
|
+
contextSeedData: seedData,
|
|
412
|
+
contextSeedConfig: seedConfig,
|
|
413
|
+
contextFileName,
|
|
414
|
+
latestMigration: path.basename(outputFile),
|
|
377
415
|
});
|
|
416
|
+
process.exit(0);
|
|
378
417
|
}catch (e){
|
|
379
418
|
console.log("Error - Cannot read or find file ", e);
|
|
380
419
|
process.exit(1);
|
|
@@ -576,17 +615,7 @@ program.hook('preAction', () => {
|
|
|
576
615
|
}
|
|
577
616
|
|
|
578
617
|
console.log(`\n💾 Updating snapshot...`);
|
|
579
|
-
|
|
580
|
-
file : contextAbs,
|
|
581
|
-
executedLocation : executedLocation,
|
|
582
|
-
context : contextInstance,
|
|
583
|
-
contextEntities : cleanEntities,
|
|
584
|
-
contextSeedData: contextInstance.__contextSeedData || {},
|
|
585
|
-
contextFileName: contextFileName,
|
|
586
|
-
latestMigration: mFiles.length ? path.basename(mFiles[mFiles.length - 1]) : null
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
migration.createSnapShot(snap);
|
|
618
|
+
// EF: applying migrations does NOT touch the snapshot — only the history table.
|
|
590
619
|
console.log(`\n✅ Database updated successfully!`);
|
|
591
620
|
|
|
592
621
|
// Final verification for SQLite
|
|
@@ -720,16 +749,8 @@ program.hook('preAction', () => {
|
|
|
720
749
|
}
|
|
721
750
|
|
|
722
751
|
// Update snapshot
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
executedLocation : executedLocation,
|
|
726
|
-
context : contextInstance,
|
|
727
|
-
contextEntities : cleanEntities,
|
|
728
|
-
contextSeedData: contextInstance.__contextSeedData || {},
|
|
729
|
-
contextSeedConfig: contextInstance.__contextSeedConfig || {},
|
|
730
|
-
contextFileName: contextFileName
|
|
731
|
-
}
|
|
732
|
-
migration.createSnapShot(snap);
|
|
752
|
+
// EF: reverting a migration does NOT touch the snapshot either; `migrations remove`
|
|
753
|
+
// is what rolls the authored model back.
|
|
733
754
|
console.log("✓ Database rolled back successfully");
|
|
734
755
|
await __cleanupAndExit(contextInstance, 0);
|
|
735
756
|
|
|
@@ -818,15 +839,7 @@ program.hook('preAction', () => {
|
|
|
818
839
|
await newMigrationProjectInstance.up(tableObj);
|
|
819
840
|
if (typeof newMigrationProjectInstance.finalize === 'function') await newMigrationProjectInstance.finalize();
|
|
820
841
|
}
|
|
821
|
-
|
|
822
|
-
file : contextAbs,
|
|
823
|
-
executedLocation : executedLocation,
|
|
824
|
-
context : contextInstance,
|
|
825
|
-
contextEntities : cleanEntities,
|
|
826
|
-
contextFileName: contextFileName
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
migration.createSnapShot(snap);
|
|
842
|
+
// EF: applying migrations never rewrites the snapshot (see add-migration).
|
|
830
843
|
console.log("✓ Database restarted and updated successfully");
|
|
831
844
|
await __cleanupAndExit(contextInstance, 0);
|
|
832
845
|
|
|
@@ -1126,17 +1139,7 @@ program.hook('preAction', () => {
|
|
|
1126
1139
|
}
|
|
1127
1140
|
}
|
|
1128
1141
|
|
|
1129
|
-
//
|
|
1130
|
-
const snap = {
|
|
1131
|
-
file : contextAbs,
|
|
1132
|
-
executedLocation : executedLocation,
|
|
1133
|
-
context : contextInstance,
|
|
1134
|
-
contextEntities : cleanEntities,
|
|
1135
|
-
contextSeedData: contextInstance.__contextSeedData || {},
|
|
1136
|
-
contextSeedConfig: contextInstance.__contextSeedConfig || {},
|
|
1137
|
-
contextFileName: path.basename(snapshotFile).replace('_contextSnapShot.json','')
|
|
1138
|
-
}
|
|
1139
|
-
migration.createSnapShot(snap);
|
|
1142
|
+
// EF: applying/reverting never rewrites the snapshot (see add-migration).
|
|
1140
1143
|
console.log("✓ Database rolled back to target migration successfully");
|
|
1141
1144
|
await __cleanupAndExit(contextInstance, 0);
|
|
1142
1145
|
|
|
@@ -1370,16 +1373,7 @@ program.hook('preAction', () => {
|
|
|
1370
1373
|
console.log(`✓ ${entry.ctxName}: applied ${appliedCount} migration(s)`);
|
|
1371
1374
|
}
|
|
1372
1375
|
// Snapshot only a context that fully applied without error.
|
|
1373
|
-
|
|
1374
|
-
file : entry.contextAbs,
|
|
1375
|
-
executedLocation : executedLocation,
|
|
1376
|
-
context : contextInstance,
|
|
1377
|
-
contextEntities : cleanEntities,
|
|
1378
|
-
contextSeedData: contextInstance.__contextSeedData || {},
|
|
1379
|
-
contextSeedConfig: contextInstance.__contextSeedConfig || {},
|
|
1380
|
-
contextFileName: entry.ctxName
|
|
1381
|
-
}
|
|
1382
|
-
migration.createSnapShot(snap);
|
|
1376
|
+
// EF: applying migrations does NOT touch the snapshot — only the history table.
|
|
1383
1377
|
summary.push({ ctxName: entry.ctxName, status: appliedCount === 0 ? 'up to date' : `applied ${appliedCount}`, applied: appliedCount });
|
|
1384
1378
|
}
|
|
1385
1379
|
}catch(errCtx){
|
|
@@ -1461,6 +1455,7 @@ program.hook('preAction', () => {
|
|
|
1461
1455
|
if(seen.has(key)){ continue; }
|
|
1462
1456
|
seen.add(key);
|
|
1463
1457
|
// Create snapshot relative to the context file directory
|
|
1458
|
+
;
|
|
1464
1459
|
const snap = {
|
|
1465
1460
|
file : abs,
|
|
1466
1461
|
executedLocation : executedLocation,
|
|
@@ -37,13 +37,19 @@ export default ${this.name};
|
|
|
37
37
|
`;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Emit alterColumn with the column definition INLINE, the way addColumn and
|
|
42
|
+
* dropColumn already do. It used to emit `alterColumn(table.X)`, which resolved
|
|
43
|
+
* against the diff computed at apply time — so the migration only worked while the
|
|
44
|
+
* snapshot still lagged behind the entities. EF migrations are self-contained; this
|
|
45
|
+
* makes ours self-contained too, and lets `down` revert to the OLD definition
|
|
46
|
+
* instead of re-applying the new one.
|
|
47
|
+
*/
|
|
48
|
+
alterColumn(type, spec){
|
|
49
|
+
if(!spec) { return; }
|
|
50
|
+
const stmt = ` await this.alterColumn(${JSON.stringify(spec)});`;
|
|
51
|
+
if(type === "up"){ this.#up += os.EOL + stmt; }
|
|
52
|
+
else{ this.#down += os.EOL + stmt; }
|
|
47
53
|
}
|
|
48
54
|
createTable(type, name){
|
|
49
55
|
if(type === "up"){
|
package/Migrations/migrations.js
CHANGED
|
@@ -712,8 +712,13 @@ class Migrations{
|
|
|
712
712
|
item.updatedColumns.forEach(function (column, _index) {
|
|
713
713
|
const isEmpty = Object.keys(column).length === 0;
|
|
714
714
|
if(!isEmpty){
|
|
715
|
-
|
|
716
|
-
|
|
715
|
+
const name = column.table && column.table.name;
|
|
716
|
+
if(!name){ return; }
|
|
717
|
+
// up applies the NEW definition, down restores the OLD one (EF's Down
|
|
718
|
+
// reverts the change rather than re-applying it).
|
|
719
|
+
MT.alterColumn("up", self.#columnLiteral(item.new, name, item.name));
|
|
720
|
+
const revert = item.old && item.old[name] ? self.#columnLiteral(item.old, name, item.name) : null;
|
|
721
|
+
MT.alterColumn("down", revert);
|
|
717
722
|
}
|
|
718
723
|
});
|
|
719
724
|
|
|
@@ -5,6 +5,25 @@ import tools from '../Tools.js';
|
|
|
5
5
|
import queryScript from './queryScript.js';
|
|
6
6
|
import FieldTransformer from '../Entity/fieldTransformer.js';
|
|
7
7
|
|
|
8
|
+
/**
|
|
9
|
+
* A row count is always an integer, on every engine.
|
|
10
|
+
*
|
|
11
|
+
* node-postgres returns COUNT(*) (int8) as a STRING so a count beyond 2^53 cannot
|
|
12
|
+
* lose precision, and MySQL can hand back a BigInt. Passing that through made
|
|
13
|
+
* `count()` engine-dependent: `n === 0` was never true on Postgres while working on
|
|
14
|
+
* SQLite, and `n + 1` produced "01" instead of 1 — a bug that only shows up in
|
|
15
|
+
* production. EF's CountAsync returns an int everywhere; so does this.
|
|
16
|
+
* sum()/avg()/min()/max() and groupBy().aggregate() already coerced; count() did not.
|
|
17
|
+
*/
|
|
18
|
+
function toCountNumber(value) {
|
|
19
|
+
if (value === null || value === undefined) return 0;
|
|
20
|
+
if (typeof value === 'number') return value;
|
|
21
|
+
if (typeof value === 'bigint') return Number(value);
|
|
22
|
+
const n = Number(value);
|
|
23
|
+
return Number.isNaN(n) ? value : n;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
8
27
|
// Security: `.take()`/`.skip()` values are interpolated directly into
|
|
9
28
|
// LIMIT/OFFSET (these clauses cannot be parameterized on SQLite/MySQL/Postgres).
|
|
10
29
|
// Pagination values are the single most common place an application forwards
|
|
@@ -704,30 +723,17 @@ class queryMethods{
|
|
|
704
723
|
|
|
705
724
|
await this.__context._ensureReady();
|
|
706
725
|
|
|
707
|
-
if(this.__context.isSQLite){
|
|
708
|
-
// trying to match string select and relace with select Count(*);
|
|
709
|
-
var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
|
|
710
|
-
var val = entityValue[Object.keys(entityValue)[0]];
|
|
711
|
-
this.__reset();
|
|
712
|
-
return val;
|
|
713
|
-
}
|
|
714
|
-
else if(this.__context.isMySQL){
|
|
715
|
-
// trying to match string select and relace with select Count(*);
|
|
716
|
-
var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
|
|
717
|
-
var val = entityValue[Object.keys(entityValue)[0]];
|
|
718
|
-
this.__reset();
|
|
719
|
-
return val;
|
|
720
|
-
}
|
|
721
|
-
else if(this.__context.isPostgres){
|
|
722
|
-
// trying to match string select and relace with select Count(*);
|
|
723
|
-
var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
|
|
724
|
-
var val = entityValue[Object.keys(entityValue)[0]];
|
|
726
|
+
if(!(this.__context.isSQLite || this.__context.isMySQL || this.__context.isPostgres)){
|
|
725
727
|
this.__reset();
|
|
726
|
-
|
|
728
|
+
throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
|
|
727
729
|
}
|
|
728
|
-
|
|
730
|
+
|
|
731
|
+
try {
|
|
732
|
+
const entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
|
|
733
|
+
const raw = (entityValue && typeof entityValue === 'object') ? entityValue[Object.keys(entityValue)[0]] : entityValue;
|
|
734
|
+
return toCountNumber(raw);
|
|
735
|
+
} finally {
|
|
729
736
|
this.__reset();
|
|
730
|
-
throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
|
|
731
737
|
}
|
|
732
738
|
}
|
|
733
739
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.30.0",
|
|
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",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
],
|
|
87
87
|
"dependencies": {
|
|
88
88
|
"better-sqlite3": ">=12.6.2 <14",
|
|
89
|
-
"commander": "^
|
|
89
|
+
"commander": "^14.0.3",
|
|
90
90
|
"deep-object-diff": "^1.1.9",
|
|
91
91
|
"glob": "^13.0.6",
|
|
92
92
|
"mysql2": "^3.23.2",
|
package/postgresEngine.js
CHANGED
|
@@ -162,7 +162,9 @@ class postgresEngine {
|
|
|
162
162
|
const qi = (n) => this._q(n);
|
|
163
163
|
const sel = [
|
|
164
164
|
...groups.map(g => `${alias}.${qi(g.column)} AS ${qi(g.column)}`),
|
|
165
|
-
|
|
165
|
+
// COUNT is bigint on Postgres; cast it to int so the driver returns a number
|
|
166
|
+
// (EF/Npgsql does the same). SUM/AVG must NOT be cast — they can be fractional.
|
|
167
|
+
...aggs.map(a => `${a.fn}(${a.column ? `${alias}.${qi(a.column)}` : '*'})${a.fn === 'COUNT' ? '::int' : ''} AS ${qi(a.alias)}`),
|
|
166
168
|
].join(', ');
|
|
167
169
|
const params = q.parameters ? [...q.parameters.getParams()] : [];
|
|
168
170
|
let sql = `SELECT ${sel} ${this.buildFrom(q, entity)} ${this.buildWhere(q, entity)} ${this.buildAnd(q, entity)} GROUP BY ${groups.map(g => `${alias}.${qi(g.column)}`).join(', ')}`;
|
|
@@ -566,11 +568,21 @@ class postgresEngine {
|
|
|
566
568
|
return cols.join(', ');
|
|
567
569
|
}
|
|
568
570
|
|
|
571
|
+
/**
|
|
572
|
+
* Postgres `count(*)` is bigint (int8), and node-postgres returns int8 as a STRING
|
|
573
|
+
* so a value beyond 2^53 cannot silently lose precision. Un-cast, that made count()
|
|
574
|
+
* engine-dependent — `n === 0` was never true here but was on SQLite.
|
|
575
|
+
*
|
|
576
|
+
* Cast in SQL rather than coercing in JS, which is how EF Core's Npgsql provider
|
|
577
|
+
* translates `Queryable.Count()`: it emits `count(*)::int` so the driver returns a
|
|
578
|
+
* native 32-bit integer. (EF's `Count()` is likewise an int32; it offers
|
|
579
|
+
* `LongCount()` for tables past ~2.1 billion rows, where this cast would overflow.)
|
|
580
|
+
*/
|
|
569
581
|
buildCount(query, entity) {
|
|
570
582
|
const entityStr = this.getEntity(entity.__name, query.entityMap);
|
|
571
583
|
if (query.count === "none") {
|
|
572
584
|
// `alias.*` is not standard Postgres syntax — use COUNT(*) instead.
|
|
573
|
-
return `COUNT(*)`;
|
|
585
|
+
return `COUNT(*)::int`;
|
|
574
586
|
}
|
|
575
587
|
// query.count is a cachedExpr with selectFields when set via `.count(p => p.field)`.
|
|
576
588
|
let field;
|
|
@@ -579,8 +591,8 @@ class postgresEngine {
|
|
|
579
591
|
} else if (typeof query.count === 'string') {
|
|
580
592
|
field = query.count;
|
|
581
593
|
}
|
|
582
|
-
if (!field) return `COUNT(*)`;
|
|
583
|
-
return `COUNT(${entityStr}.${this._q(field)})`;
|
|
594
|
+
if (!field) return `COUNT(*)::int`;
|
|
595
|
+
return `COUNT(${entityStr}.${this._q(field)})::int`;
|
|
584
596
|
}
|
|
585
597
|
|
|
586
598
|
buildFrom(query, entity) {
|