masterrecord 1.28.1 → 1.30.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.
- package/CHANGES.md +102 -0
- package/Migrations/cli.js +41 -66
- package/Migrations/migrationTemplate.js +13 -7
- package/Migrations/migrations.js +7 -2
- package/QueryLanguage/queryMethods.js +27 -21
- package/package.json +1 -1
- package/postgresEngine.js +16 -4
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,107 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.30.1 — `baseline` is scoped to one context, as everything in EF is
|
|
4
|
+
|
|
5
|
+
**Data-corrupting bug.** `baseline <ctx> --all` globbed `**/*_migration.js` from the working
|
|
6
|
+
directory and recorded **every context's migrations into the one target context's history
|
|
7
|
+
table**. In a repo with several contexts that meant a context could end up with 141 history
|
|
8
|
+
rows for 8 real migrations, listing migrations owned by entirely unrelated contexts.
|
|
9
|
+
|
|
10
|
+
This was a divergence from EF, which never searches the filesystem for migrations: EF
|
|
11
|
+
resolves them by *ownership* — `IMigrationsAssembly.Migrations` contains only the migrations
|
|
12
|
+
whose `[DbContext(typeof(T))]` matches the context being operated on, so another context's
|
|
13
|
+
migration is simply not visible. `baseline` now resolves through the context's own snapshot
|
|
14
|
+
and migration folder via `MigrationsAssembly`, the same path every other command already
|
|
15
|
+
used; it was the only command still globbing from the working directory.
|
|
16
|
+
|
|
17
|
+
- `baseline <ctx> --all` records only the migrations that context owns.
|
|
18
|
+
- `baseline <ctx> <name>` resolves the name through `MigrationsAssembly.getMigrationId()`
|
|
19
|
+
(EF's `MigrationsAssemblyExtensions.GetMigrationId`), so a full id, a file name or the
|
|
20
|
+
bare name all work — and a migration the context does not own is refused with the list of
|
|
21
|
+
the ones it does own, instead of being silently written into its history.
|
|
22
|
+
- Removed the unused `__buildSnapshot()` helper, which derived `latestMigration` from the
|
|
23
|
+
history table. 1.30.0 made snapshot writing authoring-only, which orphaned it; with a
|
|
24
|
+
polluted history it could have reported a foreign migration as a context's latest.
|
|
25
|
+
|
|
26
|
+
**Repairing an already-polluted history.** Upgrading stops new pollution but does not remove
|
|
27
|
+
rows already written. For each affected context, delete the history rows naming migrations
|
|
28
|
+
that are not in its own migrations folder, then confirm with `masterrecord migrations-status
|
|
29
|
+
<ctx>` — it reports recorded-but-missing files, which is exactly what the foreign rows look
|
|
30
|
+
like.
|
|
31
|
+
|
|
32
|
+
New tests: `test/baseline-context-scoped.test.js` — a two-context repo proves `--all` records
|
|
33
|
+
only the named context's migrations, that a foreign migration is refused by name and nothing
|
|
34
|
+
is written on failure, and that a baselined migration is not replayed by `update-database`.
|
|
35
|
+
|
|
36
|
+
## v1.30.0 — the snapshot belongs to authoring, as in EF Core (migrations now replay from empty)
|
|
37
|
+
|
|
38
|
+
**Behaviour change. Read this before upgrading a project with existing migrations.**
|
|
39
|
+
|
|
40
|
+
EF Core writes the model snapshot when a migration is *authored*: `dotnet ef migrations add`
|
|
41
|
+
regenerates `ModelSnapshot`, and `dotnet ef database update` never touches it. That is what
|
|
42
|
+
makes every migration a delta between authored states, and it is why a fresh database can
|
|
43
|
+
replay them in order.
|
|
44
|
+
|
|
45
|
+
masterrecord did the opposite. The snapshot was written by `update-database`,
|
|
46
|
+
`update-database-all`, `-down`, `-restart`, `-target`, so it recorded **applied database
|
|
47
|
+
state**. Any schema created outside migrations — a bootstrap script, a hand-made table, a
|
|
48
|
+
half-applied run — got baked into the snapshot, and the next `add-migration` then generated
|
|
49
|
+
a migration that *assumed* schema no migration creates. Those migrations worked in the
|
|
50
|
+
environment they were authored in and failed on a fresh database. Two `add-migration` calls
|
|
51
|
+
in a row also emitted the same change twice, because nothing advanced the snapshot between
|
|
52
|
+
them.
|
|
53
|
+
|
|
54
|
+
- **`add-migration` now advances the snapshot** (and records `latestMigration`).
|
|
55
|
+
- **No apply-time command writes the snapshot any more.** Applying only writes the history
|
|
56
|
+
table. The snapshot's writers are now exactly EF's: `add-migration`,
|
|
57
|
+
`enable-migrations`, `enable-migrations-all`, `remove-migration`.
|
|
58
|
+
- **`alterColumn` migrations are self-contained.** They emitted `alterColumn(table.X)`,
|
|
59
|
+
resolved against a diff computed at apply time, so they only worked while the snapshot
|
|
60
|
+
lagged. The column definition is now inlined, as `addColumn`/`dropColumn` already did —
|
|
61
|
+
and `down` restores the **old** definition instead of re-applying the new one, which was
|
|
62
|
+
a silent no-op revert.
|
|
63
|
+
- This also removes the snapshot churn at its root: `update-database` and
|
|
64
|
+
`update-database-all` can no longer rewrite each other's snapshots, because neither writes.
|
|
65
|
+
|
|
66
|
+
**Upgrading:** your existing snapshots currently describe applied state, which is the same
|
|
67
|
+
starting point `add-migration` already diffs against — so the next migration you generate is
|
|
68
|
+
unchanged. From then on the snapshot advances at authoring time. If a project has schema that
|
|
69
|
+
no migration creates (a bootstrap script), author catch-up migrations for it and
|
|
70
|
+
`masterrecord baseline <context> --all` against the databases that already have it, then
|
|
71
|
+
delete the bootstrap — otherwise a fresh database still cannot reach the same schema.
|
|
72
|
+
|
|
73
|
+
New tests: `test/snapshot-authoring-semantics.test.js` — the snapshot advances on authoring
|
|
74
|
+
and not on applying, a second `add-migration` with no model change emits nothing, migrations
|
|
75
|
+
replay onto an empty database, and `alterColumn` inlines its definitions.
|
|
76
|
+
|
|
77
|
+
## v1.29.0 — count() returns a number on Postgres; one snapshot shape across every command
|
|
78
|
+
|
|
79
|
+
Both found by running against a live PostgreSQL 16.15 server. Neither was a regression —
|
|
80
|
+
both predate the 1.2x series — but both are real.
|
|
81
|
+
|
|
82
|
+
- **Fix: `count()` was engine-dependent.** Postgres `count(*)` is `bigint`, and
|
|
83
|
+
node-postgres returns `int8` as a **string** so a count past 2^53 cannot silently lose
|
|
84
|
+
precision. Un-cast, `count()` returned `"0"` on Postgres and `0` on SQLite: `n === 0`
|
|
85
|
+
was never true, `n + 1` produced `"01"`, and `>` still worked by coercion — so it failed
|
|
86
|
+
*selectively*, which is the worst kind. Fixed the way EF Core's Npgsql provider fixes
|
|
87
|
+
it — **cast in SQL**, `count(*)::int`, so the driver returns a native integer rather
|
|
88
|
+
than repairing the value in the client. `COUNT` inside `groupBy().aggregate()` is cast
|
|
89
|
+
too; `SUM`/`AVG` are deliberately not, since they can be fractional. (As in EF, whose
|
|
90
|
+
`Count()` is an int32, this overflows past ~2.1 billion rows; EF's answer there is
|
|
91
|
+
`LongCount()`.) `sum`/`avg`/`min`/`max` already coerced correctly — `count()` was the gap.
|
|
92
|
+
- **Fix: the two migration commands wrote different snapshots.** `update-database`
|
|
93
|
+
recorded `latestMigration` but omitted `contextSeedConfig`; `update-database-all` did
|
|
94
|
+
the reverse — so running one after the other rewrote the same files back and forth, and
|
|
95
|
+
the batch command recorded `latestMigration: null` even after applying migrations. All
|
|
96
|
+
commands now build the snapshot through one helper, and `latestMigration` comes from the
|
|
97
|
+
**history table** (what actually applied) rather than the last file on disk, so a
|
|
98
|
+
partially-failed run cannot claim a migration it never ran. Verified on live Postgres:
|
|
99
|
+
`update-database` -> `update-database-all` -> `update-database` now produce byte-identical
|
|
100
|
+
snapshots.
|
|
101
|
+
|
|
102
|
+
New tests: `test/count-returns-number.test.js` (generated SQL per engine + behaviour), plus
|
|
103
|
+
a `count()` type assertion in the live cross-engine suite.
|
|
104
|
+
|
|
3
105
|
## v1.28.1 — the package no longer contradicts its own engine requirement
|
|
4
106
|
|
|
5
107
|
- **Fix:** `package.json` declared `engines.node: ">=20.0.0"` while depending on
|
package/Migrations/cli.js
CHANGED
|
@@ -367,14 +367,25 @@ program.hook('preAction', () => {
|
|
|
367
367
|
}
|
|
368
368
|
const migrationDate = Date.now();
|
|
369
369
|
const outputFile = `${migBase}/${migrationDate}_${name}_migration.js`
|
|
370
|
-
fs.
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
370
|
+
fs.writeFileSync(outputFile, newEntity, 'utf8');
|
|
371
|
+
console.log(`✓ Migration '${name}' created successfully at ${outputFile}`);
|
|
372
|
+
|
|
373
|
+
// EF semantics: the snapshot advances when a migration is AUTHORED, not when it
|
|
374
|
+
// is applied (`dotnet ef migrations add` regenerates ModelSnapshot; `database
|
|
375
|
+
// update` never touches it). That is what makes each migration a delta between
|
|
376
|
+
// authored states, so a fresh database can replay them in order. It also means
|
|
377
|
+
// two add-migrations in a row no longer emit the same change twice.
|
|
378
|
+
migration.createSnapShot({
|
|
379
|
+
file: contextAbs,
|
|
380
|
+
executedLocation,
|
|
381
|
+
context: contextInstance,
|
|
382
|
+
contextEntities: cleanEntities,
|
|
383
|
+
contextSeedData: seedData,
|
|
384
|
+
contextSeedConfig: seedConfig,
|
|
385
|
+
contextFileName,
|
|
386
|
+
latestMigration: path.basename(outputFile),
|
|
377
387
|
});
|
|
388
|
+
process.exit(0);
|
|
378
389
|
}catch (e){
|
|
379
390
|
console.log("Error - Cannot read or find file ", e);
|
|
380
391
|
process.exit(1);
|
|
@@ -576,17 +587,7 @@ program.hook('preAction', () => {
|
|
|
576
587
|
}
|
|
577
588
|
|
|
578
589
|
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);
|
|
590
|
+
// EF: applying migrations does NOT touch the snapshot — only the history table.
|
|
590
591
|
console.log(`\n✅ Database updated successfully!`);
|
|
591
592
|
|
|
592
593
|
// Final verification for SQLite
|
|
@@ -720,16 +721,8 @@ program.hook('preAction', () => {
|
|
|
720
721
|
}
|
|
721
722
|
|
|
722
723
|
// 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);
|
|
724
|
+
// EF: reverting a migration does NOT touch the snapshot either; `migrations remove`
|
|
725
|
+
// is what rolls the authored model back.
|
|
733
726
|
console.log("✓ Database rolled back successfully");
|
|
734
727
|
await __cleanupAndExit(contextInstance, 0);
|
|
735
728
|
|
|
@@ -818,15 +811,7 @@ program.hook('preAction', () => {
|
|
|
818
811
|
await newMigrationProjectInstance.up(tableObj);
|
|
819
812
|
if (typeof newMigrationProjectInstance.finalize === 'function') await newMigrationProjectInstance.finalize();
|
|
820
813
|
}
|
|
821
|
-
|
|
822
|
-
file : contextAbs,
|
|
823
|
-
executedLocation : executedLocation,
|
|
824
|
-
context : contextInstance,
|
|
825
|
-
contextEntities : cleanEntities,
|
|
826
|
-
contextFileName: contextFileName
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
migration.createSnapShot(snap);
|
|
814
|
+
// EF: applying migrations never rewrites the snapshot (see add-migration).
|
|
830
815
|
console.log("✓ Database restarted and updated successfully");
|
|
831
816
|
await __cleanupAndExit(contextInstance, 0);
|
|
832
817
|
|
|
@@ -1126,17 +1111,7 @@ program.hook('preAction', () => {
|
|
|
1126
1111
|
}
|
|
1127
1112
|
}
|
|
1128
1113
|
|
|
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);
|
|
1114
|
+
// EF: applying/reverting never rewrites the snapshot (see add-migration).
|
|
1140
1115
|
console.log("✓ Database rolled back to target migration successfully");
|
|
1141
1116
|
await __cleanupAndExit(contextInstance, 0);
|
|
1142
1117
|
|
|
@@ -1370,16 +1345,7 @@ program.hook('preAction', () => {
|
|
|
1370
1345
|
console.log(`✓ ${entry.ctxName}: applied ${appliedCount} migration(s)`);
|
|
1371
1346
|
}
|
|
1372
1347
|
// 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);
|
|
1348
|
+
// EF: applying migrations does NOT touch the snapshot — only the history table.
|
|
1383
1349
|
summary.push({ ctxName: entry.ctxName, status: appliedCount === 0 ? 'up to date' : `applied ${appliedCount}`, applied: appliedCount });
|
|
1384
1350
|
}
|
|
1385
1351
|
}catch(errCtx){
|
|
@@ -1461,6 +1427,7 @@ program.hook('preAction', () => {
|
|
|
1461
1427
|
if(seen.has(key)){ continue; }
|
|
1462
1428
|
seen.add(key);
|
|
1463
1429
|
// Create snapshot relative to the context file directory
|
|
1430
|
+
;
|
|
1464
1431
|
const snap = {
|
|
1465
1432
|
file : abs,
|
|
1466
1433
|
executedLocation : executedLocation,
|
|
@@ -1571,24 +1538,32 @@ program
|
|
|
1571
1538
|
.description('Record a migration as applied WITHOUT running it — brings a database that already has the schema under migration control (EF: insert the history row). Use --all for every migration on disk.')
|
|
1572
1539
|
.option('-a, --all', 'baseline every migration file found, not just one')
|
|
1573
1540
|
.action(async function(contextFileName, migrationName, options){
|
|
1574
|
-
const executedLocation = process.cwd();
|
|
1575
1541
|
let ctx = null;
|
|
1576
1542
|
try {
|
|
1577
1543
|
if (!migrationName && !options.all) {
|
|
1578
1544
|
console.error('❌ baseline needs a migration name, or --all.');
|
|
1579
1545
|
process.exit(1);
|
|
1580
1546
|
}
|
|
1581
|
-
|
|
1582
|
-
|
|
1547
|
+
// EF scopes migrations by OWNERSHIP, never by searching the filesystem:
|
|
1548
|
+
// `IMigrationsAssembly.Migrations` contains only the migrations whose
|
|
1549
|
+
// `[DbContext(typeof(T))]` matches the context being operated on. This used to glob
|
|
1550
|
+
// `**/*_migration.js` from the working directory, so in a repo with several contexts
|
|
1551
|
+
// `--all` recorded EVERY context's migrations into the one target context's history
|
|
1552
|
+
// (141 rows for 8 real migrations). Resolve through the context's own snapshot and
|
|
1553
|
+
// migration folder — the same MigrationsAssembly every other command uses.
|
|
1554
|
+
const plan = await __resolveMigrationPlan(contextFileName);
|
|
1555
|
+
ctx = await instantiateReadyContext(plan.ContextCtor);
|
|
1556
|
+
const migrationsAssembly = new MigrationsAssembly({ files: plan.mFiles });
|
|
1583
1557
|
|
|
1584
1558
|
let ids;
|
|
1585
1559
|
if (options.all) {
|
|
1586
|
-
ids =
|
|
1587
|
-
|
|
1588
|
-
.sort((a, b) => __getMigrationTimestamp(a) - __getMigrationTimestamp(b));
|
|
1589
|
-
if (!ids.length) { console.log('No migration files found.'); await __cleanupAndExit(ctx, 0); return; }
|
|
1560
|
+
ids = migrationsAssembly.migrationIds;
|
|
1561
|
+
if (!ids.length) { console.log(`No migration files found for '${contextFileName}' in ${plan.migBase}.`); await __cleanupAndExit(ctx, 0); return; }
|
|
1590
1562
|
} else {
|
|
1591
|
-
|
|
1563
|
+
// Resolves a full id, a file name or the bare name, and throws listing the
|
|
1564
|
+
// context's known migrations if it owns no such migration (EF:
|
|
1565
|
+
// MigrationsAssemblyExtensions.GetMigrationId).
|
|
1566
|
+
ids = [migrationsAssembly.getMigrationId(path.basename(migrationName))];
|
|
1592
1567
|
}
|
|
1593
1568
|
|
|
1594
1569
|
let recorded = 0;
|
|
@@ -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.1",
|
|
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
|
@@ -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) {
|