@memberjunction/codegen-lib 6.2.0-edge.4 → 6.2.0-edge.6
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/README.md +7 -0
- package/dist/Angular/angular-codegen.d.ts.map +1 -1
- package/dist/Angular/angular-codegen.js +2 -0
- package/dist/Angular/angular-codegen.js.map +1 -1
- package/dist/Config/config.d.ts +162 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +81 -2
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts +205 -6
- package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.js +367 -5
- package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
- package/dist/Database/heal-schema-params.d.ts +7 -0
- package/dist/Database/heal-schema-params.d.ts.map +1 -1
- package/dist/Database/heal-schema-params.js +5 -0
- package/dist/Database/heal-schema-params.js.map +1 -1
- package/dist/Database/manage-metadata.d.ts +290 -7
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +737 -67
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +61 -8
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +238 -48
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts +2 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts.map +1 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +127 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -0
- package/dist/Database/providers/postgresql/metadataSupportObjects.js +200 -8
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +63 -13
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +204 -72
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts +2 -0
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +141 -0
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
- package/dist/Database/sql.d.ts +13 -0
- package/dist/Database/sql.d.ts.map +1 -1
- package/dist/Database/sql.js +39 -8
- package/dist/Database/sql.js.map +1 -1
- package/dist/Database/sql_codegen.d.ts +176 -4
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +676 -37
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +9 -0
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.js +28 -7
- package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.js +18 -2
- package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
- package/dist/Misc/system_integrity.d.ts +48 -0
- package/dist/Misc/system_integrity.d.ts.map +1 -1
- package/dist/Misc/system_integrity.js +151 -75
- package/dist/Misc/system_integrity.js.map +1 -1
- package/dist/runCodeGen.d.ts +35 -3
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +135 -45
- package/dist/runCodeGen.js.map +1 -1
- package/package.json +29 -29
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SQLServerDialect, PostgreSQLDialect } from '@memberjunction/sql-dialect';
|
|
2
|
-
import { CodeGenDatabaseProvider } from './codeGenDatabaseProvider.js';
|
|
2
|
+
import { CodeGenDatabaseProvider, SetBaseViewExclusionsPermitted, BaseViewExclusionsPermitted } from './codeGenDatabaseProvider.js';
|
|
3
3
|
import { AnalyzeQueryForMaterialization, DetectAggregationKeyColumns, DetectAdditiveMeasures, MATERIALIZATION_SURROGATE_COLUMN } from './materializationAnalysis.js';
|
|
4
4
|
import { EvaluateMaterializationDrift } from './materializationDrift.js';
|
|
5
5
|
import { ClassifyQueryParameters, BuildHeldValues } from './materializationParamClassifier.js';
|
|
@@ -10,7 +10,7 @@ import { QueryParameterProcessor } from '@memberjunction/query-processor';
|
|
|
10
10
|
// `ClassFactory.CreateInstance(CodeGenDatabaseProvider, 'sqlserver')` returns nothing
|
|
11
11
|
// and the SS code path silently fails.
|
|
12
12
|
import './providers/sqlserver/SQLServerCodeGenProvider.js';
|
|
13
|
-
import { configInfo,
|
|
13
|
+
import { configInfo, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir, ResolveAdditionalSchemaInfoPath } from '../Config/config.js';
|
|
14
14
|
import { CodeNameFromString, EntityFieldInfo, EntityInfo, ExternalDataSourceReadRouter, ExtractActualDefaultValue, LogError, LogStatus, Metadata, RunQuerySQLFilterManager, SeverityType } from "@memberjunction/core";
|
|
15
15
|
import { MJEntityFieldSchema } from "@memberjunction/core-entities";
|
|
16
16
|
import { logError, LogMessage, logStatus, LogWarning, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
|
|
@@ -65,6 +65,27 @@ export class ManageMetadataBase {
|
|
|
65
65
|
* references to it on this so codegen doesn't throw on a DB lacking the materialization schema. Cached per run.
|
|
66
66
|
*/
|
|
67
67
|
this._materializedResultTableExists = null;
|
|
68
|
+
/**
|
|
69
|
+
* Whether this database's `spDeleteUnneededEntityFields` accepts a `ProtectedFieldNames`
|
|
70
|
+
* parameter. Cached for the run (a routine signature cannot change mid-run).
|
|
71
|
+
*
|
|
72
|
+
* This is the interlock for base-view column exclusions. The prune's orphan test is "does this
|
|
73
|
+
* EntityField have a column in `vwSQLColumnsAndEntityFields`?", and that view resolves columns
|
|
74
|
+
* VIEW-FIRST (`COALESCE(view_object_id, object_id)`) on both dialects. So excluding a physical
|
|
75
|
+
* column from a base view makes its `EntityField` row look orphaned, and the next CodeGen run
|
|
76
|
+
* DELETES it — silently taking out every metadata-mediated read and write of that column.
|
|
77
|
+
*
|
|
78
|
+
* CodeGen therefore refuses to apply an exclusion it cannot protect. The PostgreSQL routine ships
|
|
79
|
+
* with CodeGen (`metadataSupportObjects.ts`) so it always has the parameter; SQL Server's ships in
|
|
80
|
+
* migrations, so on a database whose migration set predates the parameter the answer is false and
|
|
81
|
+
* the exclusion is declined with a message naming the prerequisite. Probing rather than
|
|
82
|
+
* dialect-branching means the SQL Server half activates the moment the migration lands, with no
|
|
83
|
+
* further code change.
|
|
84
|
+
*
|
|
85
|
+
* INFORMATION_SCHEMA.PARAMETERS exists on both platforms. PostgreSQL reports the declared name
|
|
86
|
+
* with its `p_` prefix; SQL Server reports it with a leading `@`; so the comparison strips both.
|
|
87
|
+
*/
|
|
88
|
+
this._pruneSupportsProtectedFieldNames = null;
|
|
68
89
|
/**
|
|
69
90
|
* Per-run cache of the entity NAMES (trimmed + lowercased) that an API-KEY row filter
|
|
70
91
|
* (`APIKeyScope.RowFilterID`) or an API-APPLICATION row ceiling (`APIApplicationScope.RowFilterID`) binds to.
|
|
@@ -525,10 +546,9 @@ export class ManageMetadataBase {
|
|
|
525
546
|
* {@link invalidateSoftPKFKConfigCache} at the start of each run so a rewritten file is picked up.
|
|
526
547
|
*/
|
|
527
548
|
static GetSoftPKFKConfig() {
|
|
528
|
-
// Return cached config if path hasn't changed
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
: '';
|
|
549
|
+
// Return cached config if path hasn't changed. The path resolves against the mj.config
|
|
550
|
+
// file's directory (or the RSU env override), never the process cwd (#5858).
|
|
551
|
+
const configPath = ResolveAdditionalSchemaInfoPath() ?? '';
|
|
532
552
|
if (this._softPKFKConfigCache !== null && this._softPKFKConfigPath === configPath) {
|
|
533
553
|
return this._softPKFKConfigCache;
|
|
534
554
|
}
|
|
@@ -2079,6 +2099,10 @@ export class ManageMetadataBase {
|
|
|
2079
2099
|
return false;
|
|
2080
2100
|
}
|
|
2081
2101
|
}
|
|
2102
|
+
// Settle base-view column exclusions BEFORE anything generates a view. The decision depends on
|
|
2103
|
+
// whether this database's field prune can be told to leave the excluded columns' metadata
|
|
2104
|
+
// alone, which is a database fact and therefore only knowable here.
|
|
2105
|
+
await this.resolveBaseViewExclusionSupport(pool);
|
|
2082
2106
|
// Authored exclude list (sys, staging, …) must be captured BEFORE includeSchemas is
|
|
2083
2107
|
// compiled into excludeSchemas. Heal EXEC statements use that original list plus
|
|
2084
2108
|
// @IncludedSchemaNames — never the sibling snapshot of this machine's database.
|
|
@@ -2157,6 +2181,12 @@ export class ManageMetadataBase {
|
|
|
2157
2181
|
// failure for this entire function
|
|
2158
2182
|
}
|
|
2159
2183
|
logStatus(` > Recompiled base views in ${(new Date().getTime() - start.getTime()) / 1000} seconds`);
|
|
2184
|
+
// Keep pre-6.1 hierarchies working: opt in the self-referencing FKs that already had a Root*
|
|
2185
|
+
// column before the field sync and view regeneration below drop it (#5976).
|
|
2186
|
+
if (!await this.seedLegacyHierarchyConfiguration(pool, excludeSchemas)) {
|
|
2187
|
+
logError(' Error seeding hierarchy configuration for legacy self-referencing foreign keys');
|
|
2188
|
+
bSuccess = false;
|
|
2189
|
+
}
|
|
2160
2190
|
start = new Date();
|
|
2161
2191
|
logStatus(' Managing entity fields...');
|
|
2162
2192
|
// note that we skip Advanced Generation here because we do it again later when the manageSQLScriptsAndExecution occurs in SQLCodeGen class
|
|
@@ -2281,6 +2311,109 @@ export class ManageMetadataBase {
|
|
|
2281
2311
|
await this.checkEntityFieldSequenceIntegrity(pool, excludeSchemas);
|
|
2282
2312
|
return bSuccess;
|
|
2283
2313
|
}
|
|
2314
|
+
/**
|
|
2315
|
+
* One-time upgrade step for #5976. Before 6.1, CodeGen projected a `Root<Field>` column for every
|
|
2316
|
+
* self-referencing foreign key; 6.1 made that opt-in through `Configuration.Hierarchy.IsHierarchy`.
|
|
2317
|
+
* An application schema upgraded without seeding that flag keeps its virtual `Root<Field>`
|
|
2318
|
+
* EntityField while the regenerated view drops the column, and every read of the entity fails.
|
|
2319
|
+
*
|
|
2320
|
+
* This sets `{"Hierarchy":{"IsHierarchy":true}}` (merged into any existing Configuration) on every
|
|
2321
|
+
* non-virtual, non-key self-referencing FK whose Configuration has no `Hierarchy` key, when the
|
|
2322
|
+
* entity still has a virtual `Root<Field>` EntityField or the database still has the field's
|
|
2323
|
+
* `fn<Table><Field>_GetRootID` function. Each seeded field is logged as a warning so the owner can
|
|
2324
|
+
* opt out deliberately. The core schema is skipped: its hierarchy fields are seeded by metadata,
|
|
2325
|
+
* and its baseline-shipped root functions exist for fields that were deliberately left out.
|
|
2326
|
+
*/
|
|
2327
|
+
async seedLegacyHierarchyConfiguration(pool, excludeSchemas) {
|
|
2328
|
+
try {
|
|
2329
|
+
const q = (n) => this.qi(n);
|
|
2330
|
+
const candidateSQL = `SELECT ef.${q('ID')} AS ${q('ID')}, ef.${q('EntityID')} AS ${q('EntityID')}, ef.${q('Name')} AS ${q('Name')},
|
|
2331
|
+
ef.${q('Configuration')} AS ${q('Configuration')}, e.${q('Name')} AS ${q('EntityName')},
|
|
2332
|
+
e.${q('SchemaName')} AS ${q('SchemaName')}, e.${q('BaseTable')} AS ${q('BaseTable')}
|
|
2333
|
+
FROM ${this.qs(MjCoreSchema(), 'EntityField')} ef
|
|
2334
|
+
INNER JOIN ${this.qs(MjCoreSchema(), 'Entity')} e ON e.${q('ID')} = ef.${q('EntityID')}
|
|
2335
|
+
WHERE ef.${q('IsVirtual')} = ${this.boolLit(false)}
|
|
2336
|
+
AND ef.${q('IsPrimaryKey')} = ${this.boolLit(false)}
|
|
2337
|
+
AND ef.${q('RelatedEntityID')} = ef.${q('EntityID')}`;
|
|
2338
|
+
const coreSchema = MjCoreSchema().trim().toLowerCase();
|
|
2339
|
+
const candidates = (await this.runQuery(pool, candidateSQL)).recordset
|
|
2340
|
+
.filter(r => !this.isSchemaExcluded(r.SchemaName, excludeSchemas) && r.SchemaName?.trim().toLowerCase() !== coreSchema);
|
|
2341
|
+
if (candidates.length === 0) {
|
|
2342
|
+
return true;
|
|
2343
|
+
}
|
|
2344
|
+
const rootFieldSQL = `SELECT ${q('EntityID')}, ${q('Name')} FROM ${this.qs(MjCoreSchema(), 'EntityField')}
|
|
2345
|
+
WHERE ${q('IsVirtual')} = ${this.boolLit(true)} AND ${q('Name')} LIKE 'Root%'`;
|
|
2346
|
+
const rootFields = (await this.runQuery(pool, rootFieldSQL)).recordset;
|
|
2347
|
+
const functionSQL = `SELECT ROUTINE_SCHEMA AS "RoutineSchema", ROUTINE_NAME AS "RoutineName"
|
|
2348
|
+
FROM INFORMATION_SCHEMA.ROUTINES
|
|
2349
|
+
WHERE ROUTINE_TYPE = 'FUNCTION' AND LOWER(ROUTINE_NAME) LIKE '%root%id'`;
|
|
2350
|
+
const functions = (await this.runQuery(pool, functionSQL)).recordset;
|
|
2351
|
+
const seeds = this.planLegacyHierarchySeeds(candidates, rootFields, functions);
|
|
2352
|
+
for (const seed of seeds) {
|
|
2353
|
+
const guard = seed.Row.Configuration === null || seed.Row.Configuration.trim().length === 0
|
|
2354
|
+
? `(${q('Configuration')} IS NULL OR ${q('Configuration')} = '')`
|
|
2355
|
+
: `${q('Configuration')} = '${EscapeSQLString(seed.Row.Configuration)}'`;
|
|
2356
|
+
const sql = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
|
|
2357
|
+
SET ${q('Configuration')} = '${EscapeSQLString(seed.Configuration)}'
|
|
2358
|
+
WHERE ${q('ID')} = '${seed.Row.ID}' AND ${guard}`;
|
|
2359
|
+
await this.logSQLAndExecute(pool, sql, `Seed Hierarchy.IsHierarchy on legacy self-referencing FK ${seed.Row.EntityName}.${seed.Row.Name}`);
|
|
2360
|
+
LogWarning(` Seeded Configuration.Hierarchy.IsHierarchy = true on ${seed.Row.EntityName}.${seed.Row.Name} (${seed.Reason}). ` +
|
|
2361
|
+
`This keeps the Root${seed.Row.Name} column it had before 6.1; set IsHierarchy to false to opt out.`);
|
|
2362
|
+
}
|
|
2363
|
+
return true;
|
|
2364
|
+
}
|
|
2365
|
+
catch (e) {
|
|
2366
|
+
logError(` Error seeding legacy hierarchy configuration: ${e instanceof Error ? e.message : String(e)}`);
|
|
2367
|
+
return false;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
* Pure decision step of {@link seedLegacyHierarchyConfiguration}: which candidate fields to seed,
|
|
2372
|
+
* why, and the Configuration JSON to write. Fields whose Configuration already has a `Hierarchy`
|
|
2373
|
+
* key are left alone, as are fields whose Configuration is not valid JSON (with a warning).
|
|
2374
|
+
*/
|
|
2375
|
+
planLegacyHierarchySeeds(candidates, rootFields, functions) {
|
|
2376
|
+
// Function names compare with case and underscores removed, which matches both the
|
|
2377
|
+
// `fn<Table><Field>_GetRootID` form and PostgreSQL's snake_case `fn_<table>_<field>_get_root_id`.
|
|
2378
|
+
const squash = (v) => v.toLowerCase().replace(/_/g, '');
|
|
2379
|
+
const functionKeys = new Set(functions.map(f => `${String(f.RoutineSchema).trim().toLowerCase()}.${squash(String(f.RoutineName))}`));
|
|
2380
|
+
const rootFieldKeys = new Set(rootFields.map(f => `${NormalizeUUID(String(f.EntityID))}|${String(f.Name).toLowerCase()}`));
|
|
2381
|
+
const seeds = [];
|
|
2382
|
+
for (const row of candidates) {
|
|
2383
|
+
let existing = {};
|
|
2384
|
+
const raw = row.Configuration?.trim() ?? '';
|
|
2385
|
+
if (raw.length > 0) {
|
|
2386
|
+
let parsed;
|
|
2387
|
+
try {
|
|
2388
|
+
parsed = JSON.parse(raw);
|
|
2389
|
+
}
|
|
2390
|
+
catch {
|
|
2391
|
+
LogWarning(` Not seeding hierarchy on ${row.EntityName}.${row.Name}: its Configuration is not valid JSON`);
|
|
2392
|
+
continue;
|
|
2393
|
+
}
|
|
2394
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
2395
|
+
LogWarning(` Not seeding hierarchy on ${row.EntityName}.${row.Name}: its Configuration is not a JSON object`);
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2398
|
+
existing = parsed;
|
|
2399
|
+
if ('Hierarchy' in existing) {
|
|
2400
|
+
continue; // an explicit setting, opt-in or opt-out, always wins
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
const hasRootField = rootFieldKeys.has(`${NormalizeUUID(String(row.EntityID))}|root${row.Name.toLowerCase()}`);
|
|
2404
|
+
const functionKey = `${String(row.SchemaName).trim().toLowerCase()}.${squash(`fn${row.BaseTable}${row.Name}GetRootID`)}`;
|
|
2405
|
+
const hasRootFunction = functionKeys.has(functionKey);
|
|
2406
|
+
if (!hasRootField && !hasRootFunction) {
|
|
2407
|
+
continue;
|
|
2408
|
+
}
|
|
2409
|
+
seeds.push({
|
|
2410
|
+
Row: row,
|
|
2411
|
+
Reason: hasRootField ? `virtual Root${row.Name} field present` : `root ID function for ${row.Name} present`,
|
|
2412
|
+
Configuration: JSON.stringify({ ...existing, Hierarchy: { IsHierarchy: true } }),
|
|
2413
|
+
});
|
|
2414
|
+
}
|
|
2415
|
+
return seeds;
|
|
2416
|
+
}
|
|
2284
2417
|
/** @deprecated Use {@link ManageMetadata}. */
|
|
2285
2418
|
async manageMetadata(pool, currentUser) {
|
|
2286
2419
|
return this.ManageMetadata(pool, currentUser);
|
|
@@ -3198,19 +3331,30 @@ export class ManageMetadataBase {
|
|
|
3198
3331
|
* that mirror the parent entity's base table fields (excluding PKs, timestamps, and virtual fields).
|
|
3199
3332
|
* Runs collision detection to prevent child table columns from shadowing parent fields.
|
|
3200
3333
|
*/
|
|
3201
|
-
async manageParentEntityFields(pool) {
|
|
3334
|
+
async manageParentEntityFields(pool, excludeSchemas = []) {
|
|
3202
3335
|
let bSuccess = true;
|
|
3203
|
-
|
|
3336
|
+
const updatedChildNames = [];
|
|
3337
|
+
// `excludeSchemas` is the compiled scope: the authored exclude list plus every schema the
|
|
3338
|
+
// includeSchemas allow-list left out (ApplyIncludeSchemaScope). Only children in scope are
|
|
3339
|
+
// synced. Without this an Open App publisher run processed every IS-A child in the database
|
|
3340
|
+
// and wrote INSERTs for sibling apps' children into its own migration capture (#4879).
|
|
3204
3341
|
const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
|
|
3205
|
-
const
|
|
3342
|
+
const allChildEntities = md.Entities.filter(e => e.IsChildType);
|
|
3343
|
+
const childEntities = allChildEntities.filter(e => !this.isSchemaExcluded(e.SchemaName, excludeSchemas));
|
|
3344
|
+
const outOfScope = allChildEntities.length - childEntities.length;
|
|
3206
3345
|
if (childEntities.length === 0) {
|
|
3346
|
+
if (outOfScope > 0) {
|
|
3347
|
+
logStatus(` Skipping IS-A parent fields: all ${outOfScope} child entit${outOfScope === 1 ? 'y is' : 'ies are'} in excluded schemas`);
|
|
3348
|
+
}
|
|
3207
3349
|
return { success: true, anyUpdates: false };
|
|
3208
3350
|
}
|
|
3209
|
-
logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}...`);
|
|
3351
|
+
logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}${outOfScope > 0 ? ` (${outOfScope} in excluded schemas skipped)` : ''}...`);
|
|
3210
3352
|
for (const childEntity of childEntities) {
|
|
3211
3353
|
try {
|
|
3212
3354
|
const { success, updated } = await this.manageSingleEntityParentFields(pool, childEntity);
|
|
3213
|
-
|
|
3355
|
+
if (updated) {
|
|
3356
|
+
updatedChildNames.push(childEntity.Name);
|
|
3357
|
+
}
|
|
3214
3358
|
if (!success) {
|
|
3215
3359
|
logError(` Error managing IS-A parent fields for ${childEntity.Name}`);
|
|
3216
3360
|
bSuccess = false;
|
|
@@ -3221,7 +3365,27 @@ export class ManageMetadataBase {
|
|
|
3221
3365
|
bSuccess = false;
|
|
3222
3366
|
}
|
|
3223
3367
|
}
|
|
3224
|
-
|
|
3368
|
+
// A child whose virtual EntityField set changed has a different TypeScript surface (entity
|
|
3369
|
+
// subclass, zod schema, GraphQL types). The rows were written directly above, so nothing
|
|
3370
|
+
// else marks the entity — and the file emit only rebuilds schemas holding a new or modified
|
|
3371
|
+
// entity (fileEmit.dirtySchemaOnly). Mark it here or the run reports success and ships a
|
|
3372
|
+
// class that lacks the field the metadata declares, until someone runs `--skipdb` (#5961).
|
|
3373
|
+
if (updatedChildNames.length > 0) {
|
|
3374
|
+
ManageMetadataBase.AddNewEntitiesToModifiedList(updatedChildNames);
|
|
3375
|
+
}
|
|
3376
|
+
return { success: bSuccess, anyUpdates: updatedChildNames.length > 0 };
|
|
3377
|
+
}
|
|
3378
|
+
/**
|
|
3379
|
+
* True when `schemaName` is on the compiled exclude list. Schema names are compared
|
|
3380
|
+
* case-insensitively: SQL Server resolves them that way, and PostgreSQL folds unquoted
|
|
3381
|
+
* identifiers, so the list and the metadata can legitimately differ in case.
|
|
3382
|
+
*/
|
|
3383
|
+
isSchemaExcluded(schemaName, excludeSchemas) {
|
|
3384
|
+
if (!schemaName || excludeSchemas.length === 0) {
|
|
3385
|
+
return false;
|
|
3386
|
+
}
|
|
3387
|
+
const target = schemaName.trim().toLowerCase();
|
|
3388
|
+
return excludeSchemas.some(s => s.trim().toLowerCase() === target);
|
|
3225
3389
|
}
|
|
3226
3390
|
/**
|
|
3227
3391
|
* Creates/updates virtual EntityField records for a single child entity's parent fields.
|
|
@@ -3250,20 +3414,39 @@ export class ManageMetadataBase {
|
|
|
3250
3414
|
// Identifiers are quoted via qi(): __mj.EntityField's columns are mixed-case, and an
|
|
3251
3415
|
// unquoted reference folds to lower case on PostgreSQL — `column "length" does not exist`.
|
|
3252
3416
|
// SQL Server's case-insensitive resolution hid this for as long as IS-A ran only there.
|
|
3253
|
-
const existsResult = await this.runQueryWithParams(pool, `SELECT ${this.qi('ID')}, ${this.qi('IsVirtual')}, ${this.qi('Type')}, ${this.qi('Length')}, ${this.qi('Precision')}, ${this.qi('Scale')}, ${this.qi('AllowsNull')}, ${this.qi('AllowUpdateAPI')}
|
|
3417
|
+
const existsResult = await this.runQueryWithParams(pool, `SELECT ${this.qi('ID')}, ${this.qi('IsVirtual')}, ${this.qi('Type')}, ${this.qi('Length')}, ${this.qi('Precision')}, ${this.qi('Scale')}, ${this.qi('AllowsNull')}, ${this.qi('AllowUpdateAPI')},
|
|
3418
|
+
${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('RelatedEntityDisplayType')},
|
|
3419
|
+
${this.qi('IncludeRelatedEntityNameFieldInBaseView')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
|
|
3254
3420
|
FROM ${this.qs(MjCoreSchema(), 'EntityField')}
|
|
3255
3421
|
WHERE ${this.qi('EntityID')} = @EntityID AND ${this.qi('Name')} = @FieldName`, { 'EntityID': childEntity.ID, 'FieldName': parentField.Name });
|
|
3422
|
+
// The inherited column reaches the child through its view, so there is no FK constraint
|
|
3423
|
+
// on the child table to derive the relationship from. It is copied from the parent's
|
|
3424
|
+
// field instead (#4569), or the generated form renders a plain text input that writes ''
|
|
3425
|
+
// into a uniqueidentifier column.
|
|
3426
|
+
const related = this.inheritedRelatedEntityInfo(parentField);
|
|
3256
3427
|
if (existsResult.recordset.length > 0) {
|
|
3257
3428
|
// Field already exists — update it to ensure it's marked as a virtual IS-A field
|
|
3258
3429
|
const existingRow = existsResult.recordset[0];
|
|
3430
|
+
// AutoUpdateRelatedEntityInfo = 0 pins a hand-set relationship; leave it alone. The
|
|
3431
|
+
// related-name join is forced off either way: an inherited row never gets its own
|
|
3432
|
+
// name-field join in the child's view.
|
|
3433
|
+
const syncRelated = this.isTruthyBit(existingRow.AutoUpdateRelatedEntityInfo ?? true);
|
|
3259
3434
|
const needsUpdate = !existingRow.IsVirtual ||
|
|
3260
3435
|
existingRow.Type?.trim().toLowerCase() !== parentField.Type.trim().toLowerCase() ||
|
|
3261
3436
|
existingRow.Length !== parentField.Length ||
|
|
3262
3437
|
existingRow.Precision !== parentField.Precision ||
|
|
3263
3438
|
existingRow.Scale !== parentField.Scale ||
|
|
3264
3439
|
existingRow.AllowsNull !== parentField.AllowsNull ||
|
|
3265
|
-
!existingRow.AllowUpdateAPI
|
|
3440
|
+
!existingRow.AllowUpdateAPI ||
|
|
3441
|
+
this.isTruthyBit(existingRow.IncludeRelatedEntityNameFieldInBaseView ?? false) ||
|
|
3442
|
+
(syncRelated && this.inheritedRelatedEntityInfoDiffers(existingRow, related));
|
|
3266
3443
|
if (needsUpdate) {
|
|
3444
|
+
const relatedSet = syncRelated
|
|
3445
|
+
? `,
|
|
3446
|
+
${this.qi('RelatedEntityID')}=${related.RelatedEntityID ? `'${related.RelatedEntityID}'` : 'NULL'},
|
|
3447
|
+
${this.qi('RelatedEntityFieldName')}=${this.sqlStringOrNull(related.RelatedEntityFieldName)},
|
|
3448
|
+
${this.qi('RelatedEntityDisplayType')}='${EscapeSQLString(related.RelatedEntityDisplayType)}'`
|
|
3449
|
+
: '';
|
|
3267
3450
|
const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
|
|
3268
3451
|
SET ${this.qi('IsVirtual')}=${this.boolLit(true)},
|
|
3269
3452
|
${this.qi('Type')}='${parentField.Type}',
|
|
@@ -3271,7 +3454,8 @@ export class ManageMetadataBase {
|
|
|
3271
3454
|
${this.qi('Precision')}=${parentField.Precision},
|
|
3272
3455
|
${this.qi('Scale')}=${parentField.Scale},
|
|
3273
3456
|
${this.qi('AllowsNull')}=${this.boolLit(parentField.AllowsNull)},
|
|
3274
|
-
${this.qi('AllowUpdateAPI')}=${this.boolLit(true)}
|
|
3457
|
+
${this.qi('AllowUpdateAPI')}=${this.boolLit(true)},
|
|
3458
|
+
${this.qi('IncludeRelatedEntityNameFieldInBaseView')}=${this.boolLit(false)}${relatedSet}
|
|
3275
3459
|
WHERE ${this.qi('ID')}='${existingRow.ID}'`;
|
|
3276
3460
|
await this.logSQLAndExecute(pool, sqlUpdate, `Update IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
|
|
3277
3461
|
bUpdated = true;
|
|
@@ -3283,18 +3467,31 @@ export class ManageMetadataBase {
|
|
|
3283
3467
|
// Apply-time Sequence (see applyTimeEntityFieldSequenceSQL); reordered by
|
|
3284
3468
|
// updateExistingEntityFieldsFromSchema afterwards.
|
|
3285
3469
|
const q = (n) => this.qi(n);
|
|
3286
|
-
|
|
3470
|
+
// The INSERT is captured into the run's migration SQL and replayed on other hosts, so it
|
|
3471
|
+
// carries the same existence guard as the schema-field inserts in createNewEntityFieldsFromSchema.
|
|
3472
|
+
// Unguarded, a replay on a host where the field already exists (a second app captured on the
|
|
3473
|
+
// same chain, or the owning app shipping the field itself) fails on
|
|
3474
|
+
// UQ_EntityField_EntityID_Name and stops the install (#4879).
|
|
3475
|
+
const conflictCheck = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ${q('ID')} = '${newFieldID}' OR (${q('EntityID')} = '${childEntity.ID}' AND ${q('Name')} = '${parentField.Name}')`;
|
|
3476
|
+
const guard = this.dbProvider.wrapInsertWithConflictGuard(conflictCheck);
|
|
3477
|
+
const sqlInsert = `${guard.prefix}
|
|
3478
|
+
INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
|
|
3287
3479
|
${q('ID')}, ${q('EntityID')}, ${q('Name')}, ${q('Type')}, ${q('AllowsNull')},
|
|
3288
3480
|
${q('Length')}, ${q('Precision')}, ${q('Scale')},
|
|
3289
3481
|
${q('Sequence')}, ${q('IsVirtual')}, ${q('AllowUpdateAPI')},
|
|
3290
3482
|
${q('IsPrimaryKey')}, ${q('IsUnique')},
|
|
3483
|
+
${q('RelatedEntityID')}, ${q('RelatedEntityFieldName')}, ${q('RelatedEntityDisplayType')},
|
|
3484
|
+
${q('IncludeRelatedEntityNameFieldInBaseView')},
|
|
3291
3485
|
${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')})
|
|
3292
3486
|
VALUES (
|
|
3293
3487
|
'${newFieldID}', '${childEntity.ID}', '${parentField.Name}',
|
|
3294
3488
|
'${parentField.Type}', ${this.boolLit(parentField.AllowsNull)},
|
|
3295
3489
|
${parentField.Length}, ${parentField.Precision}, ${parentField.Scale},
|
|
3296
3490
|
${this.applyTimeEntityFieldSequenceSQL(childEntity.ID)}, ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)},
|
|
3297
|
-
${this.
|
|
3491
|
+
${related.RelatedEntityID ? `'${related.RelatedEntityID}'` : 'NULL'}, ${this.sqlStringOrNull(related.RelatedEntityFieldName)}, '${EscapeSQLString(related.RelatedEntityDisplayType)}',
|
|
3492
|
+
${this.boolLit(false)},
|
|
3493
|
+
${this.utcNow()}, ${this.utcNow()})
|
|
3494
|
+
${guard.suffix}`;
|
|
3298
3495
|
await this.logSQLAndExecute(pool, sqlInsert, `Create IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
|
|
3299
3496
|
ManageMetadataBase.registerNewField(childEntity.ID, parentField.Name);
|
|
3300
3497
|
bUpdated = true;
|
|
@@ -3317,6 +3514,35 @@ export class ManageMetadataBase {
|
|
|
3317
3514
|
}
|
|
3318
3515
|
return { success: true, updated: bUpdated };
|
|
3319
3516
|
}
|
|
3517
|
+
/**
|
|
3518
|
+
* The relationship an IS-A inherited field carries, copied from the parent's field (#4569).
|
|
3519
|
+
* RelatedEntityNameFieldMap is left NULL and IncludeRelatedEntityNameFieldInBaseView is written
|
|
3520
|
+
* as 0, so the child's view gains no name-field join for the inherited column.
|
|
3521
|
+
*/
|
|
3522
|
+
inheritedRelatedEntityInfo(parentField) {
|
|
3523
|
+
return {
|
|
3524
|
+
RelatedEntityID: parentField.RelatedEntityID ? parentField.RelatedEntityID : null,
|
|
3525
|
+
RelatedEntityFieldName: parentField.RelatedEntityID && parentField.RelatedEntityFieldName ? parentField.RelatedEntityFieldName : null,
|
|
3526
|
+
RelatedEntityDisplayType: parentField.RelatedEntityDisplayType || 'Search',
|
|
3527
|
+
};
|
|
3528
|
+
}
|
|
3529
|
+
/** True when the stored row's relationship columns differ from what the parent field implies. */
|
|
3530
|
+
inheritedRelatedEntityInfoDiffers(existingRow, related) {
|
|
3531
|
+
const currentID = existingRow.RelatedEntityID ?? null;
|
|
3532
|
+
const idDiffers = (currentID === null) !== (related.RelatedEntityID === null) ||
|
|
3533
|
+
(currentID !== null && related.RelatedEntityID !== null && !UUIDsEqual(currentID, related.RelatedEntityID));
|
|
3534
|
+
return idDiffers ||
|
|
3535
|
+
(existingRow.RelatedEntityFieldName ?? null) !== related.RelatedEntityFieldName ||
|
|
3536
|
+
(existingRow.RelatedEntityDisplayType ?? 'Search') !== related.RelatedEntityDisplayType;
|
|
3537
|
+
}
|
|
3538
|
+
/** Reads a bit column that may come back as boolean, number or string depending on the driver. */
|
|
3539
|
+
isTruthyBit(value) {
|
|
3540
|
+
return value === true || value === 1 || value === '1' || value === 'true';
|
|
3541
|
+
}
|
|
3542
|
+
/** A SQL string literal, or NULL for a null/empty value. */
|
|
3543
|
+
sqlStringOrNull(value) {
|
|
3544
|
+
return value ? `'${EscapeSQLString(value)}'` : 'NULL';
|
|
3545
|
+
}
|
|
3320
3546
|
/**
|
|
3321
3547
|
* Checks if an existing virtual parent field record needs to be updated to match the parent field.
|
|
3322
3548
|
*/
|
|
@@ -3454,15 +3680,100 @@ export class ManageMetadataBase {
|
|
|
3454
3680
|
const relCount = relationshipCountMap.get(parentEntityID) || 0;
|
|
3455
3681
|
const sequence = relCount + 1;
|
|
3456
3682
|
const newEntityRelationshipUUID = this.createNewUUID();
|
|
3683
|
+
// EntityKeyField names the column on the PARENT (the EntityID side) that carries the join
|
|
3684
|
+
// value. It is NULL for an ordinary FK-to-primary-key relationship, where every consumer
|
|
3685
|
+
// correctly falls back to the parent's PK. It is load-bearing whenever the FK points at a
|
|
3686
|
+
// NON-PK column: see resolveRelationshipEntityKeyField.
|
|
3687
|
+
const entityKeyField = this.resolveRelationshipEntityKeyField(f, parentEntity);
|
|
3688
|
+
const keyFieldColumn = entityKeyField ? `, ${this.qi('EntityKeyField')}` : '';
|
|
3689
|
+
const keyFieldValue = entityKeyField ? `, '${entityKeyField.replace(/'/g, "''")}'` : '';
|
|
3457
3690
|
const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newEntityRelationshipUUID}'`;
|
|
3458
|
-
const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
|
|
3459
|
-
VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}', 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
|
|
3691
|
+
const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}${keyFieldColumn}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
|
|
3692
|
+
VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}'${keyFieldValue}, 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
|
|
3460
3693
|
relationshipCountMap.set(parentEntityID, sequence);
|
|
3461
3694
|
return `
|
|
3462
3695
|
/* Create Entity Relationship: ${parentEntity.Name} -> ${e.Name} (One To Many via ${f.Name}) */
|
|
3463
3696
|
${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};
|
|
3464
3697
|
`;
|
|
3465
3698
|
}
|
|
3699
|
+
/**
|
|
3700
|
+
* Resolves the `EntityRelationship.EntityKeyField` value for a discovered FK field, or `null`
|
|
3701
|
+
* when the relationship joins the parent's primary key and the column therefore must stay NULL.
|
|
3702
|
+
*
|
|
3703
|
+
* WHY THIS EXISTS. A foreign key does not have to point at a primary key. `EntityField` records
|
|
3704
|
+
* the referenced column in `RelatedEntityFieldName` — populated for declared FKs by the provider
|
|
3705
|
+
* introspection query and for soft FKs by `applySoftPKFKConfig` — but nothing carried it across
|
|
3706
|
+
* into the relationship row. `EntityRelationshipInfo.EntityKeyField` is the only place a consumer
|
|
3707
|
+
* can learn it, and all three consumers fall back to the parent's first primary key when it is
|
|
3708
|
+
* blank (`entityInfo.ts` BuildRelationshipViewParams, `entity-helpers.ts`,
|
|
3709
|
+
* `DependencyGraphWalker.ts`). So a relationship over a non-PK join column silently queried the
|
|
3710
|
+
* wrong column and returned zero rows for every parent record — measured on an imported schema
|
|
3711
|
+
* whose real keys are external ids: 60 relationships, 0 rows each.
|
|
3712
|
+
*
|
|
3713
|
+
* NULL IS THE CORRECT VALUE FOR AN ORDINARY FK, not merely an acceptable one. The PK fallback is
|
|
3714
|
+
* the documented contract, a stored 'ID' would duplicate it, and emitting the column only when it
|
|
3715
|
+
* differs keeps the generated SQL byte-identical for every FK-to-PK relationship — which is all
|
|
3716
|
+
* of them in core MJ.
|
|
3717
|
+
*
|
|
3718
|
+
* Returns null when: no referenced column was recorded; the referenced column IS the parent's
|
|
3719
|
+
* primary key; or the parent has a composite key (a single-column join cannot address it, and
|
|
3720
|
+
* guessing which component to use would be worse than the existing fallback).
|
|
3721
|
+
*/
|
|
3722
|
+
resolveRelationshipEntityKeyField(f, parentEntity) {
|
|
3723
|
+
const referenced = String(f.RelatedEntityFieldName ?? '').trim();
|
|
3724
|
+
if (referenced.length === 0) {
|
|
3725
|
+
return null;
|
|
3726
|
+
}
|
|
3727
|
+
const pkFields = parentEntity.PrimaryKeys ?? [];
|
|
3728
|
+
if (pkFields.length !== 1) {
|
|
3729
|
+
return null;
|
|
3730
|
+
}
|
|
3731
|
+
if (pkFields[0].Name.trim().toLowerCase() === referenced.toLowerCase()) {
|
|
3732
|
+
return null;
|
|
3733
|
+
}
|
|
3734
|
+
// The column must exist on the parent, or the consumer's `record.Get(EntityKeyField)` would
|
|
3735
|
+
// read undefined and build `WHERE col = undefined`. A referenced column MJ has no field for
|
|
3736
|
+
// is a metadata gap to report, not one to encode into a relationship row.
|
|
3737
|
+
const match = parentEntity.Fields.find(pf => pf.Name.trim().toLowerCase() === referenced.toLowerCase());
|
|
3738
|
+
if (!match) {
|
|
3739
|
+
logError(` > resolveRelationshipEntityKeyField: ${parentEntity.Name} has no field named '${referenced}' (referenced by FK ${f.Name}); leaving EntityKeyField NULL so the primary-key fallback applies.`);
|
|
3740
|
+
return null;
|
|
3741
|
+
}
|
|
3742
|
+
return match.Name.trim();
|
|
3743
|
+
}
|
|
3744
|
+
/**
|
|
3745
|
+
* Emits the UPDATE that brings an existing relationship row's `EntityKeyField` into line with the
|
|
3746
|
+
* schema, or `''` when it already agrees.
|
|
3747
|
+
*
|
|
3748
|
+
* This is the half that actually repairs a live database. A relationship whose
|
|
3749
|
+
* `RelatedEntityJoinField` is already correct takes the "exact match" path and is skipped, so
|
|
3750
|
+
* rows created before `EntityKeyField` was written stay blank forever and keep returning zero
|
|
3751
|
+
* rows. Honours `AutoUpdateFromSchema` exactly as the join-field reassignment below does: a row
|
|
3752
|
+
* an operator has taken ownership of is never touched.
|
|
3753
|
+
*/
|
|
3754
|
+
buildRelationshipEntityKeyFieldHealSQL(r, f, md) {
|
|
3755
|
+
if (!r.AutoUpdateFromSchema) {
|
|
3756
|
+
return '';
|
|
3757
|
+
}
|
|
3758
|
+
const parentEntity = md.Entities.find(e => UUIDsEqual(e.ID, f.RelatedEntityID));
|
|
3759
|
+
if (!parentEntity) {
|
|
3760
|
+
return '';
|
|
3761
|
+
}
|
|
3762
|
+
const desired = this.resolveRelationshipEntityKeyField(f, parentEntity);
|
|
3763
|
+
const current = String(r.EntityKeyField ?? '').trim();
|
|
3764
|
+
if ((desired ?? '') === current) {
|
|
3765
|
+
return '';
|
|
3766
|
+
}
|
|
3767
|
+
const literal = desired === null ? 'NULL' : `'${desired.replace(/'/g, "''")}'`;
|
|
3768
|
+
logStatus(` > Healing EntityRelationship key field: '${current}' -> ${desired ?? 'NULL'} (ID: ${r.ID})`);
|
|
3769
|
+
return `
|
|
3770
|
+
/* Heal EntityRelationship EntityKeyField from '${current}' to ${desired ?? 'NULL'} (non-PK join column) */
|
|
3771
|
+
UPDATE ${this.qs(MjCoreSchema(), 'EntityRelationship')}
|
|
3772
|
+
SET ${this.qi('EntityKeyField')} = ${literal},
|
|
3773
|
+
${this.qi('__mj_UpdatedAt')} = ${this.utcNow()}
|
|
3774
|
+
WHERE ${this.qi('ID')} = '${r.ID}';
|
|
3775
|
+
`;
|
|
3776
|
+
}
|
|
3466
3777
|
/**
|
|
3467
3778
|
* Groups FK fields by their entity pair key (ParentEntityID|ChildEntityID).
|
|
3468
3779
|
* This ensures all FK fields for the same entity pair are processed together,
|
|
@@ -3513,6 +3824,13 @@ export class ManageMetadataBase {
|
|
|
3513
3824
|
let sql = '';
|
|
3514
3825
|
// Build sets for matching
|
|
3515
3826
|
const fkFieldNames = new Set(fkFields.map(f => String(f.Name).trim()));
|
|
3827
|
+
const fkFieldsByName = new Map();
|
|
3828
|
+
for (const f of fkFields) {
|
|
3829
|
+
const key = String(f.Name).trim();
|
|
3830
|
+
if (!fkFieldsByName.has(key)) {
|
|
3831
|
+
fkFieldsByName.set(key, f);
|
|
3832
|
+
}
|
|
3833
|
+
}
|
|
3516
3834
|
const matchedRelationshipIDs = new Set();
|
|
3517
3835
|
const matchedFieldNames = new Set();
|
|
3518
3836
|
// Pass 1: exact matches — relationship already has the correct JoinField
|
|
@@ -3521,6 +3839,13 @@ export class ManageMetadataBase {
|
|
|
3521
3839
|
if (fkFieldNames.has(joinField) && !matchedFieldNames.has(joinField)) {
|
|
3522
3840
|
matchedRelationshipIDs.add(String(r.ID));
|
|
3523
3841
|
matchedFieldNames.add(joinField);
|
|
3842
|
+
// The join field agrees, so nothing below will look at this row again — but
|
|
3843
|
+
// EntityKeyField may still be stale or (for every row written before it was emitted)
|
|
3844
|
+
// blank. That is the state that returns zero rows on a non-PK join, so heal it here.
|
|
3845
|
+
const matchedField = fkFieldsByName.get(joinField);
|
|
3846
|
+
if (matchedField) {
|
|
3847
|
+
sql += this.buildRelationshipEntityKeyFieldHealSQL(r, matchedField, md);
|
|
3848
|
+
}
|
|
3524
3849
|
}
|
|
3525
3850
|
}
|
|
3526
3851
|
// Pass 2: assign unmatched FK fields to unmatched auto-update relationships
|
|
@@ -3541,6 +3866,10 @@ export class ManageMetadataBase {
|
|
|
3541
3866
|
WHERE ${this.qi('ID')} = '${r.ID}';
|
|
3542
3867
|
`;
|
|
3543
3868
|
}
|
|
3869
|
+
// Reassigning the join field can also change which parent column the join addresses, so
|
|
3870
|
+
// the key field has to move with it — including back to NULL when the new FK targets the
|
|
3871
|
+
// parent's primary key.
|
|
3872
|
+
sql += this.buildRelationshipEntityKeyFieldHealSQL(r, f, md);
|
|
3544
3873
|
}
|
|
3545
3874
|
// Pass 3: create new relationships for any remaining unmatched FK fields
|
|
3546
3875
|
const remainingFields = unmatchedFields.slice(unmatchedRelationships.length);
|
|
@@ -3622,6 +3951,9 @@ export class ManageMetadataBase {
|
|
|
3622
3951
|
const sql = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntitiesWithMissingBaseTables')}${this.dbProvider.getEntitiesWithMissingBaseTablesFilter()}`;
|
|
3623
3952
|
const entitiesResult = await this.runQuery(pool, sql);
|
|
3624
3953
|
const entities = entitiesResult.recordset;
|
|
3954
|
+
// An entity whose removal fails is recorded and the rest still run; the step then fails
|
|
3955
|
+
// (#3546). A half-pruned entity left behind silently drops out of every later generation.
|
|
3956
|
+
const failedRemovals = [];
|
|
3625
3957
|
if (entities && entities.length > 0) {
|
|
3626
3958
|
for (const e of entities) {
|
|
3627
3959
|
// External-data-source entities have no physical MJ table by design, so they always
|
|
@@ -3635,9 +3967,8 @@ export class ManageMetadataBase {
|
|
|
3635
3967
|
if (e.ExternalDataSourceID) {
|
|
3636
3968
|
continue;
|
|
3637
3969
|
}
|
|
3638
|
-
// for the given entity, wipe out the entity metadata and its core deps.
|
|
3639
|
-
//
|
|
3640
|
-
// for the admin to handle manually
|
|
3970
|
+
// for the given entity, wipe out the entity metadata and its core deps. This fails when
|
|
3971
|
+
// a dependency the routine does not handle still references the entity.
|
|
3641
3972
|
try {
|
|
3642
3973
|
// discardResult: this routine only performs deletions — nothing below reads rows
|
|
3643
3974
|
// from it — and on PostgreSQL it is declared RETURNS SETOF record, which cannot be
|
|
@@ -3659,13 +3990,18 @@ export class ManageMetadataBase {
|
|
|
3659
3990
|
await this.checkDropSQLObject(pool, e.FullTextSearchFunctionGenerated, 'function', e.SchemaName, e.FullTextSearchFunction);
|
|
3660
3991
|
}
|
|
3661
3992
|
catch (ex) {
|
|
3662
|
-
|
|
3993
|
+
failedRemovals.push(`${e.Name} (${e.SchemaName}.${e.BaseTable})`);
|
|
3994
|
+
logError(`Error removing metadata for entity ${e.Name} (${e.SchemaName}.${e.BaseTable}): ${ex instanceof Error ? ex.message : String(ex)}`);
|
|
3663
3995
|
}
|
|
3664
3996
|
}
|
|
3665
3997
|
// if we get here we now need to refresh our metadata object
|
|
3666
3998
|
const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
|
|
3667
3999
|
await md.Refresh();
|
|
3668
4000
|
}
|
|
4001
|
+
if (failedRemovals.length > 0) {
|
|
4002
|
+
logError(` Could not remove metadata for ${failedRemovals.length} entit${failedRemovals.length === 1 ? 'y' : 'ies'} whose base table was dropped: ${failedRemovals.join(', ')}`);
|
|
4003
|
+
return false;
|
|
4004
|
+
}
|
|
3669
4005
|
return true;
|
|
3670
4006
|
}
|
|
3671
4007
|
catch (e) {
|
|
@@ -3750,19 +4086,45 @@ export class ManageMetadataBase {
|
|
|
3750
4086
|
* Manages the creation, updating and deletion of entity field records in the metadata based on the database schema.
|
|
3751
4087
|
*
|
|
3752
4088
|
* @param entityFilter Optional list of entity NAMES to scope the field-management work to. When provided,
|
|
3753
|
-
* the
|
|
3754
|
-
*
|
|
3755
|
-
*
|
|
3756
|
-
* which is the typical "no schema changes since last run" case in Pass 2.
|
|
4089
|
+
* the create-new and update-existing schema-sync passes filter to those entities only. The orphan prune
|
|
4090
|
+
* is never scoped (#4050): it runs first, over every entity, and any entity it removed fields from is
|
|
4091
|
+
* added to the filter so its Sequence is renumbered in the same run. An empty filter with nothing pruned
|
|
4092
|
+
* skips the rest of the method, which is the typical "no schema changes since last run" case in Pass 2.
|
|
3757
4093
|
* `undefined` (default) preserves prior full-scan behavior.
|
|
3758
4094
|
*/
|
|
3759
4095
|
async ManageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields = false, entityFilter) {
|
|
3760
4096
|
let bSuccess = true;
|
|
3761
4097
|
const startTime = new Date();
|
|
3762
|
-
//
|
|
3763
|
-
|
|
4098
|
+
// Prune orphaned EntityField rows FIRST and UNSCOPED (#4050, #5976, #6028). The SQL pass
|
|
4099
|
+
// regenerates the base view of every included entity, so a view can lose columns while its
|
|
4100
|
+
// table is unchanged (the hierarchy opt-in gate drops Root*/Depth/Path this way). Such an
|
|
4101
|
+
// entity is in neither the new nor the modified list, which are built from table changes,
|
|
4102
|
+
// so a scoped prune — or the empty-filter exit below — never reaches it. The prune is one
|
|
4103
|
+
// routine call; the scan is the same one R__RefreshMetadata runs on every migrate.
|
|
4104
|
+
let prunedEntityNames = [];
|
|
4105
|
+
if (skipDeleteUnneededFields) {
|
|
4106
|
+
logStatus(` Skipping deletion of unneeded entity fields (deferred to post-SQL pass)`);
|
|
4107
|
+
}
|
|
4108
|
+
else {
|
|
4109
|
+
const pruneStart = new Date();
|
|
4110
|
+
const prune = await this.deleteUnneededEntityFields(pool, excludeSchemas);
|
|
4111
|
+
if (!prune.success) {
|
|
4112
|
+
logError('Error deleting unneeded entity fields');
|
|
4113
|
+
bSuccess = false;
|
|
4114
|
+
}
|
|
4115
|
+
prunedEntityNames = prune.prunedEntityNames;
|
|
4116
|
+
logStatus(` Deleted unneeded entity fields${prunedEntityNames.length > 0 ? ` from ${prunedEntityNames.length} entit${prunedEntityNames.length === 1 ? 'y' : 'ies'}` : ''} in ${(new Date().getTime() - pruneStart.getTime()) / 1000} seconds`);
|
|
4117
|
+
}
|
|
4118
|
+
// A pruned entity joins this pass's scope: spUpdateExistingEntityFieldsFromSchema renumbers
|
|
4119
|
+
// Sequence from the live view and only touches entities in scope. The caller snapshotted the
|
|
4120
|
+
// modified list before this call, so the prune's addition to that list does not reach here.
|
|
4121
|
+
const effectiveFilter = entityFilter
|
|
4122
|
+
? [...new Set([...entityFilter, ...prunedEntityNames])]
|
|
4123
|
+
: undefined;
|
|
4124
|
+
// Fast-exit: an empty filter means "no entities changed in Pass 1 and nothing was pruned"
|
|
4125
|
+
if (effectiveFilter && effectiveFilter.length === 0) {
|
|
3764
4126
|
logStatus(` manageEntityFields: empty entityFilter — skipping Pass 2 (no entities to process)`);
|
|
3765
|
-
return
|
|
4127
|
+
return bSuccess;
|
|
3766
4128
|
}
|
|
3767
4129
|
// Resolve entity names → IDs once up front so SP wrappers can receive UUIDs directly.
|
|
3768
4130
|
// If a non-empty filter resolved to zero IDs (e.g., all names were stale/invalid),
|
|
@@ -3770,11 +4132,11 @@ export class ManageMetadataBase {
|
|
|
3770
4132
|
// unscoped full scan, which is worse than the original intent. Treating "filter
|
|
3771
4133
|
// provided but nothing resolved" as a no-op is the correct behavior.
|
|
3772
4134
|
let scopedEntityIDs;
|
|
3773
|
-
if (
|
|
3774
|
-
scopedEntityIDs = this.resolveEntityNamesToIDs(
|
|
4135
|
+
if (effectiveFilter) {
|
|
4136
|
+
scopedEntityIDs = this.resolveEntityNamesToIDs(effectiveFilter);
|
|
3775
4137
|
if (scopedEntityIDs.length === 0) {
|
|
3776
|
-
logStatus(` manageEntityFields: entityFilter (${
|
|
3777
|
-
return
|
|
4138
|
+
logStatus(` manageEntityFields: entityFilter (${effectiveFilter.length} names) resolved to 0 IDs — skipping Pass 2`);
|
|
4139
|
+
return bSuccess;
|
|
3778
4140
|
}
|
|
3779
4141
|
}
|
|
3780
4142
|
if (!skipCreatedAtUpdatedAtDeletedAtFieldValidation) {
|
|
@@ -3785,17 +4147,6 @@ export class ManageMetadataBase {
|
|
|
3785
4147
|
}
|
|
3786
4148
|
logStatus(` Ensured ${EntityInfo.CreatedAtFieldName}/${EntityInfo.UpdatedAtFieldName}/${EntityInfo.DeletedAtFieldName} fields exist in ${(new Date().getTime() - startTime.getTime()) / 1000} seconds`);
|
|
3787
4149
|
}
|
|
3788
|
-
const step1StartTime = new Date();
|
|
3789
|
-
if (skipDeleteUnneededFields) {
|
|
3790
|
-
logStatus(` Skipping deletion of unneeded entity fields (deferred to post-SQL pass)`);
|
|
3791
|
-
}
|
|
3792
|
-
else {
|
|
3793
|
-
if (!await this.deleteUnneededEntityFields(pool, excludeSchemas, scopedEntityIDs)) {
|
|
3794
|
-
logError('Error deleting unneeded entity fields');
|
|
3795
|
-
bSuccess = false;
|
|
3796
|
-
}
|
|
3797
|
-
logStatus(` Deleted unneeded entity fields in ${(new Date().getTime() - step1StartTime.getTime()) / 1000} seconds`);
|
|
3798
|
-
}
|
|
3799
4150
|
// AN: 14-June-2025 - See note below about the new order of these steps, this must
|
|
3800
4151
|
// happen before we update existing entity fields from schema.
|
|
3801
4152
|
const step2StartTime = new Date();
|
|
@@ -3828,12 +4179,13 @@ export class ManageMetadataBase {
|
|
|
3828
4179
|
const stepConfigStartTime = new Date();
|
|
3829
4180
|
if (!await this.applySoftPKFKConfig(pool)) {
|
|
3830
4181
|
logError('Error applying soft PK/FK configuration');
|
|
4182
|
+
bSuccess = false;
|
|
3831
4183
|
}
|
|
3832
4184
|
logStatus(` Applied soft PK/FK configuration in ${(new Date().getTime() - stepConfigStartTime.getTime()) / 1000} seconds`);
|
|
3833
4185
|
// CRITICAL: Refresh metadata to pick up soft PK/FK flags
|
|
3834
4186
|
// Without this, downstream SQL and TypeScript generation will fail
|
|
3835
4187
|
// because entity.Fields and entity.PrimaryKeys won't reflect the updated flags
|
|
3836
|
-
if (
|
|
4188
|
+
if (ResolveAdditionalSchemaInfoPath()) {
|
|
3837
4189
|
logStatus(' Refreshing metadata after applying soft PK/FK configuration...');
|
|
3838
4190
|
const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
|
|
3839
4191
|
await md.Refresh();
|
|
@@ -3842,7 +4194,7 @@ export class ManageMetadataBase {
|
|
|
3842
4194
|
// IS-A parent field sync: create/update virtual EntityField records for parent chain fields
|
|
3843
4195
|
// Must run AFTER metadata refresh so it sees current soft PK/FK flags
|
|
3844
4196
|
const stepISAStartTime = new Date();
|
|
3845
|
-
const isaResult = await this.manageParentEntityFields(pool);
|
|
4197
|
+
const isaResult = await this.manageParentEntityFields(pool, excludeSchemas);
|
|
3846
4198
|
if (!isaResult.success) {
|
|
3847
4199
|
logError('Error managing IS-A parent entity fields');
|
|
3848
4200
|
bSuccess = false;
|
|
@@ -3964,21 +4316,27 @@ export class ManageMetadataBase {
|
|
|
3964
4316
|
* {@link applyVirtualEntitySoftKeys}.
|
|
3965
4317
|
*/
|
|
3966
4318
|
async applySoftPKFKConfig(pool) {
|
|
3967
|
-
// Check if additionalSchemaInfo is configured
|
|
3968
|
-
|
|
4319
|
+
// Check if additionalSchemaInfo is configured (mj.config.cjs or the RSU env override)
|
|
4320
|
+
const configPath = ResolveAdditionalSchemaInfoPath();
|
|
4321
|
+
if (!configPath) {
|
|
3969
4322
|
// No additional schema info configured - this is fine, it's optional
|
|
3970
4323
|
return true;
|
|
3971
4324
|
}
|
|
3972
|
-
|
|
4325
|
+
// A configured file that does not exist yet is normal: RSU writes it the first time it adds
|
|
4326
|
+
// a table, so a fresh checkout has none. Say where CodeGen looked, so a path that resolves
|
|
4327
|
+
// somewhere unexpected is visible (#5858). RSU itself fails the run when CodeGen creates no
|
|
4328
|
+
// entity for a table it added, which is what catches a real mismatch. An unreadable file
|
|
4329
|
+
// (below) is still a failure.
|
|
3973
4330
|
if (!fs.existsSync(configPath)) {
|
|
3974
|
-
|
|
4331
|
+
LogWarning(` additionalSchemaInfo is configured but no file exists yet at ${configPath}; no soft keys applied`);
|
|
3975
4332
|
return true;
|
|
3976
4333
|
}
|
|
3977
4334
|
try {
|
|
3978
|
-
logStatus(` Found ${
|
|
4335
|
+
logStatus(` Found ${configPath}, applying soft PK/FK configuration...`);
|
|
3979
4336
|
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
3980
4337
|
if (!config) {
|
|
3981
|
-
|
|
4338
|
+
logError(` additionalSchemaInfo file could not be parsed: ${configPath}`);
|
|
4339
|
+
return false;
|
|
3982
4340
|
}
|
|
3983
4341
|
// Config supports two formats:
|
|
3984
4342
|
// 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
|
|
@@ -4044,6 +4402,15 @@ export class ManageMetadataBase {
|
|
|
4044
4402
|
async applySoftKeysToTables(pool, tables, clearUniqueOnCompositeKey) {
|
|
4045
4403
|
let totalPKs = 0;
|
|
4046
4404
|
let totalFKs = 0;
|
|
4405
|
+
const conflicts = this.findConflictingSoftForeignKeys(tables);
|
|
4406
|
+
for (const c of conflicts) {
|
|
4407
|
+
logError(` Soft FK ${c.SchemaName}.${c.TableName}.${c.FieldName} is declared with ${c.Targets.length} different targets (${c.Targets.join(', ')}). ` +
|
|
4408
|
+
`None of them is applied and the field is left as it is; keep one declaration in additionalSchemaInfo.`);
|
|
4409
|
+
}
|
|
4410
|
+
const skipFields = new Set(conflicts.map(c => this.softFKFieldKey(c.SchemaName, c.TableName, c.FieldName)));
|
|
4411
|
+
// Primary keys first, for every table, so the FK pass sees each target's soft PK whatever the
|
|
4412
|
+
// order of the tables in the file.
|
|
4413
|
+
const resolved = [];
|
|
4047
4414
|
for (const table of tables) {
|
|
4048
4415
|
// Look up entity ID (SELECT query - no need to log to migration file)
|
|
4049
4416
|
const entityLookupSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName = '${EscapeSQLString(table.SchemaName)}' AND BaseTable = '${EscapeSQLString(table.TableName)}'`;
|
|
@@ -4055,11 +4422,108 @@ export class ManageMetadataBase {
|
|
|
4055
4422
|
const entityId = entityResult.recordset[0].ID;
|
|
4056
4423
|
const primaryKeys = table.PrimaryKey || [];
|
|
4057
4424
|
totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
|
|
4058
|
-
|
|
4425
|
+
resolved.push({ table, entityId });
|
|
4426
|
+
}
|
|
4427
|
+
for (const { table, entityId } of resolved) {
|
|
4428
|
+
totalFKs += await this.applySoftForeignKeys(pool, table, entityId, skipFields);
|
|
4059
4429
|
}
|
|
4060
4430
|
logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
|
|
4061
4431
|
return totalPKs + totalFKs;
|
|
4062
4432
|
}
|
|
4433
|
+
/**
|
|
4434
|
+
* Finds fields declared as a soft FK to more than one target. Each declaration is applied as its
|
|
4435
|
+
* own UPDATE, so without this check the last one in the file would win silently.
|
|
4436
|
+
* Names compare case-insensitively: on SQL Server `ID` and `id` are the same column; on
|
|
4437
|
+
* PostgreSQL one of the two does not exist, which the target check reports.
|
|
4438
|
+
*/
|
|
4439
|
+
findConflictingSoftForeignKeys(tables) {
|
|
4440
|
+
const byField = new Map();
|
|
4441
|
+
for (const table of tables) {
|
|
4442
|
+
for (const fk of table.ForeignKeys || []) {
|
|
4443
|
+
const fieldKey = this.softFKFieldKey(table.SchemaName, table.TableName, fk.FieldName);
|
|
4444
|
+
const target = `${fk.SchemaName || table.SchemaName}.${fk.RelatedTable}.${fk.RelatedField}`;
|
|
4445
|
+
let entry = byField.get(fieldKey);
|
|
4446
|
+
if (!entry) {
|
|
4447
|
+
entry = { SchemaName: table.SchemaName, TableName: table.TableName, FieldName: fk.FieldName, Targets: [] };
|
|
4448
|
+
byField.set(fieldKey, entry);
|
|
4449
|
+
}
|
|
4450
|
+
if (!entry.Targets.some(t => t.toLowerCase() === target.toLowerCase())) {
|
|
4451
|
+
entry.Targets.push(target);
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
}
|
|
4455
|
+
return [...byField.values()].filter(e => e.Targets.length > 1);
|
|
4456
|
+
}
|
|
4457
|
+
softFKFieldKey(schemaName, tableName, fieldName) {
|
|
4458
|
+
return `${schemaName}.${tableName}.${fieldName}`.toLowerCase();
|
|
4459
|
+
}
|
|
4460
|
+
/**
|
|
4461
|
+
* Checks a soft FK's target column against the related entity's fields. The name matches
|
|
4462
|
+
* case-sensitively on PostgreSQL, where `ID` and `id` are different identifiers, and
|
|
4463
|
+
* case-insensitively on SQL Server. A column of a multi-column primary key is not unique on its
|
|
4464
|
+
* own, so a join on it alone can return several rows. That is decided before `IsUnique` is read:
|
|
4465
|
+
* on a live SQL Server run, both columns of a two-column primary key carried `IsUnique = 1`.
|
|
4466
|
+
*/
|
|
4467
|
+
checkSoftFKTarget(relatedFields, relatedField, caseSensitive) {
|
|
4468
|
+
const target = relatedFields.find(f => caseSensitive ? f.Name === relatedField : f.Name.toLowerCase() === relatedField.toLowerCase());
|
|
4469
|
+
if (!target) {
|
|
4470
|
+
return { ResolvedName: null, IsUnique: false };
|
|
4471
|
+
}
|
|
4472
|
+
const pkCount = relatedFields.filter(f => f.IsPrimaryKey).length;
|
|
4473
|
+
if (target.IsPrimaryKey && pkCount > 1) {
|
|
4474
|
+
return { ResolvedName: target.Name, IsUnique: false, NotUniqueReason: `it is one column of a ${pkCount}-column primary key` };
|
|
4475
|
+
}
|
|
4476
|
+
if (target.IsPrimaryKey) {
|
|
4477
|
+
return { ResolvedName: target.Name, IsUnique: true };
|
|
4478
|
+
}
|
|
4479
|
+
if (target.IsUnique) {
|
|
4480
|
+
return { ResolvedName: target.Name, IsUnique: true, UniqueByFlagOnly: true };
|
|
4481
|
+
}
|
|
4482
|
+
return { ResolvedName: target.Name, IsUnique: false, NotUniqueReason: 'it is neither a primary key nor unique' };
|
|
4483
|
+
}
|
|
4484
|
+
/**
|
|
4485
|
+
* Confirms a target that only `IsUnique` vouches for against the database's unique indexes.
|
|
4486
|
+
* Schema sync sets `IsUnique` on every column of a composite unique constraint, so the flag
|
|
4487
|
+
* alone cannot say whether a join on the column returns one row. A failed or unsupported
|
|
4488
|
+
* lookup keeps the flag's answer.
|
|
4489
|
+
*/
|
|
4490
|
+
async confirmSoftFKTargetUnique(pool, schemaName, tableName, target) {
|
|
4491
|
+
if (!target.UniqueByFlagOnly || target.ResolvedName === null) {
|
|
4492
|
+
return target;
|
|
4493
|
+
}
|
|
4494
|
+
const sql = this.uniqueIndexMembershipSQL(schemaName, tableName, target.ResolvedName);
|
|
4495
|
+
if (!sql) {
|
|
4496
|
+
return target;
|
|
4497
|
+
}
|
|
4498
|
+
try {
|
|
4499
|
+
const res = await this.runQuery(pool, sql);
|
|
4500
|
+
const rows = res.recordset.map(r => ({ KeyColumnCount: Number(r.KeyColumnCount), IsIncludedColumn: this.isFlagSet(r.IsIncludedColumn) }));
|
|
4501
|
+
return this.uniquenessFromIndexes(target, rows);
|
|
4502
|
+
}
|
|
4503
|
+
catch (e) {
|
|
4504
|
+
LogWarning(` ⚠️ Could not read the unique indexes of ${schemaName}.${tableName}.${target.ResolvedName}; trusting IsUnique: ${e}`);
|
|
4505
|
+
return target;
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
4508
|
+
/** The platform's unique-index lookup for a column, or null when it has none. */
|
|
4509
|
+
uniqueIndexMembershipSQL(schemaName, tableName, columnName) {
|
|
4510
|
+
return this.dbProvider.GetUniqueIndexMembershipSQL(schemaName, tableName, columnName);
|
|
4511
|
+
}
|
|
4512
|
+
/**
|
|
4513
|
+
* Decides uniqueness from the unique indexes a column belongs to. A single-key-column index makes
|
|
4514
|
+
* it unique. Otherwise a composite unique index, or being only an INCLUDE column, means it is not.
|
|
4515
|
+
* No rows (a view, or IsUnique set by configuration) keeps the target as it is.
|
|
4516
|
+
*/
|
|
4517
|
+
uniquenessFromIndexes(target, indexes) {
|
|
4518
|
+
const keyIndexes = indexes.filter(ix => !ix.IsIncludedColumn);
|
|
4519
|
+
if (indexes.length === 0 || keyIndexes.some(ix => ix.KeyColumnCount === 1)) {
|
|
4520
|
+
return target;
|
|
4521
|
+
}
|
|
4522
|
+
const reason = keyIndexes.length > 0
|
|
4523
|
+
? `it is one column of a ${Math.min(...keyIndexes.map(ix => ix.KeyColumnCount))}-column unique constraint`
|
|
4524
|
+
: 'it is only an INCLUDE column of a unique index';
|
|
4525
|
+
return { ResolvedName: target.ResolvedName, IsUnique: false, NotUniqueReason: reason };
|
|
4526
|
+
}
|
|
4063
4527
|
/**
|
|
4064
4528
|
* Sets IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1 on each configured key column.
|
|
4065
4529
|
* IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync.
|
|
@@ -4100,12 +4564,17 @@ export class ManageMetadataBase {
|
|
|
4100
4564
|
/**
|
|
4101
4565
|
* Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
|
|
4102
4566
|
* key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
|
|
4567
|
+
* A field in `skipFields` (declared with conflicting targets) and a target column the related
|
|
4568
|
+
* entity does not have are skipped; a target that is not unique on its own is applied with a warning.
|
|
4103
4569
|
* @returns the number of UPDATEs written
|
|
4104
4570
|
*/
|
|
4105
|
-
async applySoftForeignKeys(pool, table, entityId) {
|
|
4571
|
+
async applySoftForeignKeys(pool, table, entityId, skipFields = new Set()) {
|
|
4106
4572
|
const schema = MjCoreSchema();
|
|
4107
4573
|
let written = 0;
|
|
4108
4574
|
for (const fk of table.ForeignKeys || []) {
|
|
4575
|
+
if (skipFields.has(this.softFKFieldKey(table.SchemaName, table.TableName, fk.FieldName))) {
|
|
4576
|
+
continue; // conflicting declarations, reported once by applySoftKeysToTables
|
|
4577
|
+
}
|
|
4109
4578
|
const fkSchema = fk.SchemaName || table.SchemaName;
|
|
4110
4579
|
// Look up related entity ID (SELECT query - no need to log to migration file)
|
|
4111
4580
|
const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${EscapeSQLString(fkSchema)}' AND BaseTable = '${EscapeSQLString(fk.RelatedTable)}'`;
|
|
@@ -4116,6 +4585,22 @@ export class ManageMetadataBase {
|
|
|
4116
4585
|
}
|
|
4117
4586
|
const relatedEntityId = relatedEntityResult.recordset[0].ID;
|
|
4118
4587
|
const fieldName = EscapeSQLString(fk.FieldName);
|
|
4588
|
+
// The target column must exist on the related entity, and should be unique on its own:
|
|
4589
|
+
// a label join on a non-unique column multiplies the rows of the generated base view.
|
|
4590
|
+
const targetFieldsSQL = `SELECT ${this.qi('Name')}, ${this.qi('IsPrimaryKey')}, ${this.qi('IsUnique')}
|
|
4591
|
+
FROM ${this.qs(schema, 'EntityField')}
|
|
4592
|
+
WHERE ${this.qi('EntityID')} = '${relatedEntityId}'`;
|
|
4593
|
+
const targetFieldsRes = await this.runQuery(pool, targetFieldsSQL);
|
|
4594
|
+
const flagCheck = this.checkSoftFKTarget(targetFieldsRes.recordset.map(r => ({ Name: String(r.Name), IsPrimaryKey: this.isFlagSet(r.IsPrimaryKey), IsUnique: this.isFlagSet(r.IsUnique) })), fk.RelatedField, DbPlatform() === 'postgresql');
|
|
4595
|
+
const target = await this.confirmSoftFKTargetUnique(pool, fkSchema, fk.RelatedTable, flagCheck);
|
|
4596
|
+
if (target.ResolvedName === null) {
|
|
4597
|
+
LogWarning(` ⚠️ Soft FK ${table.SchemaName}.${table.TableName}.${fk.FieldName} targets ${fkSchema}.${fk.RelatedTable}.${fk.RelatedField}, which has no such column - skipping`);
|
|
4598
|
+
continue;
|
|
4599
|
+
}
|
|
4600
|
+
if (!target.IsUnique) {
|
|
4601
|
+
LogWarning(` ⚠️ Soft FK ${table.SchemaName}.${table.TableName}.${fk.FieldName} targets ${fkSchema}.${fk.RelatedTable}.${target.ResolvedName}, but ${target.NotUniqueReason}; a join on it can return more than one row`);
|
|
4602
|
+
}
|
|
4603
|
+
const relatedField = target.ResolvedName;
|
|
4119
4604
|
const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
|
|
4120
4605
|
FROM ${this.qs(schema, 'EntityField')}
|
|
4121
4606
|
WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
|
|
@@ -4128,7 +4613,7 @@ export class ManageMetadataBase {
|
|
|
4128
4613
|
const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
|
|
4129
4614
|
const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
|
|
4130
4615
|
if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
|
|
4131
|
-
curRelField ===
|
|
4616
|
+
curRelField === relatedField.trim().toLowerCase() &&
|
|
4132
4617
|
this.isFlagSet(row.IsSoftForeignKey) &&
|
|
4133
4618
|
!this.isFlagSet(row.AutoUpdateRelatedEntityInfo)) {
|
|
4134
4619
|
continue; // Already correctly set, skip write
|
|
@@ -4136,13 +4621,13 @@ export class ManageMetadataBase {
|
|
|
4136
4621
|
const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
|
|
4137
4622
|
SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
|
|
4138
4623
|
${this.qi('RelatedEntityID')} = '${relatedEntityId}',
|
|
4139
|
-
${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(
|
|
4624
|
+
${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(relatedField)}',
|
|
4140
4625
|
${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
|
|
4141
4626
|
${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
|
|
4142
4627
|
WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
|
|
4143
|
-
const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${
|
|
4628
|
+
const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${relatedField}`);
|
|
4144
4629
|
if (result !== null) {
|
|
4145
|
-
logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${
|
|
4630
|
+
logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${relatedField}`);
|
|
4146
4631
|
written++;
|
|
4147
4632
|
}
|
|
4148
4633
|
}
|
|
@@ -4903,6 +5388,144 @@ export class ManageMetadataBase {
|
|
|
4903
5388
|
logStatus(` > Applied ${applied} schema name prefix/suffix rules from additionalSchemaInfo.json`);
|
|
4904
5389
|
}
|
|
4905
5390
|
}
|
|
5391
|
+
/**
|
|
5392
|
+
* Returns the names of entities whose BASE VIEW exposes a view-only column that MJ has no
|
|
5393
|
+
* `EntityField` for — the virtual-field drift probe.
|
|
5394
|
+
*
|
|
5395
|
+
* WHY THIS IS NEEDED AND WHY NOTHING ELSE FINDS IT. Pass 2 of `ManageEntityFields` is scoped to
|
|
5396
|
+
* `NewEntityList ∪ ModifiedEntityList`, and the only writer of `ModifiedEntityList` is the
|
|
5397
|
+
* reconciler pass — it lists entities something CHANGED on during THIS run. A related-entity name
|
|
5398
|
+
* field whose `EntityField` row was missed once therefore drops out of scope permanently: nothing
|
|
5399
|
+
* changes on that entity again, so it is never in the list, so pass 2 never revisits it, so the
|
|
5400
|
+
* row is never created. The only recovery was `forceRegeneration`, which reprocesses every entity
|
|
5401
|
+
* in the database to heal one.
|
|
5402
|
+
*
|
|
5403
|
+
* The cost of leaving it is not cosmetic. `BaseEntity.InnerLoad` reads the base view and then
|
|
5404
|
+
* looks up each returned column in metadata; a column with no `EntityField` throws, so EVERY
|
|
5405
|
+
* record form for that entity fails — measured at 145 entities on one imported schema.
|
|
5406
|
+
*
|
|
5407
|
+
* WHAT THE PROBE MATCHES. `vwSQLColumnsAndEntityFields` is the catalog view both dialects already
|
|
5408
|
+
* use for exactly this comparison (`EntityFieldID IS NULL` is how `getPendingEntityFieldsSQL`
|
|
5409
|
+
* finds columns needing a field). Adding `IsVirtual <> 0` narrows it to VIEW-ONLY columns: those
|
|
5410
|
+
* are the ones pass 2 exists to create, and they are the ones pass 1 structurally cannot see,
|
|
5411
|
+
* because their names are invented during Step 2's view generation and only exist in the view.
|
|
5412
|
+
* New PHYSICAL columns are excluded — they carry `IsVirtual = 0`, pass 1 already finds them, and
|
|
5413
|
+
* pulling them in here would widen the scoped pass back out to a full scan.
|
|
5414
|
+
*
|
|
5415
|
+
* The observed spelling was a `<fk>_Virtual` alias, but the suffix is incidental (it is only
|
|
5416
|
+
* appended on a name collision, see `sql_codegen.ts` safeAlias); the load-bearing property is
|
|
5417
|
+
* "view-only column with no EntityField", so the probe tests that and not the name.
|
|
5418
|
+
*
|
|
5419
|
+
* `IsVirtual <> 0` rather than `= 1` deliberately: the column is an INTEGER in the PostgreSQL view
|
|
5420
|
+
* and a bit-valued expression in the SQL Server one, and `<> 0` is correct for both.
|
|
5421
|
+
*/
|
|
5422
|
+
async FindVirtualFieldDriftEntities(pool, excludeSchemas) {
|
|
5423
|
+
try {
|
|
5424
|
+
const excluded = (excludeSchemas ?? []).filter(sc => sc && sc.trim().length > 0);
|
|
5425
|
+
const schemaFilter = excluded.length > 0
|
|
5426
|
+
? ` AND ${this.qi('SchemaName')} NOT IN (${excluded.map(sc => `'${sc.replace(/'/g, "''")}'`).join(',')})`
|
|
5427
|
+
: '';
|
|
5428
|
+
const sSQL = `SELECT DISTINCT ${this.qi('Entity')}
|
|
5429
|
+
FROM ${this.qs(MjCoreSchema(), 'vwSQLColumnsAndEntityFields')}
|
|
5430
|
+
WHERE ${this.qi('EntityFieldID')} IS NULL
|
|
5431
|
+
AND ${this.qi('IsVirtual')} <> 0
|
|
5432
|
+
AND ${this.qi('Entity')} IS NOT NULL${schemaFilter}`;
|
|
5433
|
+
const result = await this.runQuery(pool, sSQL);
|
|
5434
|
+
const names = (result.recordset ?? [])
|
|
5435
|
+
.map((r) => String(r.Entity ?? '').trim())
|
|
5436
|
+
.filter((n) => n.length > 0);
|
|
5437
|
+
if (names.length > 0) {
|
|
5438
|
+
logStatus(` > Virtual-field drift probe: ${names.length} entit${names.length === 1 ? 'y' : 'ies'} carry a view-only column with no EntityField — adding to the Pass 2 scope.`);
|
|
5439
|
+
}
|
|
5440
|
+
return [...new Set(names)];
|
|
5441
|
+
}
|
|
5442
|
+
catch (e) {
|
|
5443
|
+
// A probe that cannot run must not take the run down: the pre-probe behaviour (drift
|
|
5444
|
+
// stays unhealed) is strictly better than a failed CodeGen.
|
|
5445
|
+
logError(` > Virtual-field drift probe failed; Pass 2 scope is unchanged. ${e}`);
|
|
5446
|
+
return [];
|
|
5447
|
+
}
|
|
5448
|
+
}
|
|
5449
|
+
async pruneSupportsProtectedFieldNames(pool) {
|
|
5450
|
+
if (this._pruneSupportsProtectedFieldNames === null) {
|
|
5451
|
+
try {
|
|
5452
|
+
// PARAMETER_MODE = 'IN' matters: a PostgreSQL `RETURNS TABLE` function also reports its
|
|
5453
|
+
// OUTPUT columns here (verified on PG 16), and SQL Server reports input parameters as 'IN'
|
|
5454
|
+
// too, so the filter is both necessary and portable.
|
|
5455
|
+
const sql = `SELECT PARAMETER_NAME FROM INFORMATION_SCHEMA.PARAMETERS ` +
|
|
5456
|
+
`WHERE SPECIFIC_SCHEMA = '${MjCoreSchema()}' ` +
|
|
5457
|
+
`AND SPECIFIC_NAME LIKE 'spDeleteUnneededEntityFields%' AND PARAMETER_MODE = 'IN'`;
|
|
5458
|
+
const result = await this.runQuery(pool, sql);
|
|
5459
|
+
const rows = (result.recordset ?? []);
|
|
5460
|
+
this._pruneSupportsProtectedFieldNames = rows.some(r => {
|
|
5461
|
+
const raw = String(r.PARAMETER_NAME ?? r.parameter_name ?? '').trim();
|
|
5462
|
+
return raw.replace(/^@/, '').replace(/^p_/i, '').toLowerCase() === 'protectedfieldnames';
|
|
5463
|
+
});
|
|
5464
|
+
}
|
|
5465
|
+
catch (e) {
|
|
5466
|
+
// Cannot prove the parameter exists → treat it as absent. The consequence of guessing
|
|
5467
|
+
// wrong in this direction is "the exclusion is declined"; the other direction is
|
|
5468
|
+
// "metadata is deleted".
|
|
5469
|
+
logError(` > Could not read spDeleteUnneededEntityFields parameters; base-view column exclusions will be declined. ${e}`);
|
|
5470
|
+
this._pruneSupportsProtectedFieldNames = false;
|
|
5471
|
+
}
|
|
5472
|
+
}
|
|
5473
|
+
return this._pruneSupportsProtectedFieldNames;
|
|
5474
|
+
}
|
|
5475
|
+
/**
|
|
5476
|
+
* Decides whether base-view column exclusions may be applied in this run, and records the answer
|
|
5477
|
+
* where the (synchronous, connectionless) base-view generators can read it.
|
|
5478
|
+
*
|
|
5479
|
+
* Called during metadata management, which runs BEFORE SQL generation, so the flag is settled by
|
|
5480
|
+
* the time any base view is emitted. A run that never calls this leaves exclusions disabled and
|
|
5481
|
+
* emits `alias.*` exactly as before.
|
|
5482
|
+
*/
|
|
5483
|
+
async resolveBaseViewExclusionSupport(pool) {
|
|
5484
|
+
const configured = (configInfo.baseViewExcludedFields ?? []).filter(f => f && f.trim().length > 0);
|
|
5485
|
+
if (configured.length === 0) {
|
|
5486
|
+
SetBaseViewExclusionsPermitted(false);
|
|
5487
|
+
return;
|
|
5488
|
+
}
|
|
5489
|
+
const supported = await this.pruneSupportsProtectedFieldNames(pool);
|
|
5490
|
+
SetBaseViewExclusionsPermitted(supported);
|
|
5491
|
+
if (supported) {
|
|
5492
|
+
LogWarning(` > baseViewExcludedFields is set (${configured.join(', ')}). Affected entities get an EXPLICIT base-view column list instead of SELECT alias.*, those columns are absent from every MJ read of the entity, and the view stops auto-absorbing new physical columns until the next CodeGen run.`);
|
|
5493
|
+
}
|
|
5494
|
+
else {
|
|
5495
|
+
LogWarning(` > baseViewExcludedFields is set (${configured.join(', ')}) but was DECLINED: ${MjCoreSchema()}.spDeleteUnneededEntityFields on this database does not accept @ProtectedFieldNames, so excluding a column from a base view would make CodeGen delete its EntityField row on the next run. Base views are emitted unchanged. Apply the migration that adds that parameter to enable exclusions.`);
|
|
5496
|
+
}
|
|
5497
|
+
}
|
|
5498
|
+
/** The configured base-view exclusions, as bare field names for the prune's protected list. */
|
|
5499
|
+
configuredProtectedFieldNames() {
|
|
5500
|
+
if (!BaseViewExclusionsPermitted()) {
|
|
5501
|
+
return [];
|
|
5502
|
+
}
|
|
5503
|
+
const out = new Set();
|
|
5504
|
+
for (const raw of configInfo.baseViewExcludedFields ?? []) {
|
|
5505
|
+
const entry = raw.trim();
|
|
5506
|
+
if (entry.length === 0) {
|
|
5507
|
+
continue;
|
|
5508
|
+
}
|
|
5509
|
+
// `EntityName.FieldName` narrows WHICH entity the view excludes it from, but the prune
|
|
5510
|
+
// protects by name across entities — a superset, and deliberately so: protecting a field
|
|
5511
|
+
// row that was never at risk costs nothing, while a per-entity protected list would need a
|
|
5512
|
+
// second parameter for the entity ids and buys no safety.
|
|
5513
|
+
const lastDot = entry.lastIndexOf('.');
|
|
5514
|
+
const field = lastDot > 0 && lastDot < entry.length - 1 ? entry.slice(lastDot + 1).trim() : entry;
|
|
5515
|
+
if (field.length > 0) {
|
|
5516
|
+
out.add(field);
|
|
5517
|
+
}
|
|
5518
|
+
}
|
|
5519
|
+
return [...out];
|
|
5520
|
+
}
|
|
5521
|
+
/**
|
|
5522
|
+
* Removes EntityField rows whose column no longer exists on the entity's base view or table.
|
|
5523
|
+
*
|
|
5524
|
+
* @param entityIDs Optional scope. {@link ManageEntityFields} omits it so every entity is scanned:
|
|
5525
|
+
* an entity orphaned by a view-only change is never in a change list (#4050).
|
|
5526
|
+
* @returns `success`, plus the distinct names of the entities rows were deleted from, so the
|
|
5527
|
+
* caller can bring them into scope for the Sequence renumber that follows.
|
|
5528
|
+
*/
|
|
4906
5529
|
async deleteUnneededEntityFields(pool, excludeSchemas, entityIDs) {
|
|
4907
5530
|
try {
|
|
4908
5531
|
// One SP call regardless of scope: pass the entire entity ID list as a comma-delimited
|
|
@@ -4913,6 +5536,11 @@ export class ManageMetadataBase {
|
|
|
4913
5536
|
authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
|
|
4914
5537
|
includeSchemas: configInfo.includeSchemas,
|
|
4915
5538
|
entityIDs,
|
|
5539
|
+
// Base-view column exclusions make their columns look orphaned to this prune (the
|
|
5540
|
+
// catalog view resolves columns view-first), so the excluded names are handed over as a
|
|
5541
|
+
// protected list. Empty unless exclusions are configured AND supported, so the emitted
|
|
5542
|
+
// EXEC is unchanged for every install that does not use them.
|
|
5543
|
+
protectedFieldNames: this.configuredProtectedFieldNames(),
|
|
4916
5544
|
});
|
|
4917
5545
|
const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spDeleteUnneededEntityFields', heal.Values, heal.Names);
|
|
4918
5546
|
const isScoped = entityIDs !== undefined && entityIDs.length > 0;
|
|
@@ -4922,16 +5550,30 @@ export class ManageMetadataBase {
|
|
|
4922
5550
|
const result = await this.logSQLAndExecute(pool, sSQL, label, true);
|
|
4923
5551
|
// result contains the DELETED entity fields. Get a distinct list of entity names
|
|
4924
5552
|
// and add them to the modified entity list if they're not already in there.
|
|
4925
|
-
|
|
4926
|
-
|
|
5553
|
+
const prunedEntityNames = this.distinctPrunedEntityNames(result);
|
|
5554
|
+
if (prunedEntityNames.length > 0) {
|
|
5555
|
+
ManageMetadataBase.addNewEntitiesToModifiedList(prunedEntityNames);
|
|
4927
5556
|
}
|
|
4928
|
-
return true;
|
|
5557
|
+
return { success: true, prunedEntityNames };
|
|
4929
5558
|
}
|
|
4930
5559
|
catch (e) {
|
|
4931
|
-
logError(e);
|
|
4932
|
-
return false;
|
|
5560
|
+
logError(`Error deleting unneeded entity fields: ${e instanceof Error ? e.message : String(e)}`);
|
|
5561
|
+
return { success: false, prunedEntityNames: [] };
|
|
4933
5562
|
}
|
|
4934
5563
|
}
|
|
5564
|
+
/**
|
|
5565
|
+
* Distinct, non-blank entity names from the rows spDeleteUnneededEntityFields returns (one row per
|
|
5566
|
+
* deleted field, carrying the owning entity's name in `Entity`).
|
|
5567
|
+
*/
|
|
5568
|
+
distinctPrunedEntityNames(rows) {
|
|
5569
|
+
if (!rows || rows.length === 0) {
|
|
5570
|
+
return [];
|
|
5571
|
+
}
|
|
5572
|
+
const names = rows
|
|
5573
|
+
.map(r => r.Entity)
|
|
5574
|
+
.filter((name) => typeof name === 'string' && name.trim().length > 0);
|
|
5575
|
+
return [...new Set(names)];
|
|
5576
|
+
}
|
|
4935
5577
|
async manageEntityFieldValuesAndValidatorFunctions(pool, excludeSchemas, currentUser, skipDBUpdate) {
|
|
4936
5578
|
try {
|
|
4937
5579
|
// here we want to get all of the entity fields that have check constraints attached to them. For each field that has a check constraint, we want to
|
|
@@ -5679,12 +6321,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
5679
6321
|
* Checks if a table has a soft primary key defined in the additionalSchemaInfo JSON file (configured in mj.config.cjs)
|
|
5680
6322
|
*/
|
|
5681
6323
|
hasSoftPrimaryKeyInConfig(schemaName, tableName) {
|
|
5682
|
-
|
|
6324
|
+
const configPath = ResolveAdditionalSchemaInfoPath();
|
|
6325
|
+
if (!configPath) {
|
|
5683
6326
|
return false;
|
|
5684
6327
|
}
|
|
5685
|
-
const configPath = path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo);
|
|
5686
6328
|
if (!fs.existsSync(configPath)) {
|
|
5687
|
-
|
|
6329
|
+
logError(` [Soft PK Check] additionalSchemaInfo is configured but the file was not found: ${configPath}`);
|
|
5688
6330
|
return false;
|
|
5689
6331
|
}
|
|
5690
6332
|
try {
|
|
@@ -7272,8 +7914,36 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
7272
7914
|
isFieldEligibleForNameField(field) {
|
|
7273
7915
|
if (field.IsVirtual === true && !this.isInheritedISAField(field))
|
|
7274
7916
|
return false;
|
|
7917
|
+
if (this.isForeignKeyOrPolymorphicRecordIDField(field))
|
|
7918
|
+
return false;
|
|
7275
7919
|
return this.isNameFieldTypeSafe(field);
|
|
7276
7920
|
}
|
|
7921
|
+
/**
|
|
7922
|
+
* Rejects foreign-key columns (`RelatedEntityID`) and polymorphic record-ID
|
|
7923
|
+
* payload columns (`EntityIDFieldName` populated, or named `*RecordID` /
|
|
7924
|
+
* `*RecordPrimaryKey` such as `RecordID`, `SourceRecordID`, `TargetRecordID`,
|
|
7925
|
+
* `LinkedRecordID`, `SurvivingRecordID`) from being selected as `IsNameField`.
|
|
7926
|
+
*
|
|
7927
|
+
* Polymorphic `RecordID` columns use `nvarchar(450)` / `nvarchar(750)` so they
|
|
7928
|
+
* can hold composite primary keys or non-UUID strings, which previously tricked
|
|
7929
|
+
* Smart Field Identification into treating them as human-readable text names
|
|
7930
|
+
* and displaying raw UUIDs in tab headers, breadcrumbs, and link cards.
|
|
7931
|
+
*/
|
|
7932
|
+
isForeignKeyOrPolymorphicRecordIDField(field) {
|
|
7933
|
+
const relatedEntityId = field.RelatedEntityID;
|
|
7934
|
+
if (relatedEntityId && String(relatedEntityId).trim().length > 0) {
|
|
7935
|
+
return true;
|
|
7936
|
+
}
|
|
7937
|
+
const entityIdFieldName = field.EntityIDFieldName;
|
|
7938
|
+
if (entityIdFieldName && String(entityIdFieldName).trim().length > 0) {
|
|
7939
|
+
return true;
|
|
7940
|
+
}
|
|
7941
|
+
const name = (field.Name ?? '').trim();
|
|
7942
|
+
if (/^(?:[A-Z][A-Za-z0-9]*?)?Record(?:ID|PrimaryKey)$/.test(name)) {
|
|
7943
|
+
return true;
|
|
7944
|
+
}
|
|
7945
|
+
return false;
|
|
7946
|
+
}
|
|
7277
7947
|
/**
|
|
7278
7948
|
* The TYPE half of {@link isFieldEligibleForNameField}, with no virtuality
|
|
7279
7949
|
* opinion: a primary key, a non-text type, or unbounded (MAX) text can never be
|