@memberjunction/codegen-lib 6.2.0-edge.3 → 6.2.0-edge.5
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 +5 -3
- package/dist/Angular/angular-codegen.js.map +1 -1
- package/dist/Config/config.d.ts +36 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +33 -0
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts +118 -2
- package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.js +234 -4
- 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 +263 -9
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +714 -67
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +36 -3
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +104 -23
- 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 +155 -2
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +23 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +77 -19
- 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/sql_codegen.d.ts +39 -1
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +100 -2
- 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/runCodeGen.d.ts +14 -0
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +21 -1
- 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';
|
|
@@ -23,7 +23,7 @@ import { CodeGenReporter } from "../Misc/codegen-reporter.js";
|
|
|
23
23
|
import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
|
|
24
24
|
import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
|
|
25
25
|
import { SQLParser } from "@memberjunction/sql-parser";
|
|
26
|
-
import { createDisplayName, EscapeSQLString, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
|
|
26
|
+
import { createDisplayName, EscapeSQLString, generatePluralName, IndexByUUID, MJGlobal, NormalizeUUID, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
|
|
27
27
|
import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
|
|
28
28
|
import * as fs from 'fs';
|
|
29
29
|
import path from 'path';
|
|
@@ -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.
|
|
@@ -1165,7 +1186,7 @@ export class ManageMetadataBase {
|
|
|
1165
1186
|
* Processes Entity attribute configurations from the additionalSchemaInfo config.
|
|
1166
1187
|
* For each entry in the top-level "Entities" array, looks up the entity by
|
|
1167
1188
|
* BaseTable + SchemaName and applies any declared attribute updates to the Entity table.
|
|
1168
|
-
* Reserved keys (BaseTable, SchemaName) are excluded from the UPDATE statement.
|
|
1189
|
+
* Reserved keys (BaseTable, SchemaName, AutoAddPermissions) are excluded from the UPDATE statement.
|
|
1169
1190
|
* Must run AFTER entities are created.
|
|
1170
1191
|
*/
|
|
1171
1192
|
async processEntityConfigs(pool) {
|
|
@@ -1177,7 +1198,8 @@ export class ManageMetadataBase {
|
|
|
1177
1198
|
return { success: true, updatedCount: 0 };
|
|
1178
1199
|
let updatedCount = 0;
|
|
1179
1200
|
const schema = MjCoreSchema();
|
|
1180
|
-
|
|
1201
|
+
// AutoAddPermissions is a creation-time option, not an Entity column (see resolveCreationTimeAutoAddPermissions).
|
|
1202
|
+
const reservedKeys = new Set(['BaseTable', 'SchemaName', 'AutoAddPermissions']);
|
|
1181
1203
|
for (const ec of entityConfigs) {
|
|
1182
1204
|
try {
|
|
1183
1205
|
// Collect the attribute columns to update (everything except BaseTable/SchemaName)
|
|
@@ -2078,6 +2100,10 @@ export class ManageMetadataBase {
|
|
|
2078
2100
|
return false;
|
|
2079
2101
|
}
|
|
2080
2102
|
}
|
|
2103
|
+
// Settle base-view column exclusions BEFORE anything generates a view. The decision depends on
|
|
2104
|
+
// whether this database's field prune can be told to leave the excluded columns' metadata
|
|
2105
|
+
// alone, which is a database fact and therefore only knowable here.
|
|
2106
|
+
await this.resolveBaseViewExclusionSupport(pool);
|
|
2081
2107
|
// Authored exclude list (sys, staging, …) must be captured BEFORE includeSchemas is
|
|
2082
2108
|
// compiled into excludeSchemas. Heal EXEC statements use that original list plus
|
|
2083
2109
|
// @IncludedSchemaNames — never the sibling snapshot of this machine's database.
|
|
@@ -3389,12 +3415,12 @@ export class ManageMetadataBase {
|
|
|
3389
3415
|
// individually caused a ping-pong bug where multi-FK pairs swapped JoinFields
|
|
3390
3416
|
// on every CodeGen run.
|
|
3391
3417
|
const entityPairGroups = this.groupFieldsByEntityPair(entityFields);
|
|
3418
|
+
const relationshipsForPair = ManageMetadataBase.relationshipsByEntityPair(allRelationships);
|
|
3392
3419
|
let batchSQL = '';
|
|
3393
3420
|
let batchCount = 0;
|
|
3394
3421
|
for (const [_pairKey, fkFields] of entityPairGroups) {
|
|
3395
3422
|
const firstField = fkFields[0];
|
|
3396
|
-
const relationships =
|
|
3397
|
-
UUIDsEqual(r.RelatedEntityID, firstField.EntityID));
|
|
3423
|
+
const relationships = relationshipsForPair(firstField.RelatedEntityID, firstField.EntityID);
|
|
3398
3424
|
if (relationships.length === 0) {
|
|
3399
3425
|
// No relationships exist for this pair — create one per FK field
|
|
3400
3426
|
for (const f of fkFields) {
|
|
@@ -3453,15 +3479,100 @@ export class ManageMetadataBase {
|
|
|
3453
3479
|
const relCount = relationshipCountMap.get(parentEntityID) || 0;
|
|
3454
3480
|
const sequence = relCount + 1;
|
|
3455
3481
|
const newEntityRelationshipUUID = this.createNewUUID();
|
|
3482
|
+
// EntityKeyField names the column on the PARENT (the EntityID side) that carries the join
|
|
3483
|
+
// value. It is NULL for an ordinary FK-to-primary-key relationship, where every consumer
|
|
3484
|
+
// correctly falls back to the parent's PK. It is load-bearing whenever the FK points at a
|
|
3485
|
+
// NON-PK column: see resolveRelationshipEntityKeyField.
|
|
3486
|
+
const entityKeyField = this.resolveRelationshipEntityKeyField(f, parentEntity);
|
|
3487
|
+
const keyFieldColumn = entityKeyField ? `, ${this.qi('EntityKeyField')}` : '';
|
|
3488
|
+
const keyFieldValue = entityKeyField ? `, '${entityKeyField.replace(/'/g, "''")}'` : '';
|
|
3456
3489
|
const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newEntityRelationshipUUID}'`;
|
|
3457
|
-
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')})
|
|
3458
|
-
VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}', 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
|
|
3490
|
+
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')})
|
|
3491
|
+
VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}'${keyFieldValue}, 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
|
|
3459
3492
|
relationshipCountMap.set(parentEntityID, sequence);
|
|
3460
3493
|
return `
|
|
3461
3494
|
/* Create Entity Relationship: ${parentEntity.Name} -> ${e.Name} (One To Many via ${f.Name}) */
|
|
3462
3495
|
${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};
|
|
3463
3496
|
`;
|
|
3464
3497
|
}
|
|
3498
|
+
/**
|
|
3499
|
+
* Resolves the `EntityRelationship.EntityKeyField` value for a discovered FK field, or `null`
|
|
3500
|
+
* when the relationship joins the parent's primary key and the column therefore must stay NULL.
|
|
3501
|
+
*
|
|
3502
|
+
* WHY THIS EXISTS. A foreign key does not have to point at a primary key. `EntityField` records
|
|
3503
|
+
* the referenced column in `RelatedEntityFieldName` — populated for declared FKs by the provider
|
|
3504
|
+
* introspection query and for soft FKs by `applySoftPKFKConfig` — but nothing carried it across
|
|
3505
|
+
* into the relationship row. `EntityRelationshipInfo.EntityKeyField` is the only place a consumer
|
|
3506
|
+
* can learn it, and all three consumers fall back to the parent's first primary key when it is
|
|
3507
|
+
* blank (`entityInfo.ts` BuildRelationshipViewParams, `entity-helpers.ts`,
|
|
3508
|
+
* `DependencyGraphWalker.ts`). So a relationship over a non-PK join column silently queried the
|
|
3509
|
+
* wrong column and returned zero rows for every parent record — measured on an imported schema
|
|
3510
|
+
* whose real keys are external ids: 60 relationships, 0 rows each.
|
|
3511
|
+
*
|
|
3512
|
+
* NULL IS THE CORRECT VALUE FOR AN ORDINARY FK, not merely an acceptable one. The PK fallback is
|
|
3513
|
+
* the documented contract, a stored 'ID' would duplicate it, and emitting the column only when it
|
|
3514
|
+
* differs keeps the generated SQL byte-identical for every FK-to-PK relationship — which is all
|
|
3515
|
+
* of them in core MJ.
|
|
3516
|
+
*
|
|
3517
|
+
* Returns null when: no referenced column was recorded; the referenced column IS the parent's
|
|
3518
|
+
* primary key; or the parent has a composite key (a single-column join cannot address it, and
|
|
3519
|
+
* guessing which component to use would be worse than the existing fallback).
|
|
3520
|
+
*/
|
|
3521
|
+
resolveRelationshipEntityKeyField(f, parentEntity) {
|
|
3522
|
+
const referenced = String(f.RelatedEntityFieldName ?? '').trim();
|
|
3523
|
+
if (referenced.length === 0) {
|
|
3524
|
+
return null;
|
|
3525
|
+
}
|
|
3526
|
+
const pkFields = parentEntity.PrimaryKeys ?? [];
|
|
3527
|
+
if (pkFields.length !== 1) {
|
|
3528
|
+
return null;
|
|
3529
|
+
}
|
|
3530
|
+
if (pkFields[0].Name.trim().toLowerCase() === referenced.toLowerCase()) {
|
|
3531
|
+
return null;
|
|
3532
|
+
}
|
|
3533
|
+
// The column must exist on the parent, or the consumer's `record.Get(EntityKeyField)` would
|
|
3534
|
+
// read undefined and build `WHERE col = undefined`. A referenced column MJ has no field for
|
|
3535
|
+
// is a metadata gap to report, not one to encode into a relationship row.
|
|
3536
|
+
const match = parentEntity.Fields.find(pf => pf.Name.trim().toLowerCase() === referenced.toLowerCase());
|
|
3537
|
+
if (!match) {
|
|
3538
|
+
logError(` > resolveRelationshipEntityKeyField: ${parentEntity.Name} has no field named '${referenced}' (referenced by FK ${f.Name}); leaving EntityKeyField NULL so the primary-key fallback applies.`);
|
|
3539
|
+
return null;
|
|
3540
|
+
}
|
|
3541
|
+
return match.Name.trim();
|
|
3542
|
+
}
|
|
3543
|
+
/**
|
|
3544
|
+
* Emits the UPDATE that brings an existing relationship row's `EntityKeyField` into line with the
|
|
3545
|
+
* schema, or `''` when it already agrees.
|
|
3546
|
+
*
|
|
3547
|
+
* This is the half that actually repairs a live database. A relationship whose
|
|
3548
|
+
* `RelatedEntityJoinField` is already correct takes the "exact match" path and is skipped, so
|
|
3549
|
+
* rows created before `EntityKeyField` was written stay blank forever and keep returning zero
|
|
3550
|
+
* rows. Honours `AutoUpdateFromSchema` exactly as the join-field reassignment below does: a row
|
|
3551
|
+
* an operator has taken ownership of is never touched.
|
|
3552
|
+
*/
|
|
3553
|
+
buildRelationshipEntityKeyFieldHealSQL(r, f, md) {
|
|
3554
|
+
if (!r.AutoUpdateFromSchema) {
|
|
3555
|
+
return '';
|
|
3556
|
+
}
|
|
3557
|
+
const parentEntity = md.Entities.find(e => UUIDsEqual(e.ID, f.RelatedEntityID));
|
|
3558
|
+
if (!parentEntity) {
|
|
3559
|
+
return '';
|
|
3560
|
+
}
|
|
3561
|
+
const desired = this.resolveRelationshipEntityKeyField(f, parentEntity);
|
|
3562
|
+
const current = String(r.EntityKeyField ?? '').trim();
|
|
3563
|
+
if ((desired ?? '') === current) {
|
|
3564
|
+
return '';
|
|
3565
|
+
}
|
|
3566
|
+
const literal = desired === null ? 'NULL' : `'${desired.replace(/'/g, "''")}'`;
|
|
3567
|
+
logStatus(` > Healing EntityRelationship key field: '${current}' -> ${desired ?? 'NULL'} (ID: ${r.ID})`);
|
|
3568
|
+
return `
|
|
3569
|
+
/* Heal EntityRelationship EntityKeyField from '${current}' to ${desired ?? 'NULL'} (non-PK join column) */
|
|
3570
|
+
UPDATE ${this.qs(MjCoreSchema(), 'EntityRelationship')}
|
|
3571
|
+
SET ${this.qi('EntityKeyField')} = ${literal},
|
|
3572
|
+
${this.qi('__mj_UpdatedAt')} = ${this.utcNow()}
|
|
3573
|
+
WHERE ${this.qi('ID')} = '${r.ID}';
|
|
3574
|
+
`;
|
|
3575
|
+
}
|
|
3465
3576
|
/**
|
|
3466
3577
|
* Groups FK fields by their entity pair key (ParentEntityID|ChildEntityID).
|
|
3467
3578
|
* This ensures all FK fields for the same entity pair are processed together,
|
|
@@ -3483,6 +3594,24 @@ export class ManageMetadataBase {
|
|
|
3483
3594
|
}
|
|
3484
3595
|
return groups;
|
|
3485
3596
|
}
|
|
3597
|
+
/**
|
|
3598
|
+
* Indexes relationship rows by their (EntityID, RelatedEntityID) pair, so each FK pair finds its
|
|
3599
|
+
* relationships without scanning every relationship in the database. IDs match in any case, and
|
|
3600
|
+
* each pair's rows keep their original order — exactly what a `filter` over the full list returns.
|
|
3601
|
+
*/
|
|
3602
|
+
static relationshipsByEntityPair(relationships) {
|
|
3603
|
+
const pairKey = (entityID, relatedEntityID) => `${NormalizeUUID(entityID)}|${NormalizeUUID(relatedEntityID)}`;
|
|
3604
|
+
const byPair = new Map();
|
|
3605
|
+
for (const r of relationships) {
|
|
3606
|
+
const key = pairKey(r.EntityID, r.RelatedEntityID);
|
|
3607
|
+
const group = byPair.get(key);
|
|
3608
|
+
if (group)
|
|
3609
|
+
group.push(r);
|
|
3610
|
+
else
|
|
3611
|
+
byPair.set(key, [r]);
|
|
3612
|
+
}
|
|
3613
|
+
return (entityID, relatedEntityID) => byPair.get(pairKey(entityID, relatedEntityID)) ?? [];
|
|
3614
|
+
}
|
|
3486
3615
|
/**
|
|
3487
3616
|
* Handles relationship management for an entire entity pair at once.
|
|
3488
3617
|
* Matches N FK fields to N existing relationship records using a 1:1 mapping:
|
|
@@ -3494,6 +3623,13 @@ export class ManageMetadataBase {
|
|
|
3494
3623
|
let sql = '';
|
|
3495
3624
|
// Build sets for matching
|
|
3496
3625
|
const fkFieldNames = new Set(fkFields.map(f => String(f.Name).trim()));
|
|
3626
|
+
const fkFieldsByName = new Map();
|
|
3627
|
+
for (const f of fkFields) {
|
|
3628
|
+
const key = String(f.Name).trim();
|
|
3629
|
+
if (!fkFieldsByName.has(key)) {
|
|
3630
|
+
fkFieldsByName.set(key, f);
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3497
3633
|
const matchedRelationshipIDs = new Set();
|
|
3498
3634
|
const matchedFieldNames = new Set();
|
|
3499
3635
|
// Pass 1: exact matches — relationship already has the correct JoinField
|
|
@@ -3502,6 +3638,13 @@ export class ManageMetadataBase {
|
|
|
3502
3638
|
if (fkFieldNames.has(joinField) && !matchedFieldNames.has(joinField)) {
|
|
3503
3639
|
matchedRelationshipIDs.add(String(r.ID));
|
|
3504
3640
|
matchedFieldNames.add(joinField);
|
|
3641
|
+
// The join field agrees, so nothing below will look at this row again — but
|
|
3642
|
+
// EntityKeyField may still be stale or (for every row written before it was emitted)
|
|
3643
|
+
// blank. That is the state that returns zero rows on a non-PK join, so heal it here.
|
|
3644
|
+
const matchedField = fkFieldsByName.get(joinField);
|
|
3645
|
+
if (matchedField) {
|
|
3646
|
+
sql += this.buildRelationshipEntityKeyFieldHealSQL(r, matchedField, md);
|
|
3647
|
+
}
|
|
3505
3648
|
}
|
|
3506
3649
|
}
|
|
3507
3650
|
// Pass 2: assign unmatched FK fields to unmatched auto-update relationships
|
|
@@ -3522,6 +3665,10 @@ export class ManageMetadataBase {
|
|
|
3522
3665
|
WHERE ${this.qi('ID')} = '${r.ID}';
|
|
3523
3666
|
`;
|
|
3524
3667
|
}
|
|
3668
|
+
// Reassigning the join field can also change which parent column the join addresses, so
|
|
3669
|
+
// the key field has to move with it — including back to NULL when the new FK targets the
|
|
3670
|
+
// parent's primary key.
|
|
3671
|
+
sql += this.buildRelationshipEntityKeyFieldHealSQL(r, f, md);
|
|
3525
3672
|
}
|
|
3526
3673
|
// Pass 3: create new relationships for any remaining unmatched FK fields
|
|
3527
3674
|
const remainingFields = unmatchedFields.slice(unmatchedRelationships.length);
|
|
@@ -4025,6 +4172,15 @@ export class ManageMetadataBase {
|
|
|
4025
4172
|
async applySoftKeysToTables(pool, tables, clearUniqueOnCompositeKey) {
|
|
4026
4173
|
let totalPKs = 0;
|
|
4027
4174
|
let totalFKs = 0;
|
|
4175
|
+
const conflicts = this.findConflictingSoftForeignKeys(tables);
|
|
4176
|
+
for (const c of conflicts) {
|
|
4177
|
+
logError(` Soft FK ${c.SchemaName}.${c.TableName}.${c.FieldName} is declared with ${c.Targets.length} different targets (${c.Targets.join(', ')}). ` +
|
|
4178
|
+
`None of them is applied and the field is left as it is; keep one declaration in additionalSchemaInfo.`);
|
|
4179
|
+
}
|
|
4180
|
+
const skipFields = new Set(conflicts.map(c => this.softFKFieldKey(c.SchemaName, c.TableName, c.FieldName)));
|
|
4181
|
+
// Primary keys first, for every table, so the FK pass sees each target's soft PK whatever the
|
|
4182
|
+
// order of the tables in the file.
|
|
4183
|
+
const resolved = [];
|
|
4028
4184
|
for (const table of tables) {
|
|
4029
4185
|
// Look up entity ID (SELECT query - no need to log to migration file)
|
|
4030
4186
|
const entityLookupSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName = '${EscapeSQLString(table.SchemaName)}' AND BaseTable = '${EscapeSQLString(table.TableName)}'`;
|
|
@@ -4036,11 +4192,108 @@ export class ManageMetadataBase {
|
|
|
4036
4192
|
const entityId = entityResult.recordset[0].ID;
|
|
4037
4193
|
const primaryKeys = table.PrimaryKey || [];
|
|
4038
4194
|
totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
|
|
4039
|
-
|
|
4195
|
+
resolved.push({ table, entityId });
|
|
4196
|
+
}
|
|
4197
|
+
for (const { table, entityId } of resolved) {
|
|
4198
|
+
totalFKs += await this.applySoftForeignKeys(pool, table, entityId, skipFields);
|
|
4040
4199
|
}
|
|
4041
4200
|
logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
|
|
4042
4201
|
return totalPKs + totalFKs;
|
|
4043
4202
|
}
|
|
4203
|
+
/**
|
|
4204
|
+
* Finds fields declared as a soft FK to more than one target. Each declaration is applied as its
|
|
4205
|
+
* own UPDATE, so without this check the last one in the file would win silently.
|
|
4206
|
+
* Names compare case-insensitively: on SQL Server `ID` and `id` are the same column; on
|
|
4207
|
+
* PostgreSQL one of the two does not exist, which the target check reports.
|
|
4208
|
+
*/
|
|
4209
|
+
findConflictingSoftForeignKeys(tables) {
|
|
4210
|
+
const byField = new Map();
|
|
4211
|
+
for (const table of tables) {
|
|
4212
|
+
for (const fk of table.ForeignKeys || []) {
|
|
4213
|
+
const fieldKey = this.softFKFieldKey(table.SchemaName, table.TableName, fk.FieldName);
|
|
4214
|
+
const target = `${fk.SchemaName || table.SchemaName}.${fk.RelatedTable}.${fk.RelatedField}`;
|
|
4215
|
+
let entry = byField.get(fieldKey);
|
|
4216
|
+
if (!entry) {
|
|
4217
|
+
entry = { SchemaName: table.SchemaName, TableName: table.TableName, FieldName: fk.FieldName, Targets: [] };
|
|
4218
|
+
byField.set(fieldKey, entry);
|
|
4219
|
+
}
|
|
4220
|
+
if (!entry.Targets.some(t => t.toLowerCase() === target.toLowerCase())) {
|
|
4221
|
+
entry.Targets.push(target);
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
}
|
|
4225
|
+
return [...byField.values()].filter(e => e.Targets.length > 1);
|
|
4226
|
+
}
|
|
4227
|
+
softFKFieldKey(schemaName, tableName, fieldName) {
|
|
4228
|
+
return `${schemaName}.${tableName}.${fieldName}`.toLowerCase();
|
|
4229
|
+
}
|
|
4230
|
+
/**
|
|
4231
|
+
* Checks a soft FK's target column against the related entity's fields. The name matches
|
|
4232
|
+
* case-sensitively on PostgreSQL, where `ID` and `id` are different identifiers, and
|
|
4233
|
+
* case-insensitively on SQL Server. A column of a multi-column primary key is not unique on its
|
|
4234
|
+
* own, so a join on it alone can return several rows. That is decided before `IsUnique` is read:
|
|
4235
|
+
* on a live SQL Server run, both columns of a two-column primary key carried `IsUnique = 1`.
|
|
4236
|
+
*/
|
|
4237
|
+
checkSoftFKTarget(relatedFields, relatedField, caseSensitive) {
|
|
4238
|
+
const target = relatedFields.find(f => caseSensitive ? f.Name === relatedField : f.Name.toLowerCase() === relatedField.toLowerCase());
|
|
4239
|
+
if (!target) {
|
|
4240
|
+
return { ResolvedName: null, IsUnique: false };
|
|
4241
|
+
}
|
|
4242
|
+
const pkCount = relatedFields.filter(f => f.IsPrimaryKey).length;
|
|
4243
|
+
if (target.IsPrimaryKey && pkCount > 1) {
|
|
4244
|
+
return { ResolvedName: target.Name, IsUnique: false, NotUniqueReason: `it is one column of a ${pkCount}-column primary key` };
|
|
4245
|
+
}
|
|
4246
|
+
if (target.IsPrimaryKey) {
|
|
4247
|
+
return { ResolvedName: target.Name, IsUnique: true };
|
|
4248
|
+
}
|
|
4249
|
+
if (target.IsUnique) {
|
|
4250
|
+
return { ResolvedName: target.Name, IsUnique: true, UniqueByFlagOnly: true };
|
|
4251
|
+
}
|
|
4252
|
+
return { ResolvedName: target.Name, IsUnique: false, NotUniqueReason: 'it is neither a primary key nor unique' };
|
|
4253
|
+
}
|
|
4254
|
+
/**
|
|
4255
|
+
* Confirms a target that only `IsUnique` vouches for against the database's unique indexes.
|
|
4256
|
+
* Schema sync sets `IsUnique` on every column of a composite unique constraint, so the flag
|
|
4257
|
+
* alone cannot say whether a join on the column returns one row. A failed or unsupported
|
|
4258
|
+
* lookup keeps the flag's answer.
|
|
4259
|
+
*/
|
|
4260
|
+
async confirmSoftFKTargetUnique(pool, schemaName, tableName, target) {
|
|
4261
|
+
if (!target.UniqueByFlagOnly || target.ResolvedName === null) {
|
|
4262
|
+
return target;
|
|
4263
|
+
}
|
|
4264
|
+
const sql = this.uniqueIndexMembershipSQL(schemaName, tableName, target.ResolvedName);
|
|
4265
|
+
if (!sql) {
|
|
4266
|
+
return target;
|
|
4267
|
+
}
|
|
4268
|
+
try {
|
|
4269
|
+
const res = await this.runQuery(pool, sql);
|
|
4270
|
+
const rows = res.recordset.map(r => ({ KeyColumnCount: Number(r.KeyColumnCount), IsIncludedColumn: this.isFlagSet(r.IsIncludedColumn) }));
|
|
4271
|
+
return this.uniquenessFromIndexes(target, rows);
|
|
4272
|
+
}
|
|
4273
|
+
catch (e) {
|
|
4274
|
+
LogWarning(` ⚠️ Could not read the unique indexes of ${schemaName}.${tableName}.${target.ResolvedName}; trusting IsUnique: ${e}`);
|
|
4275
|
+
return target;
|
|
4276
|
+
}
|
|
4277
|
+
}
|
|
4278
|
+
/** The platform's unique-index lookup for a column, or null when it has none. */
|
|
4279
|
+
uniqueIndexMembershipSQL(schemaName, tableName, columnName) {
|
|
4280
|
+
return this.dbProvider.GetUniqueIndexMembershipSQL(schemaName, tableName, columnName);
|
|
4281
|
+
}
|
|
4282
|
+
/**
|
|
4283
|
+
* Decides uniqueness from the unique indexes a column belongs to. A single-key-column index makes
|
|
4284
|
+
* it unique. Otherwise a composite unique index, or being only an INCLUDE column, means it is not.
|
|
4285
|
+
* No rows (a view, or IsUnique set by configuration) keeps the target as it is.
|
|
4286
|
+
*/
|
|
4287
|
+
uniquenessFromIndexes(target, indexes) {
|
|
4288
|
+
const keyIndexes = indexes.filter(ix => !ix.IsIncludedColumn);
|
|
4289
|
+
if (indexes.length === 0 || keyIndexes.some(ix => ix.KeyColumnCount === 1)) {
|
|
4290
|
+
return target;
|
|
4291
|
+
}
|
|
4292
|
+
const reason = keyIndexes.length > 0
|
|
4293
|
+
? `it is one column of a ${Math.min(...keyIndexes.map(ix => ix.KeyColumnCount))}-column unique constraint`
|
|
4294
|
+
: 'it is only an INCLUDE column of a unique index';
|
|
4295
|
+
return { ResolvedName: target.ResolvedName, IsUnique: false, NotUniqueReason: reason };
|
|
4296
|
+
}
|
|
4044
4297
|
/**
|
|
4045
4298
|
* Sets IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1 on each configured key column.
|
|
4046
4299
|
* IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync.
|
|
@@ -4081,12 +4334,17 @@ export class ManageMetadataBase {
|
|
|
4081
4334
|
/**
|
|
4082
4335
|
* Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
|
|
4083
4336
|
* key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
|
|
4337
|
+
* A field in `skipFields` (declared with conflicting targets) and a target column the related
|
|
4338
|
+
* entity does not have are skipped; a target that is not unique on its own is applied with a warning.
|
|
4084
4339
|
* @returns the number of UPDATEs written
|
|
4085
4340
|
*/
|
|
4086
|
-
async applySoftForeignKeys(pool, table, entityId) {
|
|
4341
|
+
async applySoftForeignKeys(pool, table, entityId, skipFields = new Set()) {
|
|
4087
4342
|
const schema = MjCoreSchema();
|
|
4088
4343
|
let written = 0;
|
|
4089
4344
|
for (const fk of table.ForeignKeys || []) {
|
|
4345
|
+
if (skipFields.has(this.softFKFieldKey(table.SchemaName, table.TableName, fk.FieldName))) {
|
|
4346
|
+
continue; // conflicting declarations, reported once by applySoftKeysToTables
|
|
4347
|
+
}
|
|
4090
4348
|
const fkSchema = fk.SchemaName || table.SchemaName;
|
|
4091
4349
|
// Look up related entity ID (SELECT query - no need to log to migration file)
|
|
4092
4350
|
const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${EscapeSQLString(fkSchema)}' AND BaseTable = '${EscapeSQLString(fk.RelatedTable)}'`;
|
|
@@ -4097,6 +4355,22 @@ export class ManageMetadataBase {
|
|
|
4097
4355
|
}
|
|
4098
4356
|
const relatedEntityId = relatedEntityResult.recordset[0].ID;
|
|
4099
4357
|
const fieldName = EscapeSQLString(fk.FieldName);
|
|
4358
|
+
// The target column must exist on the related entity, and should be unique on its own:
|
|
4359
|
+
// a label join on a non-unique column multiplies the rows of the generated base view.
|
|
4360
|
+
const targetFieldsSQL = `SELECT ${this.qi('Name')}, ${this.qi('IsPrimaryKey')}, ${this.qi('IsUnique')}
|
|
4361
|
+
FROM ${this.qs(schema, 'EntityField')}
|
|
4362
|
+
WHERE ${this.qi('EntityID')} = '${relatedEntityId}'`;
|
|
4363
|
+
const targetFieldsRes = await this.runQuery(pool, targetFieldsSQL);
|
|
4364
|
+
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');
|
|
4365
|
+
const target = await this.confirmSoftFKTargetUnique(pool, fkSchema, fk.RelatedTable, flagCheck);
|
|
4366
|
+
if (target.ResolvedName === null) {
|
|
4367
|
+
LogWarning(` ⚠️ Soft FK ${table.SchemaName}.${table.TableName}.${fk.FieldName} targets ${fkSchema}.${fk.RelatedTable}.${fk.RelatedField}, which has no such column - skipping`);
|
|
4368
|
+
continue;
|
|
4369
|
+
}
|
|
4370
|
+
if (!target.IsUnique) {
|
|
4371
|
+
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`);
|
|
4372
|
+
}
|
|
4373
|
+
const relatedField = target.ResolvedName;
|
|
4100
4374
|
const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
|
|
4101
4375
|
FROM ${this.qs(schema, 'EntityField')}
|
|
4102
4376
|
WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
|
|
@@ -4109,7 +4383,7 @@ export class ManageMetadataBase {
|
|
|
4109
4383
|
const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
|
|
4110
4384
|
const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
|
|
4111
4385
|
if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
|
|
4112
|
-
curRelField ===
|
|
4386
|
+
curRelField === relatedField.trim().toLowerCase() &&
|
|
4113
4387
|
this.isFlagSet(row.IsSoftForeignKey) &&
|
|
4114
4388
|
!this.isFlagSet(row.AutoUpdateRelatedEntityInfo)) {
|
|
4115
4389
|
continue; // Already correctly set, skip write
|
|
@@ -4117,13 +4391,13 @@ export class ManageMetadataBase {
|
|
|
4117
4391
|
const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
|
|
4118
4392
|
SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
|
|
4119
4393
|
${this.qi('RelatedEntityID')} = '${relatedEntityId}',
|
|
4120
|
-
${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(
|
|
4394
|
+
${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(relatedField)}',
|
|
4121
4395
|
${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
|
|
4122
4396
|
${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
|
|
4123
4397
|
WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
|
|
4124
|
-
const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${
|
|
4398
|
+
const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${relatedField}`);
|
|
4125
4399
|
if (result !== null) {
|
|
4126
|
-
logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${
|
|
4400
|
+
logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${relatedField}`);
|
|
4127
4401
|
written++;
|
|
4128
4402
|
}
|
|
4129
4403
|
}
|
|
@@ -4884,6 +5158,136 @@ export class ManageMetadataBase {
|
|
|
4884
5158
|
logStatus(` > Applied ${applied} schema name prefix/suffix rules from additionalSchemaInfo.json`);
|
|
4885
5159
|
}
|
|
4886
5160
|
}
|
|
5161
|
+
/**
|
|
5162
|
+
* Returns the names of entities whose BASE VIEW exposes a view-only column that MJ has no
|
|
5163
|
+
* `EntityField` for — the virtual-field drift probe.
|
|
5164
|
+
*
|
|
5165
|
+
* WHY THIS IS NEEDED AND WHY NOTHING ELSE FINDS IT. Pass 2 of `ManageEntityFields` is scoped to
|
|
5166
|
+
* `NewEntityList ∪ ModifiedEntityList`, and the only writer of `ModifiedEntityList` is the
|
|
5167
|
+
* reconciler pass — it lists entities something CHANGED on during THIS run. A related-entity name
|
|
5168
|
+
* field whose `EntityField` row was missed once therefore drops out of scope permanently: nothing
|
|
5169
|
+
* changes on that entity again, so it is never in the list, so pass 2 never revisits it, so the
|
|
5170
|
+
* row is never created. The only recovery was `forceRegeneration`, which reprocesses every entity
|
|
5171
|
+
* in the database to heal one.
|
|
5172
|
+
*
|
|
5173
|
+
* The cost of leaving it is not cosmetic. `BaseEntity.InnerLoad` reads the base view and then
|
|
5174
|
+
* looks up each returned column in metadata; a column with no `EntityField` throws, so EVERY
|
|
5175
|
+
* record form for that entity fails — measured at 145 entities on one imported schema.
|
|
5176
|
+
*
|
|
5177
|
+
* WHAT THE PROBE MATCHES. `vwSQLColumnsAndEntityFields` is the catalog view both dialects already
|
|
5178
|
+
* use for exactly this comparison (`EntityFieldID IS NULL` is how `getPendingEntityFieldsSQL`
|
|
5179
|
+
* finds columns needing a field). Adding `IsVirtual <> 0` narrows it to VIEW-ONLY columns: those
|
|
5180
|
+
* are the ones pass 2 exists to create, and they are the ones pass 1 structurally cannot see,
|
|
5181
|
+
* because their names are invented during Step 2's view generation and only exist in the view.
|
|
5182
|
+
* New PHYSICAL columns are excluded — they carry `IsVirtual = 0`, pass 1 already finds them, and
|
|
5183
|
+
* pulling them in here would widen the scoped pass back out to a full scan.
|
|
5184
|
+
*
|
|
5185
|
+
* The observed spelling was a `<fk>_Virtual` alias, but the suffix is incidental (it is only
|
|
5186
|
+
* appended on a name collision, see `sql_codegen.ts` safeAlias); the load-bearing property is
|
|
5187
|
+
* "view-only column with no EntityField", so the probe tests that and not the name.
|
|
5188
|
+
*
|
|
5189
|
+
* `IsVirtual <> 0` rather than `= 1` deliberately: the column is an INTEGER in the PostgreSQL view
|
|
5190
|
+
* and a bit-valued expression in the SQL Server one, and `<> 0` is correct for both.
|
|
5191
|
+
*/
|
|
5192
|
+
async FindVirtualFieldDriftEntities(pool, excludeSchemas) {
|
|
5193
|
+
try {
|
|
5194
|
+
const excluded = (excludeSchemas ?? []).filter(sc => sc && sc.trim().length > 0);
|
|
5195
|
+
const schemaFilter = excluded.length > 0
|
|
5196
|
+
? ` AND ${this.qi('SchemaName')} NOT IN (${excluded.map(sc => `'${sc.replace(/'/g, "''")}'`).join(',')})`
|
|
5197
|
+
: '';
|
|
5198
|
+
const sSQL = `SELECT DISTINCT ${this.qi('Entity')}
|
|
5199
|
+
FROM ${this.qs(MjCoreSchema(), 'vwSQLColumnsAndEntityFields')}
|
|
5200
|
+
WHERE ${this.qi('EntityFieldID')} IS NULL
|
|
5201
|
+
AND ${this.qi('IsVirtual')} <> 0
|
|
5202
|
+
AND ${this.qi('Entity')} IS NOT NULL${schemaFilter}`;
|
|
5203
|
+
const result = await this.runQuery(pool, sSQL);
|
|
5204
|
+
const names = (result.recordset ?? [])
|
|
5205
|
+
.map((r) => String(r.Entity ?? '').trim())
|
|
5206
|
+
.filter((n) => n.length > 0);
|
|
5207
|
+
if (names.length > 0) {
|
|
5208
|
+
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.`);
|
|
5209
|
+
}
|
|
5210
|
+
return [...new Set(names)];
|
|
5211
|
+
}
|
|
5212
|
+
catch (e) {
|
|
5213
|
+
// A probe that cannot run must not take the run down: the pre-probe behaviour (drift
|
|
5214
|
+
// stays unhealed) is strictly better than a failed CodeGen.
|
|
5215
|
+
logError(` > Virtual-field drift probe failed; Pass 2 scope is unchanged. ${e}`);
|
|
5216
|
+
return [];
|
|
5217
|
+
}
|
|
5218
|
+
}
|
|
5219
|
+
async pruneSupportsProtectedFieldNames(pool) {
|
|
5220
|
+
if (this._pruneSupportsProtectedFieldNames === null) {
|
|
5221
|
+
try {
|
|
5222
|
+
// PARAMETER_MODE = 'IN' matters: a PostgreSQL `RETURNS TABLE` function also reports its
|
|
5223
|
+
// OUTPUT columns here (verified on PG 16), and SQL Server reports input parameters as 'IN'
|
|
5224
|
+
// too, so the filter is both necessary and portable.
|
|
5225
|
+
const sql = `SELECT PARAMETER_NAME FROM INFORMATION_SCHEMA.PARAMETERS ` +
|
|
5226
|
+
`WHERE SPECIFIC_SCHEMA = '${MjCoreSchema()}' ` +
|
|
5227
|
+
`AND SPECIFIC_NAME LIKE 'spDeleteUnneededEntityFields%' AND PARAMETER_MODE = 'IN'`;
|
|
5228
|
+
const result = await this.runQuery(pool, sql);
|
|
5229
|
+
const rows = (result.recordset ?? []);
|
|
5230
|
+
this._pruneSupportsProtectedFieldNames = rows.some(r => {
|
|
5231
|
+
const raw = String(r.PARAMETER_NAME ?? r.parameter_name ?? '').trim();
|
|
5232
|
+
return raw.replace(/^@/, '').replace(/^p_/i, '').toLowerCase() === 'protectedfieldnames';
|
|
5233
|
+
});
|
|
5234
|
+
}
|
|
5235
|
+
catch (e) {
|
|
5236
|
+
// Cannot prove the parameter exists → treat it as absent. The consequence of guessing
|
|
5237
|
+
// wrong in this direction is "the exclusion is declined"; the other direction is
|
|
5238
|
+
// "metadata is deleted".
|
|
5239
|
+
logError(` > Could not read spDeleteUnneededEntityFields parameters; base-view column exclusions will be declined. ${e}`);
|
|
5240
|
+
this._pruneSupportsProtectedFieldNames = false;
|
|
5241
|
+
}
|
|
5242
|
+
}
|
|
5243
|
+
return this._pruneSupportsProtectedFieldNames;
|
|
5244
|
+
}
|
|
5245
|
+
/**
|
|
5246
|
+
* Decides whether base-view column exclusions may be applied in this run, and records the answer
|
|
5247
|
+
* where the (synchronous, connectionless) base-view generators can read it.
|
|
5248
|
+
*
|
|
5249
|
+
* Called during metadata management, which runs BEFORE SQL generation, so the flag is settled by
|
|
5250
|
+
* the time any base view is emitted. A run that never calls this leaves exclusions disabled and
|
|
5251
|
+
* emits `alias.*` exactly as before.
|
|
5252
|
+
*/
|
|
5253
|
+
async resolveBaseViewExclusionSupport(pool) {
|
|
5254
|
+
const configured = (configInfo.baseViewExcludedFields ?? []).filter(f => f && f.trim().length > 0);
|
|
5255
|
+
if (configured.length === 0) {
|
|
5256
|
+
SetBaseViewExclusionsPermitted(false);
|
|
5257
|
+
return;
|
|
5258
|
+
}
|
|
5259
|
+
const supported = await this.pruneSupportsProtectedFieldNames(pool);
|
|
5260
|
+
SetBaseViewExclusionsPermitted(supported);
|
|
5261
|
+
if (supported) {
|
|
5262
|
+
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.`);
|
|
5263
|
+
}
|
|
5264
|
+
else {
|
|
5265
|
+
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.`);
|
|
5266
|
+
}
|
|
5267
|
+
}
|
|
5268
|
+
/** The configured base-view exclusions, as bare field names for the prune's protected list. */
|
|
5269
|
+
configuredProtectedFieldNames() {
|
|
5270
|
+
if (!BaseViewExclusionsPermitted()) {
|
|
5271
|
+
return [];
|
|
5272
|
+
}
|
|
5273
|
+
const out = new Set();
|
|
5274
|
+
for (const raw of configInfo.baseViewExcludedFields ?? []) {
|
|
5275
|
+
const entry = raw.trim();
|
|
5276
|
+
if (entry.length === 0) {
|
|
5277
|
+
continue;
|
|
5278
|
+
}
|
|
5279
|
+
// `EntityName.FieldName` narrows WHICH entity the view excludes it from, but the prune
|
|
5280
|
+
// protects by name across entities — a superset, and deliberately so: protecting a field
|
|
5281
|
+
// row that was never at risk costs nothing, while a per-entity protected list would need a
|
|
5282
|
+
// second parameter for the entity ids and buys no safety.
|
|
5283
|
+
const lastDot = entry.lastIndexOf('.');
|
|
5284
|
+
const field = lastDot > 0 && lastDot < entry.length - 1 ? entry.slice(lastDot + 1).trim() : entry;
|
|
5285
|
+
if (field.length > 0) {
|
|
5286
|
+
out.add(field);
|
|
5287
|
+
}
|
|
5288
|
+
}
|
|
5289
|
+
return [...out];
|
|
5290
|
+
}
|
|
4887
5291
|
async deleteUnneededEntityFields(pool, excludeSchemas, entityIDs) {
|
|
4888
5292
|
try {
|
|
4889
5293
|
// One SP call regardless of scope: pass the entire entity ID list as a comma-delimited
|
|
@@ -4894,6 +5298,11 @@ export class ManageMetadataBase {
|
|
|
4894
5298
|
authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
|
|
4895
5299
|
includeSchemas: configInfo.includeSchemas,
|
|
4896
5300
|
entityIDs,
|
|
5301
|
+
// Base-view column exclusions make their columns look orphaned to this prune (the
|
|
5302
|
+
// catalog view resolves columns view-first), so the excluded names are handed over as a
|
|
5303
|
+
// protected list. Empty unless exclusions are configured AND supported, so the emitted
|
|
5304
|
+
// EXEC is unchanged for every install that does not use them.
|
|
5305
|
+
protectedFieldNames: this.configuredProtectedFieldNames(),
|
|
4897
5306
|
});
|
|
4898
5307
|
const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spDeleteUnneededEntityFields', heal.Values, heal.Names);
|
|
4899
5308
|
const isScoped = entityIDs !== undefined && entityIDs.length > 0;
|
|
@@ -4941,13 +5350,14 @@ export class ManageMetadataBase {
|
|
|
4941
5350
|
const emitValidators = skipDBUpdate || ag.featureEnabled('ParseCheckConstraints');
|
|
4942
5351
|
const columnLevelResults = result.filter((r) => r.EntityFieldID); // get the column level constraints
|
|
4943
5352
|
const tableLevelResults = result.filter((r) => !r.EntityFieldID); // get the table level constraints
|
|
5353
|
+
const entityFieldsByID = IndexByUUID(allEntityFields);
|
|
4944
5354
|
for (const r of columnLevelResults) {
|
|
4945
5355
|
// now, for each of the constraints we get back here, loop through and evaluate if they're simple and if they're simple, parse and sync with entity field values for that field
|
|
4946
5356
|
if (r.ConstraintDefinition && r.ConstraintDefinition.length > 0) {
|
|
4947
5357
|
// parse first, then decide whether THIS field should carry the list (bit, PK singleton guards).
|
|
4948
|
-
//
|
|
4949
|
-
// lookup here fails OPEN (the exclusions stop applying), so a case mismatch would be silent.
|
|
4950
|
-
const field =
|
|
5358
|
+
// Case-insensitive (the index normalizes IDs), not ===: PG returns lowercase UUIDs and SQL Server
|
|
5359
|
+
// uppercase, and a missed lookup here fails OPEN (the exclusions stop applying), so a case mismatch would be silent.
|
|
5360
|
+
const field = entityFieldsByID.Get(r.EntityFieldID);
|
|
4951
5361
|
const parsedValues = ManageMetadataBase.valueListForField(field, this.parseCheckConstraintValues(r.ConstraintDefinition, r.ColumnName, r.EntityName));
|
|
4952
5362
|
if (parsedValues) {
|
|
4953
5363
|
if (!skipDBUpdate) {
|
|
@@ -5226,7 +5636,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
5226
5636
|
* back quoted — `([Status]='Active' OR [Status]='Inactive')` — but numeric and `bit` literals come back
|
|
5227
5637
|
* **unquoted and parenthesized**: `([Level]=(3) OR [Level]=(2) OR [Level]=(1))`. Matching only the quoted
|
|
5228
5638
|
* form left a numeric IN-list with no value list at all, and so no dropdown in Explorer either (#3978).
|
|
5229
|
-
* PostgreSQL's
|
|
5639
|
+
* PostgreSQL's renderings are handled separately, by parsePostgreSQLConstraint.
|
|
5230
5640
|
*
|
|
5231
5641
|
* A single-value list is captured too: `CHECK (Status='Active')` — which is also how SQL Server renders
|
|
5232
5642
|
* `IN ('Active')` — permits exactly one value, which is a one-item list.
|
|
@@ -5238,12 +5648,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
5238
5648
|
// Normalize N'literal' to 'literal' so one pattern handles both.
|
|
5239
5649
|
// Note: Assuming fieldName does not contain regex special characters; otherwise, it needs to be escaped as well.
|
|
5240
5650
|
const processedConstraint = constraintDefinition.replace(/(^|[=(\s])N'([^']*)'/g, "$1'$2'");
|
|
5241
|
-
// PostgreSQL
|
|
5242
|
-
//
|
|
5243
|
-
//
|
|
5244
|
-
const
|
|
5245
|
-
if (
|
|
5246
|
-
return
|
|
5651
|
+
// PostgreSQL writes every one of these shapes differently from SQL Server, so it gets its own
|
|
5652
|
+
// anchored parse (#4713). It runs first because a PG definition cannot match the SQL Server
|
|
5653
|
+
// patterns below, and returning null here must NOT fall through to them.
|
|
5654
|
+
const pgValues = this.parsePostgreSQLConstraint(processedConstraint, fieldName);
|
|
5655
|
+
if (pgValues) {
|
|
5656
|
+
return pgValues;
|
|
5247
5657
|
}
|
|
5248
5658
|
// Build a regex fragment that matches the field name in any quoting style:
|
|
5249
5659
|
// [FieldName] (SQL Server) or "FieldName" (PostgreSQL) or bare FieldName
|
|
@@ -5300,7 +5710,10 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
5300
5710
|
if (!parsedValues || !field) {
|
|
5301
5711
|
return parsedValues;
|
|
5302
5712
|
}
|
|
5303
|
-
|
|
5713
|
+
// `bit` on SQL Server, `boolean`/`bool` on PostgreSQL — the same column, the same reasoning.
|
|
5714
|
+
// The PG parser cannot currently produce a boolean list anyway (true/false are neither quoted
|
|
5715
|
+
// nor numeric literals), so that half is a second line of defence rather than load-bearing.
|
|
5716
|
+
if (['bit', 'boolean', 'bool'].includes(field.Type?.trim().toLowerCase() ?? '')) {
|
|
5304
5717
|
return null;
|
|
5305
5718
|
}
|
|
5306
5719
|
if (field.IsPrimaryKey && parsedValues.length === 1) {
|
|
@@ -5336,29 +5749,211 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
5336
5749
|
return inner.endsWith('.') ? inner.slice(0, -1) : inner;
|
|
5337
5750
|
}
|
|
5338
5751
|
/**
|
|
5339
|
-
*
|
|
5340
|
-
*
|
|
5341
|
-
*
|
|
5342
|
-
*
|
|
5752
|
+
* A PostgreSQL `::type` cast as `pg_get_constraintdef()` writes it — `::text`, `::bigint`,
|
|
5753
|
+
* `::character varying`, `::double precision`, `::text[]`.
|
|
5754
|
+
*
|
|
5755
|
+
* Spelled as explicit space-separated words rather than the obvious `[A-Za-z0-9 ]*`, because that
|
|
5756
|
+
* form lets two quantifiers consume the same run of spaces (`[A-Za-z0-9 ]*` then `\\s*`), which is
|
|
5757
|
+
* polynomial backtracking on input like `::A` followed by many spaces. CodeQL flags it as
|
|
5758
|
+
* js/polynomial-redos, and it is right to: a constraint definition is input this library does not
|
|
5759
|
+
* control. Requiring a letter after every space removes the ambiguity — a run of spaces can be
|
|
5760
|
+
* split exactly one way.
|
|
5343
5761
|
*/
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
5762
|
+
static { this.PG_CAST = `::[A-Za-z][A-Za-z0-9]*(?: [A-Za-z][A-Za-z0-9]*)*(?:\\[\\])?`; }
|
|
5763
|
+
/**
|
|
5764
|
+
* Parses PostgreSQL's renderings of a value-list CHECK into the values it permits, or null when the
|
|
5765
|
+
* constraint is not a plain value list (#4713 — the other dialect of #3978).
|
|
5766
|
+
*
|
|
5767
|
+
* `pg_get_constraintdef()` writes these shapes, all captured from a live PostgreSQL 16:
|
|
5768
|
+
*
|
|
5769
|
+
* (((s)::text = ANY ((ARRAY['Active'::character varying, ...])::text[]))) multi, varchar
|
|
5770
|
+
* ((level = ANY (ARRAY[1, 2, 3]))) multi, numeric
|
|
5771
|
+
* ((bi = ANY (ARRAY['100000000000'::bigint, (2)::bigint]))) multi, mixed quoting
|
|
5772
|
+
* (((x IS NULL) OR (x = ANY (ARRAY[1, 2])))) nullable
|
|
5773
|
+
* ((one = 7)) / (((s)::text = 'OnlyOne'::text)) single value
|
|
5774
|
+
*
|
|
5775
|
+
* ANCHORED ON PURPOSE, and that is the whole design. The previous version searched for `ARRAY[...]`
|
|
5776
|
+
* anywhere in the definition and read only QUOTED elements, which was safe only by accident: both
|
|
5777
|
+
* `(x <> ALL (ARRAY[1, 2]))` (NOT IN) and `((x = ANY (ARRAY[1, 2])) OR (x > 100))` contain an ARRAY
|
|
5778
|
+
* whose elements are NOT the field's legal values — the first inverts the meaning, the second is a
|
|
5779
|
+
* subset. Reading numeric elements without anchoring the whole constraint would have turned both
|
|
5780
|
+
* into wrong value lists, and a wrong list makes `Validate()` refuse what the database accepts.
|
|
5781
|
+
*
|
|
5782
|
+
* Booleans are excluded by construction: `true`/`false` are neither quoted nor numeric, so an
|
|
5783
|
+
* `ARRAY[true, false]` yields no elements. That matches the `bit` exclusion on SQL Server — the
|
|
5784
|
+
* constraint is vacuous, and a checkbox is not a dropdown.
|
|
5785
|
+
*/
|
|
5786
|
+
parsePostgreSQLConstraint(constraintDefinition, fieldName) {
|
|
5787
|
+
// Strip the `CHECK (...)` wrapper pg_get_constraintdef() adds, then any balanced outer parens.
|
|
5788
|
+
const checkMatch = /^\s*CHECK\s*\((.*)\)\s*$/is.exec(constraintDefinition);
|
|
5789
|
+
let body = ManageMetadataBase.stripOuterParens(checkMatch ? checkMatch[1] : constraintDefinition);
|
|
5790
|
+
if (body.length === 0) {
|
|
5348
5791
|
return null;
|
|
5349
5792
|
}
|
|
5350
|
-
|
|
5351
|
-
//
|
|
5352
|
-
|
|
5353
|
-
const
|
|
5354
|
-
|
|
5355
|
-
|
|
5356
|
-
|
|
5357
|
-
|
|
5358
|
-
|
|
5793
|
+
const field = ManageMetadataBase.escapeForRegex(fieldName);
|
|
5794
|
+
// The left-hand side: the bare column, optionally double-quoted, optionally parenthesized and
|
|
5795
|
+
// cast (`(status)::text`) — which is how PG compares a varchar.
|
|
5796
|
+
const lhs = `\\(?"?${field}"?\\)?(?:${ManageMetadataBase.PG_CAST})?`;
|
|
5797
|
+
// `(x IS NULL) OR <rest>` — the nullable form. Unwrap it and judge <rest> on its own.
|
|
5798
|
+
const nullable = new RegExp(`^\\(?\\s*${lhs}\\s+IS\\s+NULL\\s*\\)?\\s+OR\\s+(.*)$`, 'is').exec(body);
|
|
5799
|
+
if (nullable) {
|
|
5800
|
+
body = ManageMetadataBase.stripOuterParens(nullable[1]);
|
|
5801
|
+
}
|
|
5802
|
+
// Anything still carrying a second condition or a non-equality operator is not a value list.
|
|
5803
|
+
// `<> ALL` is NOT IN; ` OR `/` AND ` means the list is not the whole story. Tested with the
|
|
5804
|
+
// string literals blanked first, so a constraint whose VALUES contain an operator —
|
|
5805
|
+
// `CHECK (op = ANY (ARRAY['<'::text, '>'::text]))` — is judged on its structure, not its data.
|
|
5806
|
+
const structure = body.replace(/'(?:[^']|'')*'/g, "''");
|
|
5807
|
+
if (/\s(OR|AND)\s/i.test(structure) || /<>|!=|>|</.test(structure) || /\bALL\s*\(/i.test(structure)) {
|
|
5808
|
+
return null;
|
|
5809
|
+
}
|
|
5810
|
+
// Multi-value: <lhs> = ANY (ARRAY[ ... ]) (the ARRAY may itself be parenthesized and cast).
|
|
5811
|
+
// The closing bracket is found by matching, not by regex: the varchar form ends `])::text[]`,
|
|
5812
|
+
// so a greedy `.*\]` swallows the cast and a lazy one would break on a value containing `]`.
|
|
5813
|
+
const anyMatch = new RegExp(`^${lhs}\\s*=\\s*ANY\\s*\\(\\s*\\(?\\s*ARRAY\\s*\\[`, 'is').exec(body);
|
|
5814
|
+
if (anyMatch) {
|
|
5815
|
+
const elements = ManageMetadataBase.readToMatchingBracket(body, anyMatch[0].length);
|
|
5816
|
+
return elements === null ? null : ManageMetadataBase.pgArrayElements(elements);
|
|
5817
|
+
}
|
|
5818
|
+
// Single value: <lhs> = <literal>. PG renders `IN (x)` this way, and it permits exactly x.
|
|
5819
|
+
const singleMatch = new RegExp(`^${lhs}\\s*=\\s*(.+)$`, 'is').exec(body);
|
|
5820
|
+
if (singleMatch) {
|
|
5821
|
+
const value = ManageMetadataBase.pgLiteralValue(singleMatch[1]);
|
|
5822
|
+
return value === null ? null : [value];
|
|
5823
|
+
}
|
|
5824
|
+
return null;
|
|
5825
|
+
}
|
|
5826
|
+
/**
|
|
5827
|
+
* Returns the text between an already-consumed `[` and its matching `]`, ignoring brackets that sit
|
|
5828
|
+
* inside quoted literals, or null when the bracket never closes.
|
|
5829
|
+
*/
|
|
5830
|
+
static readToMatchingBracket(text, startIndex) {
|
|
5831
|
+
let depth = 1, inQuote = false;
|
|
5832
|
+
for (let i = startIndex; i < text.length; i++) {
|
|
5833
|
+
const ch = text[i];
|
|
5834
|
+
if (inQuote) {
|
|
5835
|
+
if (ch === "'") {
|
|
5836
|
+
if (text[i + 1] === "'")
|
|
5837
|
+
i++;
|
|
5838
|
+
else
|
|
5839
|
+
inQuote = false;
|
|
5840
|
+
}
|
|
5841
|
+
continue;
|
|
5842
|
+
}
|
|
5843
|
+
if (ch === "'")
|
|
5844
|
+
inQuote = true;
|
|
5845
|
+
else if (ch === '[')
|
|
5846
|
+
depth++;
|
|
5847
|
+
else if (ch === ']') {
|
|
5848
|
+
depth--;
|
|
5849
|
+
if (depth === 0) {
|
|
5850
|
+
return text.slice(startIndex, i);
|
|
5851
|
+
}
|
|
5359
5852
|
}
|
|
5360
5853
|
}
|
|
5361
|
-
return
|
|
5854
|
+
return null;
|
|
5855
|
+
}
|
|
5856
|
+
/**
|
|
5857
|
+
* Splits an ARRAY[...] body into its elements and reads each one's literal value, or returns null
|
|
5858
|
+
* when any element is not a literal this can read (a boolean, a function call, a column reference).
|
|
5859
|
+
* All-or-nothing on purpose: a PARTIAL list is worse than none, because the values it drops are
|
|
5860
|
+
* legal ones that `Validate()` would then refuse. That is the bug this replaces — PG writes
|
|
5861
|
+
* `ARRAY['100000000000'::bigint, (2)::bigint]`, and reading only quoted elements captured the first
|
|
5862
|
+
* value and silently dropped the second.
|
|
5863
|
+
*/
|
|
5864
|
+
static pgArrayElements(arrayBody) {
|
|
5865
|
+
const values = [];
|
|
5866
|
+
for (const element of ManageMetadataBase.splitTopLevel(arrayBody)) {
|
|
5867
|
+
const value = ManageMetadataBase.pgLiteralValue(element);
|
|
5868
|
+
if (value === null) {
|
|
5869
|
+
return null;
|
|
5870
|
+
}
|
|
5871
|
+
values.push(value);
|
|
5872
|
+
}
|
|
5873
|
+
return values.length > 0 ? values : null;
|
|
5874
|
+
}
|
|
5875
|
+
/**
|
|
5876
|
+
* Reads one PostgreSQL literal, unwrapping the parentheses and `::type` casts it may be dressed in —
|
|
5877
|
+
* `'Active'::character varying`, `(2)::bigint`, `('1e30'::numeric)::double precision`, `2.25`.
|
|
5878
|
+
* Returns null for anything that is not a quoted or numeric literal, which is what keeps booleans,
|
|
5879
|
+
* function calls and column references out of a value list.
|
|
5880
|
+
*/
|
|
5881
|
+
static pgLiteralValue(element) {
|
|
5882
|
+
let text = element.trim();
|
|
5883
|
+
// Peel casts and wrapping parens until neither is left: ('x'::numeric)::double precision
|
|
5884
|
+
for (let i = 0; i < 10; i++) {
|
|
5885
|
+
const castAtEnd = new RegExp(`${ManageMetadataBase.PG_CAST}$`);
|
|
5886
|
+
const stripped = ManageMetadataBase.stripOuterParens(text.replace(castAtEnd, '').trim());
|
|
5887
|
+
if (stripped === text) {
|
|
5888
|
+
break;
|
|
5889
|
+
}
|
|
5890
|
+
text = stripped;
|
|
5891
|
+
}
|
|
5892
|
+
const quoted = /^'((?:[^']|'')*)'$/s.exec(text);
|
|
5893
|
+
if (quoted) {
|
|
5894
|
+
return quoted[1].replace(/''/g, "'");
|
|
5895
|
+
}
|
|
5896
|
+
return /^-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(text) ? text : null;
|
|
5897
|
+
}
|
|
5898
|
+
/** Splits on commas that sit outside quotes, parentheses and brackets. */
|
|
5899
|
+
static splitTopLevel(text) {
|
|
5900
|
+
const parts = [];
|
|
5901
|
+
let depth = 0, inQuote = false, current = '';
|
|
5902
|
+
for (let i = 0; i < text.length; i++) {
|
|
5903
|
+
const ch = text[i];
|
|
5904
|
+
if (inQuote) {
|
|
5905
|
+
inQuote = ch !== "'" || text[i + 1] === "'";
|
|
5906
|
+
if (ch === "'" && text[i + 1] === "'") {
|
|
5907
|
+
current += ch;
|
|
5908
|
+
i++;
|
|
5909
|
+
}
|
|
5910
|
+
}
|
|
5911
|
+
else if (ch === "'") {
|
|
5912
|
+
inQuote = true;
|
|
5913
|
+
}
|
|
5914
|
+
else if (ch === '(' || ch === '[') {
|
|
5915
|
+
depth++;
|
|
5916
|
+
}
|
|
5917
|
+
else if (ch === ')' || ch === ']') {
|
|
5918
|
+
depth--;
|
|
5919
|
+
}
|
|
5920
|
+
else if (ch === ',' && depth === 0) {
|
|
5921
|
+
parts.push(current);
|
|
5922
|
+
current = '';
|
|
5923
|
+
continue;
|
|
5924
|
+
}
|
|
5925
|
+
current += text[i];
|
|
5926
|
+
}
|
|
5927
|
+
if (current.trim().length > 0) {
|
|
5928
|
+
parts.push(current);
|
|
5929
|
+
}
|
|
5930
|
+
return parts;
|
|
5931
|
+
}
|
|
5932
|
+
/** Removes balanced parentheses that wrap the whole expression, however many layers deep. */
|
|
5933
|
+
static stripOuterParens(text) {
|
|
5934
|
+
let result = text.trim();
|
|
5935
|
+
while (result.startsWith('(') && result.endsWith(')')) {
|
|
5936
|
+
let depth = 0, wrapsWhole = true;
|
|
5937
|
+
for (let i = 0; i < result.length; i++) {
|
|
5938
|
+
if (result[i] === '(')
|
|
5939
|
+
depth++;
|
|
5940
|
+
else if (result[i] === ')')
|
|
5941
|
+
depth--;
|
|
5942
|
+
if (depth === 0 && i < result.length - 1) {
|
|
5943
|
+
wrapsWhole = false;
|
|
5944
|
+
break;
|
|
5945
|
+
}
|
|
5946
|
+
}
|
|
5947
|
+
if (!wrapsWhole) {
|
|
5948
|
+
break;
|
|
5949
|
+
}
|
|
5950
|
+
result = result.slice(1, -1).trim();
|
|
5951
|
+
}
|
|
5952
|
+
return result;
|
|
5953
|
+
}
|
|
5954
|
+
/** Escapes regex metacharacters so an identifier can be embedded in a pattern. */
|
|
5955
|
+
static escapeForRegex(value) {
|
|
5956
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
5362
5957
|
}
|
|
5363
5958
|
createExcludeTablesAndSchemasFilter(fieldPrefix) {
|
|
5364
5959
|
let sExcludeTables = '';
|
|
@@ -5712,7 +6307,11 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
5712
6307
|
LogError(` >>>> ERROR: Unable to add new entity ${newEntityName} to an application because no Application has SchemaAutoAddNewEntities='${newEntity.SchemaName}'. To fix this, update an existing Application record or create a new one with SchemaAutoAddNewEntities='${newEntity.SchemaName}'.`);
|
|
5713
6308
|
}
|
|
5714
6309
|
// next up, we need to check if we're configured to add permissions for new entities, and if so, add them
|
|
5715
|
-
|
|
6310
|
+
// A per-table `Entities` entry can opt a table out of the default grants (AutoAddPermissions: false),
|
|
6311
|
+
// e.g. a table only server code may touch. Applied here because grants made now would otherwise
|
|
6312
|
+
// have to be removed by a later migration.
|
|
6313
|
+
if (configInfo.newEntityDefaults.PermissionDefaults && configInfo.newEntityDefaults.PermissionDefaults.AutoAddPermissionsForNewEntities
|
|
6314
|
+
&& this.resolveCreationTimeAutoAddPermissions(newEntity.SchemaName, newEntity.TableName)) {
|
|
5716
6315
|
// we are asked to add permissions for new entities, so do that by looping through the permissions and adding them
|
|
5717
6316
|
const permissions = configInfo.newEntityDefaults.PermissionDefaults.Permissions;
|
|
5718
6317
|
for (const p of permissions) {
|
|
@@ -6331,11 +6930,79 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
6331
6930
|
${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)}, 'int', ${this.utcNow()}, ${this.utcNow()}
|
|
6332
6931
|
)`;
|
|
6333
6932
|
}
|
|
6933
|
+
/**
|
|
6934
|
+
* Returns the creation-time attribute overrides declared for one table in the additionalSchemaInfo
|
|
6935
|
+
* `Entities` array (matched case-insensitively on SchemaName + BaseTable).
|
|
6936
|
+
*
|
|
6937
|
+
* Applying these at creation — not only in the later {@link processEntityConfigs} pass — matters
|
|
6938
|
+
* for flags CodeGen acts on in the same run. The clearest case is `TrackRecordChanges`:
|
|
6939
|
+
* `ensureCreatedAtUpdatedAtFieldsExist` runs before `processEntityConfigs`, so a table declared
|
|
6940
|
+
* `TrackRecordChanges: false` used to receive `__mj_CreatedAt` / `__mj_UpdatedAt` columns on its
|
|
6941
|
+
* first CodeGen run anyway.
|
|
6942
|
+
*
|
|
6943
|
+
* Only the attributes in {@link EntityInfo.ConfigurableAtCreationAttributes} are returned, and only with a value of the right type
|
|
6944
|
+
* (boolean, or number for `UserViewMaxRows`); anything else is left to `processEntityConfigs`.
|
|
6945
|
+
*/
|
|
6946
|
+
resolveCreationTimeEntityConfig(schemaName, tableName) {
|
|
6947
|
+
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
6948
|
+
if (!config)
|
|
6949
|
+
return {};
|
|
6950
|
+
const match = this.extractEntitiesFromConfig(config).find(ec => ec.SchemaName.trim().toLowerCase() === schemaName.trim().toLowerCase() &&
|
|
6951
|
+
ec.BaseTable.trim().toLowerCase() === tableName.trim().toLowerCase());
|
|
6952
|
+
if (!match)
|
|
6953
|
+
return {};
|
|
6954
|
+
const overrides = {};
|
|
6955
|
+
for (const attr of EntityInfo.ConfigurableAtCreationAttributes) {
|
|
6956
|
+
const value = match[attr];
|
|
6957
|
+
if (attr === 'UserViewMaxRows' ? typeof value === 'number' : typeof value === 'boolean') {
|
|
6958
|
+
overrides[attr] = value;
|
|
6959
|
+
}
|
|
6960
|
+
}
|
|
6961
|
+
return overrides;
|
|
6962
|
+
}
|
|
6963
|
+
/**
|
|
6964
|
+
* Whether CodeGen should grant the default role permissions (`newEntityDefaults.PermissionDefaults`)
|
|
6965
|
+
* when it creates the entity for this table. A per-table `Entities` entry may set
|
|
6966
|
+
* `"AutoAddPermissions": false` for a table that only server code may touch; the entity is then
|
|
6967
|
+
* created with no role permissions at all. Anything other than the boolean `false` keeps the default.
|
|
6968
|
+
*/
|
|
6969
|
+
resolveCreationTimeAutoAddPermissions(schemaName, tableName) {
|
|
6970
|
+
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
6971
|
+
if (!config)
|
|
6972
|
+
return true;
|
|
6973
|
+
const match = this.extractEntitiesFromConfig(config).find(ec => ec.SchemaName.trim().toLowerCase() === schemaName.trim().toLowerCase() &&
|
|
6974
|
+
ec.BaseTable.trim().toLowerCase() === tableName.trim().toLowerCase());
|
|
6975
|
+
return match?.AutoAddPermissions !== false;
|
|
6976
|
+
}
|
|
6334
6977
|
createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
|
|
6335
6978
|
const newEntityDefaults = configInfo.newEntityDefaults;
|
|
6979
|
+
const overrides = this.resolveCreationTimeEntityConfig(newEntity.SchemaName, newEntity.TableName);
|
|
6336
6980
|
const newEntityDescriptionEscaped = newEntity.EntityDescription ? `'${newEntity.EntityDescription.replace(/'/g, "''")}'` : null;
|
|
6337
|
-
const allowCaching = this.resolveAllowCachingForSchema(newEntity.SchemaName);
|
|
6338
6981
|
const q = (name) => this.qi(name);
|
|
6982
|
+
// Effective value for each optional flag: per-table config first, then the global default.
|
|
6983
|
+
// `undefined` leaves the column out of the INSERT so the table default applies.
|
|
6984
|
+
const flag = (attr, globalDefault) => overrides[attr] !== undefined ? overrides[attr] : globalDefault;
|
|
6985
|
+
const literal = (value) => typeof value === 'boolean' ? this.boolLit(value) : String(value);
|
|
6986
|
+
const columns = [
|
|
6987
|
+
['IncludeInAPI', literal(flag('IncludeInAPI', true))],
|
|
6988
|
+
['AllowUserSearchAPI', literal(flag('AllowUserSearchAPI', newEntityDefaults.AllowUserSearchAPI ?? true))],
|
|
6989
|
+
['AllowCaching', literal(flag('AllowCaching', this.resolveAllowCachingForSchema(newEntity.SchemaName)))],
|
|
6990
|
+
];
|
|
6991
|
+
const optional = [
|
|
6992
|
+
['TrackRecordChanges', newEntityDefaults.TrackRecordChanges],
|
|
6993
|
+
['AuditRecordAccess', newEntityDefaults.AuditRecordAccess],
|
|
6994
|
+
['AuditViewRuns', newEntityDefaults.AuditViewRuns],
|
|
6995
|
+
['AllowAllRowsAPI', newEntityDefaults.AllowAllRowsAPI],
|
|
6996
|
+
['AllowCreateAPI', newEntityDefaults.AllowCreateAPI],
|
|
6997
|
+
['AllowUpdateAPI', newEntityDefaults.AllowUpdateAPI],
|
|
6998
|
+
['AllowDeleteAPI', newEntityDefaults.AllowDeleteAPI],
|
|
6999
|
+
['UserViewMaxRows', newEntityDefaults.UserViewMaxRows],
|
|
7000
|
+
];
|
|
7001
|
+
for (const [attr, globalDefault] of optional) {
|
|
7002
|
+
const value = flag(attr, globalDefault);
|
|
7003
|
+
if (value !== undefined)
|
|
7004
|
+
columns.push([attr, literal(value)]);
|
|
7005
|
+
}
|
|
6339
7006
|
const sSQLInsert = `
|
|
6340
7007
|
INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
|
|
6341
7008
|
${q('ID')},
|
|
@@ -6346,17 +7013,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
6346
7013
|
${q('BaseTable')},
|
|
6347
7014
|
${q('BaseView')},
|
|
6348
7015
|
${q('SchemaName')},
|
|
6349
|
-
${q('
|
|
6350
|
-
${q('AllowUserSearchAPI')},
|
|
6351
|
-
${q('AllowCaching')}
|
|
6352
|
-
${newEntityDefaults.TrackRecordChanges === undefined ? '' : ', ' + q('TrackRecordChanges')}
|
|
6353
|
-
${newEntityDefaults.AuditRecordAccess === undefined ? '' : ', ' + q('AuditRecordAccess')}
|
|
6354
|
-
${newEntityDefaults.AuditViewRuns === undefined ? '' : ', ' + q('AuditViewRuns')}
|
|
6355
|
-
${newEntityDefaults.AllowAllRowsAPI === undefined ? '' : ', ' + q('AllowAllRowsAPI')}
|
|
6356
|
-
${newEntityDefaults.AllowCreateAPI === undefined ? '' : ', ' + q('AllowCreateAPI')}
|
|
6357
|
-
${newEntityDefaults.AllowUpdateAPI === undefined ? '' : ', ' + q('AllowUpdateAPI')}
|
|
6358
|
-
${newEntityDefaults.AllowDeleteAPI === undefined ? '' : ', ' + q('AllowDeleteAPI')}
|
|
6359
|
-
${newEntityDefaults.UserViewMaxRows === undefined ? '' : ', ' + q('UserViewMaxRows')}
|
|
7016
|
+
${columns.map(([col]) => q(col)).join(',\n ')}
|
|
6360
7017
|
, ${q('__mj_CreatedAt')}
|
|
6361
7018
|
, ${q('__mj_UpdatedAt')}
|
|
6362
7019
|
)
|
|
@@ -6369,17 +7026,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
6369
7026
|
'${newEntity.TableName}',
|
|
6370
7027
|
'vw${generatePluralName(newEntity.TableName, { capitalizeFirstLetterOnly: true }) + (newEntitySuffix && newEntitySuffix.length > 0 ? newEntitySuffix : '')}',
|
|
6371
7028
|
'${newEntity.SchemaName}',
|
|
6372
|
-
${
|
|
6373
|
-
${newEntityDefaults.AllowUserSearchAPI === undefined ? this.boolLit(true) : this.boolLit(newEntityDefaults.AllowUserSearchAPI)},
|
|
6374
|
-
${this.boolLit(allowCaching)}
|
|
6375
|
-
${newEntityDefaults.TrackRecordChanges === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.TrackRecordChanges)}
|
|
6376
|
-
${newEntityDefaults.AuditRecordAccess === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AuditRecordAccess)}
|
|
6377
|
-
${newEntityDefaults.AuditViewRuns === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AuditViewRuns)}
|
|
6378
|
-
${newEntityDefaults.AllowAllRowsAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowAllRowsAPI)}
|
|
6379
|
-
${newEntityDefaults.AllowCreateAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowCreateAPI)}
|
|
6380
|
-
${newEntityDefaults.AllowUpdateAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowUpdateAPI)}
|
|
6381
|
-
${newEntityDefaults.AllowDeleteAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowDeleteAPI)}
|
|
6382
|
-
${newEntityDefaults.UserViewMaxRows === undefined ? '' : ', ' + (newEntityDefaults.UserViewMaxRows)}
|
|
7029
|
+
${columns.map(([, value]) => value).join(',\n ')}
|
|
6383
7030
|
, ${this.utcNow()}
|
|
6384
7031
|
, ${this.utcNow()}
|
|
6385
7032
|
)
|