@memberjunction/codegen-lib 6.2.0 → 6.3.0-edge.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/Angular/angular-codegen.js +1 -1
- package/dist/Config/config.d.ts +10 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +7 -0
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/config-retraction.d.ts +126 -0
- package/dist/Database/config-retraction.d.ts.map +1 -0
- package/dist/Database/config-retraction.js +151 -0
- package/dist/Database/config-retraction.js.map +1 -0
- package/dist/Database/manage-metadata.d.ts +142 -6
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +609 -119
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +9 -3
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/postgresql/metadataSupportObjects.js +21 -7
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +10 -4
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +61 -4
- package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js +30 -3
- package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js.map +1 -1
- package/dist/Database/sqlPassFailures.d.ts +26 -0
- package/dist/Database/sqlPassFailures.d.ts.map +1 -0
- package/dist/Database/sqlPassFailures.js +15 -0
- package/dist/Database/sqlPassFailures.js.map +1 -0
- package/dist/Database/sql_codegen.d.ts +11 -0
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +37 -3
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Database/unique-key-sets.d.ts +71 -0
- package/dist/Database/unique-key-sets.d.ts.map +1 -0
- package/dist/Database/unique-key-sets.js +140 -0
- package/dist/Database/unique-key-sets.js.map +1 -0
- package/dist/Misc/file-write.d.ts.map +1 -1
- package/dist/Misc/file-write.js +16 -10
- package/dist/Misc/file-write.js.map +1 -1
- package/dist/Misc/sql_logging.d.ts +3 -1
- package/dist/Misc/sql_logging.d.ts.map +1 -1
- package/dist/Misc/sql_logging.js +4 -2
- package/dist/Misc/sql_logging.js.map +1 -1
- package/dist/Misc/system_integrity.d.ts +28 -0
- package/dist/Misc/system_integrity.d.ts.map +1 -1
- package/dist/Misc/system_integrity.js +54 -7
- package/dist/Misc/system_integrity.js.map +1 -1
- package/dist/Misc/typed_query_codegen.d.ts +130 -0
- package/dist/Misc/typed_query_codegen.d.ts.map +1 -0
- package/dist/Misc/typed_query_codegen.js +726 -0
- package/dist/Misc/typed_query_codegen.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +66 -16
- package/dist/runCodeGen.js.map +1 -1
- package/package.json +29 -29
|
@@ -32,6 +32,8 @@ import { CanonicalJSONStringify, DeepEqualJSON } from "../Misc/util.js";
|
|
|
32
32
|
import { TrimTrailingStatementTerminators } from "../Misc/sql_text.js";
|
|
33
33
|
import { SQLLogging } from "../Misc/sql_logging.js";
|
|
34
34
|
import { ComputeFieldMetadataUpdate } from "./field-metadata-lock.js";
|
|
35
|
+
import { BuildCatalogUniqueKeyColumnsSQL, BuildStoredUniqueKeySetsSQL, BuildUniqueKeySetSyncSQL, DiffUniqueKeySets, GroupUniqueKeyColumns } from "./unique-key-sets.js";
|
|
36
|
+
import { DecideConfigValueListAction, FieldKey, NormalizeKey, NormalizeObjectName, ParseObjectName, PlanOrganicKeyRetraction, ResolveConfigEntity, SelectUndeclaredFields, } from "./config-retraction.js";
|
|
35
37
|
import { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
|
|
36
38
|
export { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, DiffEntityFieldSnapshots, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
|
|
37
39
|
export class ValidatorResult {
|
|
@@ -821,7 +823,8 @@ export class ManageMetadataBase {
|
|
|
821
823
|
* Processes organic key configurations from additionalSchemaInfo.
|
|
822
824
|
* For each configured organic key:
|
|
823
825
|
* 1. Creates transitive bridge views if TransitiveView is defined
|
|
824
|
-
* 2. Upserts EntityOrganicKey records (matched on EntityID + Name)
|
|
826
|
+
* 2. Upserts EntityOrganicKey records (matched on EntityID + Name), stamped `Source = 'Config'`:
|
|
827
|
+
* the file now owns a key it declares, which is what lets a later run retract it (#4535)
|
|
825
828
|
* 3. Upserts EntityOrganicKeyRelatedEntity records (matched on EntityOrganicKeyID + RelatedEntityID)
|
|
826
829
|
*
|
|
827
830
|
* All SQL is executed AND logged via LogSQLAndExecute for complete CI/CD traceability.
|
|
@@ -888,7 +891,8 @@ export class ManageMetadataBase {
|
|
|
888
891
|
${okConfig.CustomNormalizationExpression ? `CustomNormalizationExpression = '${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}',` : ''}
|
|
889
892
|
${okConfig.Description ? `Description = '${okConfig.Description.replace(/'/g, "''")}',` : ''}
|
|
890
893
|
Sequence = ${okConfig.Sequence ?? 0},
|
|
891
|
-
Status = 'Active'
|
|
894
|
+
Status = 'Active',
|
|
895
|
+
Source = 'Config'
|
|
892
896
|
WHERE ID = '${organicKeyId}'`;
|
|
893
897
|
await this.logSQLAndExecute(pool, updateSQL, `Update organic key "${okConfig.Name}" on ${ownerEntityName}`);
|
|
894
898
|
updatedCount++;
|
|
@@ -898,8 +902,8 @@ export class ManageMetadataBase {
|
|
|
898
902
|
// Insert new — use entity-lookup subquery so the logged SQL is portable across databases
|
|
899
903
|
const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
|
|
900
904
|
const insertSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKey')}
|
|
901
|
-
(EntityID, Name, ${okConfig.Description ? 'Description, ' : ''}MatchFieldNames, NormalizationStrategy, ${okConfig.CustomNormalizationExpression ? 'CustomNormalizationExpression, ' : ''}Sequence, Status)
|
|
902
|
-
VALUES (${ownerSubquery}, '${okConfig.Name}', ${okConfig.Description ? `'${okConfig.Description.replace(/'/g, "''")}', ` : ''}'${matchFieldNames}', '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}', ${okConfig.CustomNormalizationExpression ? `'${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}', ` : ''}${okConfig.Sequence ?? 0}, 'Active')`;
|
|
905
|
+
(EntityID, Name, ${okConfig.Description ? 'Description, ' : ''}MatchFieldNames, NormalizationStrategy, ${okConfig.CustomNormalizationExpression ? 'CustomNormalizationExpression, ' : ''}Sequence, Status, Source)
|
|
906
|
+
VALUES (${ownerSubquery}, '${okConfig.Name}', ${okConfig.Description ? `'${okConfig.Description.replace(/'/g, "''")}', ` : ''}'${matchFieldNames}', '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}', ${okConfig.CustomNormalizationExpression ? `'${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}', ` : ''}${okConfig.Sequence ?? 0}, 'Active', 'Config')`;
|
|
903
907
|
await this.logSQLAndExecute(pool, insertSQL, `Insert organic key "${okConfig.Name}" on ${ownerEntityName}`);
|
|
904
908
|
createdCount++;
|
|
905
909
|
logStatus(` > Organic key: Created "${okConfig.Name}" on ${ownerEntityName}`);
|
|
@@ -1000,6 +1004,374 @@ export class ManageMetadataBase {
|
|
|
1000
1004
|
}
|
|
1001
1005
|
return missing === 0 ? resolved : null;
|
|
1002
1006
|
}
|
|
1007
|
+
// ─── Retraction of declarations removed from additionalSchemaInfo (#4535) ───────────────────
|
|
1008
|
+
/** A nullable text column as a string or null. */
|
|
1009
|
+
optionalText(value) {
|
|
1010
|
+
return value === null || value === undefined ? null : String(value);
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Loads every organic key joined to its related-entity rows, for {@link PlanOrganicKeyRetraction}.
|
|
1014
|
+
* Null when no additionalSchemaInfo is loaded (nothing to retract) or the query fails (the
|
|
1015
|
+
* retraction pass then leaves organic keys alone).
|
|
1016
|
+
*/
|
|
1017
|
+
async loadOrganicKeyStateForRetraction(pool) {
|
|
1018
|
+
if (!ManageMetadataBase.GetSoftPKFKConfig()) {
|
|
1019
|
+
return null;
|
|
1020
|
+
}
|
|
1021
|
+
try {
|
|
1022
|
+
const schema = MjCoreSchema();
|
|
1023
|
+
const q = (alias, column) => `${alias}.${this.qi(column)}`;
|
|
1024
|
+
const sql = `SELECT ${q('k', 'ID')} AS ${this.qi('KeyID')}, ${q('k', 'Name')} AS ${this.qi('KeyName')}, ${q('k', 'Source')} AS ${this.qi('KeySource')},
|
|
1025
|
+
${q('k', 'EntityID')} AS ${this.qi('EntityID')}, ${q('e', 'Name')} AS ${this.qi('EntityName')},
|
|
1026
|
+
${q('e', 'SchemaName')} AS ${this.qi('SchemaName')}, ${q('e', 'BaseTable')} AS ${this.qi('BaseTable')},
|
|
1027
|
+
${q('r', 'ID')} AS ${this.qi('RelatedRowID')}, ${q('r', 'RelatedEntityID')} AS ${this.qi('RelatedEntityID')},
|
|
1028
|
+
${q('re', 'Name')} AS ${this.qi('RelatedEntityName')}, ${q('re', 'SchemaName')} AS ${this.qi('RelatedSchemaName')},
|
|
1029
|
+
${q('re', 'BaseTable')} AS ${this.qi('RelatedBaseTable')}, ${q('r', 'TransitiveObjectName')} AS ${this.qi('TransitiveObjectName')}
|
|
1030
|
+
FROM ${this.qs(schema, 'EntityOrganicKey')} k
|
|
1031
|
+
INNER JOIN ${this.qs(schema, 'Entity')} e ON ${q('e', 'ID')} = ${q('k', 'EntityID')}
|
|
1032
|
+
LEFT OUTER JOIN ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} r ON ${q('r', 'EntityOrganicKeyID')} = ${q('k', 'ID')}
|
|
1033
|
+
LEFT OUTER JOIN ${this.qs(schema, 'Entity')} re ON ${q('re', 'ID')} = ${q('r', 'RelatedEntityID')}
|
|
1034
|
+
ORDER BY ${q('k', 'EntityID')}, ${q('k', 'Name')}, ${q('r', 'Sequence')}, ${q('r', 'ID')}`;
|
|
1035
|
+
const result = await this.runQuery(pool, sql);
|
|
1036
|
+
return result.recordset.map((row) => ({
|
|
1037
|
+
KeyID: String(row.KeyID),
|
|
1038
|
+
KeyName: String(row.KeyName),
|
|
1039
|
+
KeySource: String(row.KeySource),
|
|
1040
|
+
EntityID: String(row.EntityID),
|
|
1041
|
+
EntityName: String(row.EntityName),
|
|
1042
|
+
SchemaName: String(row.SchemaName),
|
|
1043
|
+
BaseTable: String(row.BaseTable),
|
|
1044
|
+
RelatedRowID: this.optionalText(row.RelatedRowID),
|
|
1045
|
+
RelatedEntityID: this.optionalText(row.RelatedEntityID),
|
|
1046
|
+
RelatedEntityName: this.optionalText(row.RelatedEntityName),
|
|
1047
|
+
RelatedSchemaName: this.optionalText(row.RelatedSchemaName),
|
|
1048
|
+
RelatedBaseTable: this.optionalText(row.RelatedBaseTable),
|
|
1049
|
+
TransitiveObjectName: this.optionalText(row.TransitiveObjectName),
|
|
1050
|
+
}));
|
|
1051
|
+
}
|
|
1052
|
+
catch (e) {
|
|
1053
|
+
logError(` > Could not load organic keys for the retraction pass; organic keys are left alone this run: ${e instanceof Error ? e.message : String(e)}`);
|
|
1054
|
+
return null;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
/** Every entity, as far as matching config entries and spotting a view that backs an entity needs. */
|
|
1058
|
+
async loadEntityRefsForRetraction(pool) {
|
|
1059
|
+
const sql = `SELECT ${this.qi('ID')}, ${this.qi('Name')}, ${this.qi('SchemaName')}, ${this.qi('BaseTable')}, ${this.qi('BaseView')}
|
|
1060
|
+
FROM ${this.qs(MjCoreSchema(), 'Entity')}`;
|
|
1061
|
+
const result = await this.runQuery(pool, sql);
|
|
1062
|
+
return result.recordset.map((row) => ({
|
|
1063
|
+
ID: String(row.ID),
|
|
1064
|
+
Name: String(row.Name),
|
|
1065
|
+
SchemaName: String(row.SchemaName),
|
|
1066
|
+
BaseTable: String(row.BaseTable),
|
|
1067
|
+
BaseView: this.optionalText(row.BaseView),
|
|
1068
|
+
}));
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Fields CodeGen set as soft foreign keys. External-data-source entities are left out: their soft
|
|
1072
|
+
* FKs come from introspecting the remote schema, not from the file.
|
|
1073
|
+
*/
|
|
1074
|
+
async loadSoftForeignKeyFieldsForRetraction(pool) {
|
|
1075
|
+
const schema = MjCoreSchema();
|
|
1076
|
+
const q = (alias, column) => `${alias}.${this.qi(column)}`;
|
|
1077
|
+
const externalClause = (await this.entityHasExternalDataSourceColumn(pool))
|
|
1078
|
+
? ` AND ${q('e', 'ExternalDataSourceID')} IS NULL`
|
|
1079
|
+
: '';
|
|
1080
|
+
const sql = `SELECT ${q('e', 'ID')} AS ${this.qi('EntityID')}, ${q('e', 'Name')} AS ${this.qi('EntityName')},
|
|
1081
|
+
${q('e', 'SchemaName')} AS ${this.qi('SchemaName')}, ${q('e', 'BaseTable')} AS ${this.qi('BaseTable')},
|
|
1082
|
+
${q('ef', 'Name')} AS ${this.qi('FieldName')}, ${q('re', 'Name')} AS ${this.qi('RelatedEntityName')},
|
|
1083
|
+
${q('re', 'SchemaName')} AS ${this.qi('RelatedSchemaName')}, ${q('re', 'BaseTable')} AS ${this.qi('RelatedBaseTable')}
|
|
1084
|
+
FROM ${this.qs(schema, 'EntityField')} ef
|
|
1085
|
+
INNER JOIN ${this.qs(schema, 'vwEntities')} e ON ${q('e', 'ID')} = ${q('ef', 'EntityID')}
|
|
1086
|
+
LEFT OUTER JOIN ${this.qs(schema, 'vwEntities')} re ON ${q('re', 'ID')} = ${q('ef', 'RelatedEntityID')}
|
|
1087
|
+
WHERE ${q('ef', 'IsSoftForeignKey')} = ${this.boolLit(true)}${externalClause}
|
|
1088
|
+
ORDER BY ${q('e', 'Name')}, ${q('ef', 'Name')}`;
|
|
1089
|
+
const result = await this.runQuery(pool, sql);
|
|
1090
|
+
return result.recordset.map((row) => ({
|
|
1091
|
+
EntityID: String(row.EntityID),
|
|
1092
|
+
EntityName: String(row.EntityName),
|
|
1093
|
+
SchemaName: String(row.SchemaName),
|
|
1094
|
+
BaseTable: String(row.BaseTable),
|
|
1095
|
+
FieldName: String(row.FieldName),
|
|
1096
|
+
RelatedEntityName: this.optionalText(row.RelatedEntityName),
|
|
1097
|
+
RelatedSchemaName: this.optionalText(row.RelatedSchemaName),
|
|
1098
|
+
RelatedBaseTable: this.optionalText(row.RelatedBaseTable),
|
|
1099
|
+
}));
|
|
1100
|
+
}
|
|
1101
|
+
/** Fields holding value-list rows CodeGen wrote from the file (`Source = 'Config'`). */
|
|
1102
|
+
async loadConfigValueListFieldsForRetraction(pool) {
|
|
1103
|
+
const schema = MjCoreSchema();
|
|
1104
|
+
const q = (alias, column) => `${alias}.${this.qi(column)}`;
|
|
1105
|
+
const sql = `SELECT ${q('e', 'ID')} AS ${this.qi('EntityID')}, ${q('e', 'Name')} AS ${this.qi('EntityName')},
|
|
1106
|
+
${q('e', 'SchemaName')} AS ${this.qi('SchemaName')}, ${q('e', 'BaseTable')} AS ${this.qi('BaseTable')},
|
|
1107
|
+
${q('ef', 'Name')} AS ${this.qi('FieldName')}, COUNT(*) AS ${this.qi('ConfigValueCount')}
|
|
1108
|
+
FROM ${this.qs(schema, 'EntityFieldValue')} efv
|
|
1109
|
+
INNER JOIN ${this.qs(schema, 'EntityField')} ef ON ${q('ef', 'ID')} = ${q('efv', 'EntityFieldID')}
|
|
1110
|
+
INNER JOIN ${this.qs(schema, 'Entity')} e ON ${q('e', 'ID')} = ${q('ef', 'EntityID')}
|
|
1111
|
+
WHERE ${q('efv', 'Source')} = 'Config'
|
|
1112
|
+
GROUP BY ${q('e', 'ID')}, ${q('e', 'Name')}, ${q('e', 'SchemaName')}, ${q('e', 'BaseTable')}, ${q('ef', 'Name')}
|
|
1113
|
+
ORDER BY ${q('e', 'Name')}, ${q('ef', 'Name')}`;
|
|
1114
|
+
const result = await this.runQuery(pool, sql);
|
|
1115
|
+
return result.recordset.map((row) => ({
|
|
1116
|
+
EntityID: String(row.EntityID),
|
|
1117
|
+
EntityName: String(row.EntityName),
|
|
1118
|
+
SchemaName: String(row.SchemaName),
|
|
1119
|
+
BaseTable: String(row.BaseTable),
|
|
1120
|
+
FieldName: String(row.FieldName),
|
|
1121
|
+
// PostgreSQL returns COUNT(*) as bigint, which the pg driver delivers as a string
|
|
1122
|
+
ConfigValueCount: Number(row.ConfigValueCount),
|
|
1123
|
+
}));
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Works out what the file no longer declares. Only entities whose table the file still lists are
|
|
1127
|
+
* considered, and only rows CodeGen wrote from the file.
|
|
1128
|
+
* @param organicKeysBefore organic key state before this run's config pass; null skips organic keys
|
|
1129
|
+
*/
|
|
1130
|
+
async buildConfigRetractionPlan(pool, config, organicKeysBefore) {
|
|
1131
|
+
const entities = await this.loadEntityRefsForRetraction(pool);
|
|
1132
|
+
// Soft keys: table entries and VirtualEntities entries, resolved on schema + table like the writer.
|
|
1133
|
+
const listed = new Set();
|
|
1134
|
+
const declaredForeignKeys = new Set();
|
|
1135
|
+
for (const table of [...this.extractTablesFromConfig(config), ...this.virtualEntityConfigsAsTableConfigs(config)]) {
|
|
1136
|
+
const entity = ResolveConfigEntity(entities, table.SchemaName, table.TableName, false);
|
|
1137
|
+
if (!entity) {
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
1140
|
+
listed.add(NormalizeKey(entity.ID));
|
|
1141
|
+
for (const fk of table.ForeignKeys ?? []) {
|
|
1142
|
+
declaredForeignKeys.add(FieldKey(entity.ID, fk.FieldName));
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
const declaredValueLists = new Set();
|
|
1146
|
+
for (const [schemaTable, fields] of this.extractFieldValueLists(config)) {
|
|
1147
|
+
const dot = schemaTable.indexOf('.');
|
|
1148
|
+
const entity = ResolveConfigEntity(entities, schemaTable.slice(0, dot), schemaTable.slice(dot + 1), false);
|
|
1149
|
+
if (!entity) {
|
|
1150
|
+
continue;
|
|
1151
|
+
}
|
|
1152
|
+
listed.add(NormalizeKey(entity.ID));
|
|
1153
|
+
for (const f of fields) {
|
|
1154
|
+
declaredValueLists.add(FieldKey(entity.ID, f.FieldName));
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
const softForeignKeys = SelectUndeclaredFields(await this.loadSoftForeignKeyFieldsForRetraction(pool), listed, declaredForeignKeys);
|
|
1158
|
+
const valueLists = SelectUndeclaredFields(await this.loadConfigValueListFieldsForRetraction(pool), listed, declaredValueLists);
|
|
1159
|
+
let organicKeys = { Keys: [], RelatedRows: [], BridgeObjects: [] };
|
|
1160
|
+
const organicKeysAfter = organicKeysBefore ? await this.loadOrganicKeyStateForRetraction(pool) : null;
|
|
1161
|
+
if (organicKeysBefore && organicKeysAfter) {
|
|
1162
|
+
// Organic keys resolve their tables the way processOrganicKeyConfig does: by table, else by entity name.
|
|
1163
|
+
const organicListed = new Set(listed);
|
|
1164
|
+
const declaredKeys = [];
|
|
1165
|
+
const declaredTransitiveObjects = new Set();
|
|
1166
|
+
for (const tableConfig of this.extractOrganicKeysFromConfig(config)) {
|
|
1167
|
+
const owner = ResolveConfigEntity(entities, tableConfig.SchemaName, tableConfig.TableName, true);
|
|
1168
|
+
if (owner) {
|
|
1169
|
+
organicListed.add(NormalizeKey(owner.ID));
|
|
1170
|
+
}
|
|
1171
|
+
for (const ok of tableConfig.OrganicKeys) {
|
|
1172
|
+
let relatedIDs = new Set();
|
|
1173
|
+
for (const re of ok.RelatedEntities) {
|
|
1174
|
+
if (re.TransitiveView) {
|
|
1175
|
+
declaredTransitiveObjects.add(NormalizeObjectName(`${re.TransitiveView.SchemaName || re.SchemaName}.${re.TransitiveView.Name}`));
|
|
1176
|
+
}
|
|
1177
|
+
if (re.TransitiveObject) {
|
|
1178
|
+
declaredTransitiveObjects.add(NormalizeObjectName(re.TransitiveObject));
|
|
1179
|
+
}
|
|
1180
|
+
const related = ResolveConfigEntity(entities, re.SchemaName, re.TableName, true);
|
|
1181
|
+
if (!related) {
|
|
1182
|
+
relatedIDs = null;
|
|
1183
|
+
}
|
|
1184
|
+
else if (relatedIDs) {
|
|
1185
|
+
relatedIDs.add(NormalizeKey(related.ID));
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
if (owner) {
|
|
1189
|
+
declaredKeys.push({ EntityID: owner.ID, Name: ok.Name, RelatedEntityIDs: relatedIDs });
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
organicKeys = PlanOrganicKeyRetraction({
|
|
1194
|
+
Before: organicKeysBefore,
|
|
1195
|
+
After: organicKeysAfter,
|
|
1196
|
+
ListedEntityIDs: organicListed,
|
|
1197
|
+
Declared: declaredKeys,
|
|
1198
|
+
DeclaredTransitiveObjects: declaredTransitiveObjects,
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
return {
|
|
1202
|
+
SoftForeignKeys: softForeignKeys,
|
|
1203
|
+
ValueLists: valueLists,
|
|
1204
|
+
OrganicKeys: organicKeys,
|
|
1205
|
+
BridgeViews: await this.resolveDroppableBridgeViews(pool, organicKeys.BridgeObjects, entities),
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* The bridge objects that can be dropped: views (a table is never dropped) that exist and do not
|
|
1210
|
+
* back an entity. The rest are reported and left in place.
|
|
1211
|
+
*/
|
|
1212
|
+
async resolveDroppableBridgeViews(pool, bridgeObjects, entities) {
|
|
1213
|
+
const views = [];
|
|
1214
|
+
for (const objectName of bridgeObjects) {
|
|
1215
|
+
const parsed = ParseObjectName(objectName);
|
|
1216
|
+
if (!parsed) {
|
|
1217
|
+
logStatus(` Bridge object "${objectName}" is no longer used but names no schema — left in place`);
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
const schema = NormalizeKey(parsed.SchemaName);
|
|
1221
|
+
const name = NormalizeKey(parsed.ObjectName);
|
|
1222
|
+
const backsEntity = entities.some(e => NormalizeKey(e.SchemaName) === schema &&
|
|
1223
|
+
(NormalizeKey(e.BaseTable) === name || NormalizeKey(e.BaseView) === name));
|
|
1224
|
+
if (backsEntity) {
|
|
1225
|
+
logStatus(` Bridge object ${objectName} is no longer used by an organic key but backs an entity — left in place`);
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
const exists = await this.runQueryWithParams(pool, this.dbProvider.getViewExistsSQL(), { ViewName: parsed.ObjectName, SchemaName: parsed.SchemaName });
|
|
1229
|
+
if (exists.recordset.length === 0) {
|
|
1230
|
+
continue; // already gone, or a table: nothing to drop
|
|
1231
|
+
}
|
|
1232
|
+
views.push({ SchemaName: parsed.SchemaName, ViewName: parsed.ObjectName });
|
|
1233
|
+
}
|
|
1234
|
+
return views;
|
|
1235
|
+
}
|
|
1236
|
+
/** One line per item in the plan, for the run log. */
|
|
1237
|
+
describeConfigRetractionPlan(plan, applying) {
|
|
1238
|
+
const verb = applying ? 'Removing' : 'Would remove';
|
|
1239
|
+
const lines = [];
|
|
1240
|
+
for (const fk of plan.SoftForeignKeys) {
|
|
1241
|
+
lines.push(`${verb} soft FK ${fk.SchemaName}.${fk.BaseTable}.${fk.FieldName} → ${fk.RelatedEntityName ?? '(missing entity)'}`);
|
|
1242
|
+
}
|
|
1243
|
+
for (const vl of plan.ValueLists) {
|
|
1244
|
+
lines.push(`${verb} value list of ${vl.SchemaName}.${vl.BaseTable}.${vl.FieldName} (${vl.ConfigValueCount} value${vl.ConfigValueCount === 1 ? '' : 's'})`);
|
|
1245
|
+
}
|
|
1246
|
+
for (const key of plan.OrganicKeys.Keys) {
|
|
1247
|
+
lines.push(`${verb} organic key "${key.KeyName}" on ${key.EntityName}, with its related entities`);
|
|
1248
|
+
}
|
|
1249
|
+
for (const row of plan.OrganicKeys.RelatedRows) {
|
|
1250
|
+
lines.push(`${verb} related entity ${row.RelatedEntityName ?? row.RelatedEntityID} from organic key "${row.KeyName}" on ${row.EntityName}`);
|
|
1251
|
+
}
|
|
1252
|
+
for (const view of plan.BridgeViews) {
|
|
1253
|
+
lines.push(`${verb} unused bridge view ${view.SchemaName}.${view.ViewName}`);
|
|
1254
|
+
}
|
|
1255
|
+
return lines;
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Retracts what CodeGen wrote from additionalSchemaInfo and the file no longer declares: soft
|
|
1259
|
+
* foreign keys (with their generated relationships), value lists, and organic keys (with their
|
|
1260
|
+
* related entities and bridge views no longer used). Reports the plan on every run; applies it only
|
|
1261
|
+
* when `retractRemovedSoftKeys` is on. Every change goes through the migration log.
|
|
1262
|
+
* @param organicKeysBefore organic key state captured before processOrganicKeyConfig ran
|
|
1263
|
+
*/
|
|
1264
|
+
async retractRemovedConfigDeclarations(pool, organicKeysBefore) {
|
|
1265
|
+
const config = ManageMetadataBase.GetSoftPKFKConfig();
|
|
1266
|
+
if (!config) {
|
|
1267
|
+
return true; // no file, or an unreadable one: never retract on that signal
|
|
1268
|
+
}
|
|
1269
|
+
try {
|
|
1270
|
+
const plan = await this.buildConfigRetractionPlan(pool, config, organicKeysBefore);
|
|
1271
|
+
const applying = configInfo.retractRemovedSoftKeys === true;
|
|
1272
|
+
const lines = this.describeConfigRetractionPlan(plan, applying);
|
|
1273
|
+
if (lines.length === 0) {
|
|
1274
|
+
return true;
|
|
1275
|
+
}
|
|
1276
|
+
for (const line of lines) {
|
|
1277
|
+
logStatus(` ${line}`);
|
|
1278
|
+
}
|
|
1279
|
+
const summary = `${plan.SoftForeignKeys.length} soft FK(s), ${plan.ValueLists.length} value list(s), ` +
|
|
1280
|
+
`${plan.OrganicKeys.Keys.length} organic key(s), ${plan.OrganicKeys.RelatedRows.length} organic-key related entit(ies) ` +
|
|
1281
|
+
`and ${plan.BridgeViews.length} bridge view(s)`;
|
|
1282
|
+
if (!applying) {
|
|
1283
|
+
LogWarning(` additionalSchemaInfo no longer declares ${summary} that CodeGen created from it. ` +
|
|
1284
|
+
`Set retractRemovedSoftKeys: true in mj.config.cjs to remove them.`);
|
|
1285
|
+
return true;
|
|
1286
|
+
}
|
|
1287
|
+
logStatus(` Retracting ${summary} that additionalSchemaInfo no longer declares`);
|
|
1288
|
+
await this.applyConfigRetractionPlan(pool, plan);
|
|
1289
|
+
return true;
|
|
1290
|
+
}
|
|
1291
|
+
catch (e) {
|
|
1292
|
+
logError(` Error retracting declarations removed from additionalSchemaInfo: ${e instanceof Error ? e.message : String(e)}`);
|
|
1293
|
+
return false;
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* Applies a retraction plan. Statements identify rows by entity schema + table and by name rather
|
|
1298
|
+
* than by ID, so the logged migration applies to any database. Bridge views are dropped last, after
|
|
1299
|
+
* nothing references them; a view the database refuses to drop is reported and left in place.
|
|
1300
|
+
*/
|
|
1301
|
+
async applyConfigRetractionPlan(pool, plan) {
|
|
1302
|
+
const schema = MjCoreSchema();
|
|
1303
|
+
const esc = (value) => EscapeSQLString(value);
|
|
1304
|
+
const entityRef = (schemaName, baseTable) => this.entityIdSubquery(esc(baseTable), esc(schemaName));
|
|
1305
|
+
const modifiedEntities = [];
|
|
1306
|
+
for (const fk of plan.SoftForeignKeys) {
|
|
1307
|
+
const child = entityRef(fk.SchemaName, fk.BaseTable);
|
|
1308
|
+
const statements = [];
|
|
1309
|
+
if (fk.RelatedSchemaName && fk.RelatedBaseTable) {
|
|
1310
|
+
statements.push(`DELETE FROM ${this.qs(schema, 'EntityRelationship')}
|
|
1311
|
+
WHERE ${this.qi('EntityID')} = ${entityRef(fk.RelatedSchemaName, fk.RelatedBaseTable)}
|
|
1312
|
+
AND ${this.qi('RelatedEntityID')} = ${child}
|
|
1313
|
+
AND ${this.qi('RelatedEntityJoinField')} = '${esc(fk.FieldName)}'
|
|
1314
|
+
AND ${this.qi('Type')} = 'One To Many'
|
|
1315
|
+
AND ${this.qi('AutoUpdateFromSchema')} = ${this.boolLit(true)}`);
|
|
1316
|
+
}
|
|
1317
|
+
statements.push(`UPDATE ${this.qs(schema, 'EntityField')}
|
|
1318
|
+
SET ${this.qi(EntityInfo.UpdatedAtFieldName)} = ${this.utcNow()},
|
|
1319
|
+
${this.qi('RelatedEntityID')} = NULL,
|
|
1320
|
+
${this.qi('RelatedEntityFieldName')} = NULL,
|
|
1321
|
+
${this.qi('IsSoftForeignKey')} = ${this.boolLit(false)},
|
|
1322
|
+
${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(true)}
|
|
1323
|
+
WHERE ${this.qi('EntityID')} = ${child}
|
|
1324
|
+
AND ${this.qi('Name')} = '${esc(fk.FieldName)}'
|
|
1325
|
+
AND ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)}`);
|
|
1326
|
+
await this.logSQLBatchAndExecute(pool, statements, `Retract soft FK ${fk.SchemaName}.${fk.BaseTable}.${fk.FieldName} removed from additionalSchemaInfo`);
|
|
1327
|
+
modifiedEntities.push(fk.EntityName);
|
|
1328
|
+
}
|
|
1329
|
+
for (const vl of plan.ValueLists) {
|
|
1330
|
+
const entity = entityRef(vl.SchemaName, vl.BaseTable);
|
|
1331
|
+
const fieldID = `(SELECT ${this.qi('ID')} FROM ${this.qs(schema, 'EntityField')} WHERE ${this.qi('EntityID')} = ${entity} AND ${this.qi('Name')} = '${esc(vl.FieldName)}')`;
|
|
1332
|
+
await this.logSQLBatchAndExecute(pool, [
|
|
1333
|
+
`DELETE FROM ${this.qs(schema, 'EntityFieldValue')} WHERE ${this.qi('EntityFieldID')} = ${fieldID} AND ${this.qi('Source')} = 'Config'`,
|
|
1334
|
+
`UPDATE ${this.qs(schema, 'EntityField')} SET ${this.qi('ValueListType')} = 'None'
|
|
1335
|
+
WHERE ${this.qi('EntityID')} = ${entity} AND ${this.qi('Name')} = '${esc(vl.FieldName)}'
|
|
1336
|
+
AND NOT EXISTS (SELECT 1 FROM ${this.qs(schema, 'EntityFieldValue')} efv WHERE efv.${this.qi('EntityFieldID')} = ${this.qi('EntityField')}.${this.qi('ID')})`,
|
|
1337
|
+
], `Retract value list of ${vl.SchemaName}.${vl.BaseTable}.${vl.FieldName} removed from additionalSchemaInfo`);
|
|
1338
|
+
modifiedEntities.push(vl.EntityName);
|
|
1339
|
+
}
|
|
1340
|
+
const keyRef = (row) => `(SELECT ${this.qi('ID')} FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE ${this.qi('EntityID')} = ${entityRef(row.SchemaName, row.BaseTable)} AND ${this.qi('Name')} = '${esc(row.KeyName)}')`;
|
|
1341
|
+
for (const row of plan.OrganicKeys.RelatedRows) {
|
|
1342
|
+
if (!row.RelatedSchemaName || !row.RelatedBaseTable) {
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
await this.logSQLAndExecute(pool, `DELETE FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')}
|
|
1346
|
+
WHERE ${this.qi('EntityOrganicKeyID')} = ${keyRef(row)} AND ${this.qi('RelatedEntityID')} = ${entityRef(row.RelatedSchemaName, row.RelatedBaseTable)}`, `Retract related entity ${row.RelatedEntityName} of organic key "${row.KeyName}" on ${row.EntityName}`);
|
|
1347
|
+
}
|
|
1348
|
+
for (const key of plan.OrganicKeys.Keys) {
|
|
1349
|
+
await this.logSQLBatchAndExecute(pool, [
|
|
1350
|
+
`DELETE FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} WHERE ${this.qi('EntityOrganicKeyID')} = ${keyRef(key)}`,
|
|
1351
|
+
`DELETE FROM ${this.qs(schema, 'EntityOrganicKey')}
|
|
1352
|
+
WHERE ${this.qi('EntityID')} = ${entityRef(key.SchemaName, key.BaseTable)} AND ${this.qi('Name')} = '${esc(key.KeyName)}' AND ${this.qi('Source')} = 'Config'`,
|
|
1353
|
+
], `Retract organic key "${key.KeyName}" on ${key.EntityName}`);
|
|
1354
|
+
}
|
|
1355
|
+
for (const view of plan.BridgeViews) {
|
|
1356
|
+
try {
|
|
1357
|
+
await this.logSQLAndExecute(pool, this.dbProvider.dropObjectSQL('VIEW', view.SchemaName, view.ViewName), `Drop bridge view ${view.SchemaName}.${view.ViewName}, no longer used by any organic key`);
|
|
1358
|
+
}
|
|
1359
|
+
catch (e) {
|
|
1360
|
+
LogWarning(` Could not drop bridge view ${view.SchemaName}.${view.ViewName}; it is left in place: ${e instanceof Error ? e.message : String(e)}`);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
if (modifiedEntities.length > 0) {
|
|
1364
|
+
// Pass 2 re-syncs these entities' fields; the refreshed metadata lets the SQL generation
|
|
1365
|
+
// that follows drop the retracted joins from their base views.
|
|
1366
|
+
ManageMetadataBase.AddNewEntitiesToModifiedList(modifiedEntities);
|
|
1367
|
+
await this.refreshMetadataAfterRetraction();
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/** Reloads the metadata cache after retracted soft FKs or value lists changed field metadata. */
|
|
1371
|
+
async refreshMetadataAfterRetraction() {
|
|
1372
|
+
const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
|
|
1373
|
+
await md.Refresh();
|
|
1374
|
+
}
|
|
1003
1375
|
/**
|
|
1004
1376
|
* Builds the entity lookup behind {@link processISARelationshipConfig}: match on Name first, else
|
|
1005
1377
|
* on BaseTable, optionally constrained to a schema.
|
|
@@ -2282,7 +2654,9 @@ export class ManageMetadataBase {
|
|
|
2282
2654
|
logStatus(` > Updated attributes on ${entityConfigResult.updatedCount} entit${entityConfigResult.updatedCount === 1 ? 'y' : 'ies'} from config`);
|
|
2283
2655
|
}
|
|
2284
2656
|
// Config-driven organic key setup — create bridge views and upsert organic key metadata
|
|
2285
|
-
// Must run AFTER entities exist
|
|
2657
|
+
// Must run AFTER entities exist. The state before it runs is kept for the retraction pass
|
|
2658
|
+
// below: a related row the pass reshapes in place loses the bridge view it referenced.
|
|
2659
|
+
const organicKeysBeforeConfig = await this.loadOrganicKeyStateForRetraction(pool);
|
|
2286
2660
|
const organicKeyResult = await this.processOrganicKeyConfig(pool);
|
|
2287
2661
|
if (organicKeyResult.createdCount > 0 || organicKeyResult.updatedCount > 0) {
|
|
2288
2662
|
logStatus(` > Organic keys: ${organicKeyResult.createdCount} created, ${organicKeyResult.updatedCount} updated from config`);
|
|
@@ -2291,6 +2665,12 @@ export class ManageMetadataBase {
|
|
|
2291
2665
|
logError(` Error processing organic keys: ${organicKeyResult.failedCount} key(s) failed and were not applied — see the errors above`);
|
|
2292
2666
|
bSuccess = false;
|
|
2293
2667
|
}
|
|
2668
|
+
// Soft FKs, value lists and organic keys that CodeGen wrote from additionalSchemaInfo and the
|
|
2669
|
+
// file no longer declares: reported, or removed when retractRemovedSoftKeys is on (#4535).
|
|
2670
|
+
if (!await this.retractRemovedConfigDeclarations(pool, organicKeysBeforeConfig)) {
|
|
2671
|
+
logError(' Error retracting declarations removed from additionalSchemaInfo — see the errors above');
|
|
2672
|
+
bSuccess = false;
|
|
2673
|
+
}
|
|
2294
2674
|
// Config-driven base-view materialization — emit the physical table + wrapper view and
|
|
2295
2675
|
// attach an "MJ: Materialized Results" row to the existing entity. Runs AFTER entity fields
|
|
2296
2676
|
// are managed so the snapshot shape reflects the current base view (plan §4.1).
|
|
@@ -4321,6 +4701,14 @@ export class ManageMetadataBase {
|
|
|
4321
4701
|
bSuccess = false;
|
|
4322
4702
|
}
|
|
4323
4703
|
logStatus(` Updated existing entity fields from schema in ${(new Date().getTime() - step3StartTime.getTime()) / 1000} seconds`);
|
|
4704
|
+
// Unique keys as column sets (#4536). Unscoped: an index can be added or dropped without any
|
|
4705
|
+
// column changing, so the entity would not be in this pass's filter. One catalog read.
|
|
4706
|
+
const stepUniqueKeysStartTime = new Date();
|
|
4707
|
+
if (!await this.syncEntityUniqueKeys(pool, excludeSchemas)) {
|
|
4708
|
+
logError('Error syncing entity unique keys from schema');
|
|
4709
|
+
bSuccess = false;
|
|
4710
|
+
}
|
|
4711
|
+
logStatus(` Synced entity unique keys from schema in ${(new Date().getTime() - stepUniqueKeysStartTime.getTime()) / 1000} seconds`);
|
|
4324
4712
|
// Apply soft PK/FK configuration if config file exists
|
|
4325
4713
|
const stepConfigStartTime = new Date();
|
|
4326
4714
|
if (!await this.applySoftPKFKConfig(pool)) {
|
|
@@ -4841,8 +5229,9 @@ export class ManageMetadataBase {
|
|
|
4841
5229
|
/**
|
|
4842
5230
|
* Applies soft value-list configuration from Fields[] entries in additionalSchemaInfo.json.
|
|
4843
5231
|
* Runs AFTER manageEntityFieldValuesAndValidatorFunctions() so CHECK-constraint-derived
|
|
4844
|
-
* values are already in the database.
|
|
4845
|
-
*
|
|
5232
|
+
* values are already in the database. A field whose list a CHECK constraint owns is skipped, as
|
|
5233
|
+
* is a field holding a different list that was not written from the file. Rows written here are
|
|
5234
|
+
* stamped `Source = 'Config'`, which is what lets a later run retract them (#4535).
|
|
4846
5235
|
*/
|
|
4847
5236
|
async applyValueListConfig(pool) {
|
|
4848
5237
|
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
@@ -4865,7 +5254,7 @@ export class ManageMetadataBase {
|
|
|
4865
5254
|
totalSkipped += result.skipped;
|
|
4866
5255
|
}
|
|
4867
5256
|
if (totalApplied > 0 || totalSkipped > 0) {
|
|
4868
|
-
logStatus(` Applied ${totalApplied} soft value-list(s), skipped ${totalSkipped} (CHECK
|
|
5257
|
+
logStatus(` Applied ${totalApplied} soft value-list(s), skipped ${totalSkipped} (owned by a CHECK constraint or entered by hand, or field not found)`);
|
|
4869
5258
|
}
|
|
4870
5259
|
return true;
|
|
4871
5260
|
}
|
|
@@ -4875,23 +5264,24 @@ export class ManageMetadataBase {
|
|
|
4875
5264
|
}
|
|
4876
5265
|
}
|
|
4877
5266
|
/**
|
|
4878
|
-
* Applies value-list fields for a single table
|
|
4879
|
-
*
|
|
5267
|
+
* Applies value-list fields for a single table, skipping fields whose list the file does not own
|
|
5268
|
+
* (see {@link applyValueListForField}).
|
|
4880
5269
|
*/
|
|
4881
5270
|
async applyValueListsForTable(pool, schemaName, tableName, fields, allEntityFieldValues) {
|
|
4882
5271
|
const schema = MjCoreSchema();
|
|
4883
5272
|
let applied = 0;
|
|
4884
5273
|
let skipped = 0;
|
|
4885
5274
|
// Look up entity ID
|
|
4886
|
-
const entityLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${schemaName}' AND BaseTable = '${tableName}'`;
|
|
5275
|
+
const entityLookupSQL = `SELECT ID, ${this.qi('Name')} FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${schemaName}' AND BaseTable = '${tableName}'`;
|
|
4887
5276
|
const entityResult = await this.runQuery(pool, entityLookupSQL);
|
|
4888
5277
|
if (entityResult.recordset.length === 0) {
|
|
4889
5278
|
logStatus(` ⚠️ Entity not found for ${schemaName}.${tableName} — skipping soft value-lists`);
|
|
4890
5279
|
return { applied, skipped };
|
|
4891
5280
|
}
|
|
4892
5281
|
const entityId = entityResult.recordset[0].ID;
|
|
5282
|
+
const entityName = entityResult.recordset[0].Name;
|
|
4893
5283
|
for (const fieldCfg of fields) {
|
|
4894
|
-
const fieldResult = await this.applyValueListForField(pool, schema, entityId, schemaName, tableName, fieldCfg, allEntityFieldValues);
|
|
5284
|
+
const fieldResult = await this.applyValueListForField(pool, schema, entityId, entityName, schemaName, tableName, fieldCfg, allEntityFieldValues);
|
|
4895
5285
|
if (fieldResult === 'applied')
|
|
4896
5286
|
applied++;
|
|
4897
5287
|
else
|
|
@@ -4902,7 +5292,7 @@ export class ManageMetadataBase {
|
|
|
4902
5292
|
/**
|
|
4903
5293
|
* Applies value-list config for a single field. Returns 'applied' or 'skipped'.
|
|
4904
5294
|
*/
|
|
4905
|
-
async applyValueListForField(pool, schema, entityId, schemaName, tableName, fieldCfg, allEntityFieldValues) {
|
|
5295
|
+
async applyValueListForField(pool, schema, entityId, entityName, schemaName, tableName, fieldCfg, allEntityFieldValues) {
|
|
4906
5296
|
// Look up EntityField ID
|
|
4907
5297
|
const efSQL = `SELECT ID, ValueListType FROM ${this.qs(schema, 'EntityField')} WHERE EntityID = '${entityId}' AND Name = '${fieldCfg.FieldName}'`;
|
|
4908
5298
|
const efResult = await this.runQuery(pool, efSQL);
|
|
@@ -4912,20 +5302,33 @@ export class ManageMetadataBase {
|
|
|
4912
5302
|
}
|
|
4913
5303
|
const efRecord = efResult.recordset[0];
|
|
4914
5304
|
const entityFieldID = efRecord.ID;
|
|
4915
|
-
// CHECK constraint is authoritative
|
|
4916
|
-
|
|
5305
|
+
// A CHECK constraint is authoritative, and a list someone entered by hand is theirs: the file
|
|
5306
|
+
// writes the list only when it is empty, already the file's, or holds exactly the declared values.
|
|
5307
|
+
const existing = allEntityFieldValues.filter(efv => String(efv.EntityFieldID) === String(entityFieldID));
|
|
4917
5308
|
const currentValueListType = (efRecord.ValueListType || '').trim().toLowerCase();
|
|
4918
|
-
|
|
5309
|
+
const sortedValues = [...fieldCfg.PossibleValues].sort();
|
|
5310
|
+
const action = DecideConfigValueListAction(existing, sortedValues);
|
|
5311
|
+
if (action === 'SkipCheck') {
|
|
4919
5312
|
return 'skipped';
|
|
4920
5313
|
}
|
|
4921
|
-
|
|
4922
|
-
|
|
4923
|
-
|
|
5314
|
+
if (action === 'SkipManual') {
|
|
5315
|
+
logStatus(` ⚠️ ${schemaName}.${tableName}.${fieldCfg.FieldName} has a value list that was not written from additionalSchemaInfo and differs from it — leaving it as it is`);
|
|
5316
|
+
return 'skipped';
|
|
5317
|
+
}
|
|
5318
|
+
// Apply: sync values (stamping them as Config) and set ValueListType. syncEntityFieldValues
|
|
5319
|
+
// matches rows on the field ID exactly as the list was loaded, so pass that value through.
|
|
5320
|
+
const loadedFieldID = existing.length > 0 ? existing[0].EntityFieldID : entityFieldID;
|
|
5321
|
+
let listChanged = await this.syncEntityFieldValues(pool, loadedFieldID, sortedValues, allEntityFieldValues, 'Config');
|
|
4924
5322
|
// Update ValueListType
|
|
4925
5323
|
const newType = fieldCfg.ValueListType;
|
|
4926
5324
|
if (currentValueListType !== newType.toLowerCase()) {
|
|
4927
5325
|
const updateSQL = `UPDATE ${this.qs(schema, 'EntityField')} SET ValueListType='${newType}' WHERE ID='${entityFieldID}'`;
|
|
4928
5326
|
await this.logSQLAndExecute(pool, updateSQL, `Set soft ValueListType='${newType}' for ${schemaName}.${tableName}.${fieldCfg.FieldName}`);
|
|
5327
|
+
listChanged = true;
|
|
5328
|
+
}
|
|
5329
|
+
if (listChanged) {
|
|
5330
|
+
// the generated union / Zod enum for this field changed, so its schema must be re-emitted
|
|
5331
|
+
ManageMetadataBase.AddNewEntitiesToModifiedList([entityName]);
|
|
4929
5332
|
}
|
|
4930
5333
|
logStatus(` ✓ Applied soft value-list for ${tableName}.${fieldCfg.FieldName} (${sortedValues.length} values, type=${newType})`);
|
|
4931
5334
|
return 'applied';
|
|
@@ -5371,47 +5774,40 @@ export class ManageMetadataBase {
|
|
|
5371
5774
|
const newEntityFieldsResult = await this.runQuery(pool, sSQL);
|
|
5372
5775
|
const newEntityFields = newEntityFieldsResult.recordset;
|
|
5373
5776
|
if (newEntityFields.length > 0) {
|
|
5374
|
-
|
|
5375
|
-
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
|
|
5390
|
-
|
|
5391
|
-
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
|
|
5396
|
-
}
|
|
5397
|
-
}
|
|
5398
|
-
for (let i = 0; i < inserts.length; i += CHUNK_SIZE) {
|
|
5399
|
-
const chunk = inserts.slice(i, i + CHUNK_SIZE);
|
|
5400
|
-
try {
|
|
5401
|
-
await this.logSQLBatchAndExecute(pool, chunk, `SQL text to insert ${chunk.length} new entity field(s)`);
|
|
5402
|
-
// an error blows up the transaction (all-or-nothing), which is what we want
|
|
5403
|
-
}
|
|
5404
|
-
catch (e) {
|
|
5405
|
-
// catch for debug context, then let the transaction die
|
|
5406
|
-
logError(`Error inserting new entity field batch (rows ${i}..${i + chunk.length}).`);
|
|
5407
|
-
throw e;
|
|
5408
|
-
}
|
|
5777
|
+
// Not atomic: each chunk below commits on its own. A failed chunk leaves the earlier ones
|
|
5778
|
+
// in place, and a re-run repairs that, since the pending-field SELECT above only returns
|
|
5779
|
+
// columns that have no EntityField row yet.
|
|
5780
|
+
// [Large Schema Series] Batch the per-field INSERTs. Previously this
|
|
5781
|
+
// issued one LogSQLAndExecute — a DB round-trip AND a synchronous
|
|
5782
|
+
// migration-log append — PER field, i.e. ~40k on a 2,000-table
|
|
5783
|
+
// install (~37s). Collect each row's INSERT SQL (unchanged, conflict
|
|
5784
|
+
// guards intact) and flush in chunks through LogSQLBatchAndExecute,
|
|
5785
|
+
// which terminates + joins the statements and sends each chunk as a
|
|
5786
|
+
// single round-trip + single log append while preserving the exact
|
|
5787
|
+
// per-row SQL and the replayable migration-file output. Both dialects.
|
|
5788
|
+
// Batch size is configurable via `metadataInsertBatchSize` (default 250).
|
|
5789
|
+
const CHUNK_SIZE = configInfo.metadataInsertBatchSize ?? 250;
|
|
5790
|
+
const inserts = [];
|
|
5791
|
+
for (let i = 0; i < newEntityFields.length; ++i) {
|
|
5792
|
+
const n = newEntityFields[i];
|
|
5793
|
+
if (n.EntityID !== null && n.EntityID !== undefined && n.EntityID.length > 0) {
|
|
5794
|
+
// need to check for null entity id = that is because the above query can return candidate Entity Fields but the entities may not have been created if the entities
|
|
5795
|
+
// that would have been created violate rules - such as not having an ID column, etc.
|
|
5796
|
+
const newEntityFieldUUID = this.createNewUUID();
|
|
5797
|
+
inserts.push(this.getPendingEntityFieldINSERTSQL(newEntityFieldUUID, n));
|
|
5798
|
+
ManageMetadataBase.registerNewField(n.EntityID, n.FieldName);
|
|
5409
5799
|
}
|
|
5410
|
-
await transaction.commit();
|
|
5411
5800
|
}
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5801
|
+
for (let i = 0; i < inserts.length; i += CHUNK_SIZE) {
|
|
5802
|
+
const chunk = inserts.slice(i, i + CHUNK_SIZE);
|
|
5803
|
+
try {
|
|
5804
|
+
await this.logSQLBatchAndExecute(pool, chunk, `SQL text to insert ${chunk.length} new entity field(s)`);
|
|
5805
|
+
}
|
|
5806
|
+
catch (e) {
|
|
5807
|
+
// catch for debug context, then stop: the remaining chunks are left for a re-run
|
|
5808
|
+
logError(`Error inserting new entity field batch (rows ${i}..${i + chunk.length}).`);
|
|
5809
|
+
throw e;
|
|
5810
|
+
}
|
|
5415
5811
|
}
|
|
5416
5812
|
// if we get here now send a distinct list of the entities that had new fields to the modified entity list
|
|
5417
5813
|
// column in the resultset is called EntityName, we dont have to dedupe them here because the method below
|
|
@@ -5521,6 +5917,43 @@ export class ManageMetadataBase {
|
|
|
5521
5917
|
return false;
|
|
5522
5918
|
}
|
|
5523
5919
|
}
|
|
5920
|
+
/**
|
|
5921
|
+
* Makes `EntityUniqueKey` match the database catalog (#4536): one row per unique index or unique
|
|
5922
|
+
* constraint on each entity's base table, with its key columns in order. Only entities outside
|
|
5923
|
+
* `excludeSchemas` are read or written. See unique-key-sets.ts.
|
|
5924
|
+
*/
|
|
5925
|
+
async syncEntityUniqueKeys(pool, excludeSchemas) {
|
|
5926
|
+
try {
|
|
5927
|
+
const schema = MjCoreSchema();
|
|
5928
|
+
const catalog = await this.runQuery(pool, BuildCatalogUniqueKeyColumnsSQL(this.dialect, schema, excludeSchemas));
|
|
5929
|
+
const storedRes = await this.runQuery(pool, BuildStoredUniqueKeySetsSQL(this.dialect, schema, excludeSchemas));
|
|
5930
|
+
const desired = GroupUniqueKeyColumns(catalog.recordset.map((r) => ({
|
|
5931
|
+
EntityID: String(r.EntityID),
|
|
5932
|
+
IndexName: String(r.IndexName),
|
|
5933
|
+
ColumnName: String(r.ColumnName),
|
|
5934
|
+
KeyOrdinal: Number(r.KeyOrdinal),
|
|
5935
|
+
FilterDefinition: r.FilterDefinition == null ? null : String(r.FilterDefinition),
|
|
5936
|
+
})));
|
|
5937
|
+
const stored = storedRes.recordset.map((r) => ({
|
|
5938
|
+
ID: String(r.ID),
|
|
5939
|
+
EntityID: String(r.EntityID),
|
|
5940
|
+
Name: String(r.Name),
|
|
5941
|
+
FieldNames: String(r.FieldNames),
|
|
5942
|
+
FilterDefinition: r.FilterDefinition == null ? null : String(r.FilterDefinition),
|
|
5943
|
+
}));
|
|
5944
|
+
const changes = DiffUniqueKeySets(desired, stored);
|
|
5945
|
+
const statements = BuildUniqueKeySetSyncSQL(this.dialect, schema, changes, () => uuidv4());
|
|
5946
|
+
if (statements.length > 0) {
|
|
5947
|
+
await this.logSQLBatchAndExecute(pool, statements, `SQL text to sync entity unique keys (${changes.Inserts.length} added, ${changes.Updates.length} updated, ${changes.Deletes.length} removed)`);
|
|
5948
|
+
logStatus(` > Entity unique keys: ${changes.Inserts.length} added, ${changes.Updates.length} updated, ${changes.Deletes.length} removed`);
|
|
5949
|
+
}
|
|
5950
|
+
return true;
|
|
5951
|
+
}
|
|
5952
|
+
catch (e) {
|
|
5953
|
+
logError(`Error syncing entity unique keys: ${e}`);
|
|
5954
|
+
return false;
|
|
5955
|
+
}
|
|
5956
|
+
}
|
|
5524
5957
|
/**
|
|
5525
5958
|
* Syncs SchemaInfo records from database schemas, capturing extended properties as descriptions.
|
|
5526
5959
|
* Creates new SchemaInfo records for schemas that don't exist yet and updates descriptions
|
|
@@ -5862,7 +6295,7 @@ export class ManageMetadataBase {
|
|
|
5862
6295
|
// dropdown reads 1, 2, 10 rather than the lexical 1, 10, 2 — still fully deterministic.
|
|
5863
6296
|
ManageMetadataBase.sortCheckConstraintValues(parsedValues);
|
|
5864
6297
|
// we have parsed values from the check constraint, so sync them with the entity field values
|
|
5865
|
-
await this.syncEntityFieldValues(pool, r.EntityFieldID, parsedValues, allEntityFieldValues);
|
|
6298
|
+
let listChanged = await this.syncEntityFieldValues(pool, r.EntityFieldID, parsedValues, allEntityFieldValues, 'Check');
|
|
5866
6299
|
// finally, make sure the ValueListType column within the EntityField table is set to "List" because for check constraints we only allow the values specified in the list.
|
|
5867
6300
|
// check to see if the ValueListType is already set to "List", if not, update it
|
|
5868
6301
|
const sSQLCheck = `SELECT ValueListType FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ID='${r.EntityFieldID}'`;
|
|
@@ -5871,6 +6304,12 @@ export class ManageMetadataBase {
|
|
|
5871
6304
|
if (checkResult && checkResult.length > 0 && checkResult[0].ValueListType.trim().toLowerCase() !== 'list') {
|
|
5872
6305
|
const sSQL = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')} SET ValueListType='List' WHERE ID='${r.EntityFieldID}'`;
|
|
5873
6306
|
await this.logSQLAndExecute(pool, sSQL, `SQL text to update ValueListType for entity field ID ${r.EntityFieldID}`);
|
|
6307
|
+
listChanged = true;
|
|
6308
|
+
}
|
|
6309
|
+
if (listChanged && r.EntityName) {
|
|
6310
|
+
// a migration that only changes a CHECK value list changes the generated union and
|
|
6311
|
+
// Zod enum, so the entity's schema must be re-emitted even with dirtySchemaOnly (#6207)
|
|
6312
|
+
ManageMetadataBase.AddNewEntitiesToModifiedList([r.EntityName]);
|
|
5874
6313
|
}
|
|
5875
6314
|
}
|
|
5876
6315
|
else {
|
|
@@ -6073,59 +6512,26 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
6073
6512
|
static EntityFieldValueCode(value) {
|
|
6074
6513
|
return value.length <= ManageMetadataBase.EntityFieldValueCodeMaxLength ? value : null;
|
|
6075
6514
|
}
|
|
6076
|
-
|
|
6515
|
+
/**
|
|
6516
|
+
* Makes a field's EntityFieldValue rows match `possibleValues`: deletes the rows not in the list,
|
|
6517
|
+
* inserts the missing ones, and fixes the Sequence of the rest. Every row it leaves behind carries
|
|
6518
|
+
* `source`, so a row of another origin that holds a listed value is claimed by the writer (#4535).
|
|
6519
|
+
* Callers decide beforehand whether they own the list (see {@link DecideConfigValueListAction}).
|
|
6520
|
+
*
|
|
6521
|
+
* The statements for the field are sent as one batch that the database applies atomically (see
|
|
6522
|
+
* {@link AtomicBatchSQL}), so a failure leaves the field's rows as they were.
|
|
6523
|
+
*
|
|
6524
|
+
* @returns true when any row was added, removed, re-sequenced or re-stamped, so the caller can mark
|
|
6525
|
+
* the entity modified: a changed list changes the generated union and Zod enum (#6207). False when
|
|
6526
|
+
* nothing changed or the batch failed (and was rolled back).
|
|
6527
|
+
*/
|
|
6528
|
+
async syncEntityFieldValues(ds, entityFieldID, possibleValues, allEntityFieldValues, source) {
|
|
6077
6529
|
try {
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
// Step 1: for any existing value that is NOT in the list of possible Values, delete it
|
|
6082
|
-
let numRemoved = 0;
|
|
6083
|
-
const transaction = await ds.beginTransaction();
|
|
6084
|
-
try {
|
|
6085
|
-
for (const ev of existingValues) {
|
|
6086
|
-
if (!possibleValues.find(v => v === ev.Value)) {
|
|
6087
|
-
// delete the value from the database
|
|
6088
|
-
const sSQLDelete = `DELETE FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} WHERE ID='${ev.ID}'`;
|
|
6089
|
-
await this.logSQLAndExecute(ds, sSQLDelete, `SQL text to delete entity field value ID ${ev.ID}`);
|
|
6090
|
-
numRemoved++;
|
|
6091
|
-
}
|
|
6092
|
-
}
|
|
6093
|
-
// Step 2: for any possible value that is NOT in the list of existing values, add it
|
|
6094
|
-
let numAdded = 0;
|
|
6095
|
-
for (const v of possibleValues) {
|
|
6096
|
-
if (!existingValues.find((ev) => ev.Value === v)) {
|
|
6097
|
-
// Generate a UUID for this new EntityFieldValue record
|
|
6098
|
-
const newId = uuidv4();
|
|
6099
|
-
// add the value to the database with explicit ID. Code is NULL ("same as Value") when
|
|
6100
|
-
// the value is longer than the Code column; copying it overflowed that column (#2577).
|
|
6101
|
-
const code = ManageMetadataBase.EntityFieldValueCode(v);
|
|
6102
|
-
const sSQLInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
|
|
6103
|
-
(${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
|
|
6104
|
-
VALUES
|
|
6105
|
-
('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${EscapeSQLString(v)}', ${code === null ? 'NULL' : `'${EscapeSQLString(code)}'`}, ${this.utcNow()}, ${this.utcNow()})`;
|
|
6106
|
-
await this.logSQLAndExecute(ds, sSQLInsert, `SQL text to insert entity field value with ID ${newId}`);
|
|
6107
|
-
numAdded++;
|
|
6108
|
-
}
|
|
6109
|
-
}
|
|
6110
|
-
// Step 3: finally, for the existing values that are in the list of possible values, update the sequence to match the order in the possible values list
|
|
6111
|
-
let numUpdated = 0;
|
|
6112
|
-
for (const v of possibleValues) {
|
|
6113
|
-
const ev = existingValues.find((ev) => ev.Value === v);
|
|
6114
|
-
// NOTE: We are using != below for comparing Sequence instead of strict !== in case the
|
|
6115
|
-
// DB returns a string for Sequence instead of a number.
|
|
6116
|
-
if (ev && ev.Sequence != 1 + possibleValues.indexOf(v)) {
|
|
6117
|
-
// update the sequence to match the order in the possible values list, if it doesn't already match
|
|
6118
|
-
const sSQLUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityFieldValue')} SET Sequence=${1 + possibleValues.indexOf(v)} WHERE ID='${ev.ID}'`;
|
|
6119
|
-
await this.logSQLAndExecute(ds, sSQLUpdate, `SQL text to update entity field value sequence`);
|
|
6120
|
-
numUpdated++;
|
|
6121
|
-
}
|
|
6122
|
-
}
|
|
6123
|
-
await transaction.commit();
|
|
6124
|
-
}
|
|
6125
|
-
catch (e) {
|
|
6126
|
-
await transaction.rollback();
|
|
6127
|
-
throw e;
|
|
6530
|
+
const statements = this.entityFieldValueSyncStatements(entityFieldID, possibleValues, allEntityFieldValues, source);
|
|
6531
|
+
if (statements.length === 0) {
|
|
6532
|
+
return false;
|
|
6128
6533
|
}
|
|
6534
|
+
await this.logSQLBatchAndExecuteAtomically(ds, statements, `SQL text to sync ${statements.length} entity field value row(s) for entity field ID ${entityFieldID}`);
|
|
6129
6535
|
return true;
|
|
6130
6536
|
}
|
|
6131
6537
|
catch (e) {
|
|
@@ -6133,6 +6539,54 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
6133
6539
|
return false;
|
|
6134
6540
|
}
|
|
6135
6541
|
}
|
|
6542
|
+
/**
|
|
6543
|
+
* The DELETE, INSERT and UPDATE statements that make a field's EntityFieldValue rows match
|
|
6544
|
+
* `possibleValues` (see {@link syncEntityFieldValues}); empty when the rows already match.
|
|
6545
|
+
*/
|
|
6546
|
+
entityFieldValueSyncStatements(entityFieldID, possibleValues, allEntityFieldValues, source) {
|
|
6547
|
+
const statements = [];
|
|
6548
|
+
const existingValues = allEntityFieldValues.filter(efv => efv.EntityFieldID === entityFieldID);
|
|
6549
|
+
// Step 1: for any existing value that is NOT in the list of possible Values, delete it
|
|
6550
|
+
for (const ev of existingValues) {
|
|
6551
|
+
if (!possibleValues.find(v => v === ev.Value)) {
|
|
6552
|
+
statements.push(`DELETE FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} WHERE ID='${ev.ID}'`);
|
|
6553
|
+
}
|
|
6554
|
+
}
|
|
6555
|
+
// Step 2: for any possible value that is NOT in the list of existing values, add it
|
|
6556
|
+
for (const v of possibleValues) {
|
|
6557
|
+
if (!existingValues.find((ev) => ev.Value === v)) {
|
|
6558
|
+
// Generate a UUID for this new EntityFieldValue record
|
|
6559
|
+
const newId = uuidv4();
|
|
6560
|
+
// add the value to the database with explicit ID. Code is NULL ("same as Value") when
|
|
6561
|
+
// the value is longer than the Code column; copying it overflowed that column (#2577).
|
|
6562
|
+
const code = ManageMetadataBase.EntityFieldValueCode(v);
|
|
6563
|
+
statements.push(`INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
|
|
6564
|
+
(${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('Source')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
|
|
6565
|
+
VALUES
|
|
6566
|
+
('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${EscapeSQLString(v)}', ${code === null ? 'NULL' : `'${EscapeSQLString(code)}'`}, '${source}', ${this.utcNow()}, ${this.utcNow()})`);
|
|
6567
|
+
}
|
|
6568
|
+
}
|
|
6569
|
+
// Step 3: finally, for the existing values that are in the list of possible values, update the sequence to match
|
|
6570
|
+
// the order in the possible values list, and claim the row for this writer if another origin is recorded on it
|
|
6571
|
+
for (const v of possibleValues) {
|
|
6572
|
+
const ev = existingValues.find(ev => ev.Value === v);
|
|
6573
|
+
if (!ev) {
|
|
6574
|
+
continue;
|
|
6575
|
+
}
|
|
6576
|
+
const sets = [];
|
|
6577
|
+
// NOTE: Number() rather than a strict comparison in case the DB returns a string for Sequence.
|
|
6578
|
+
if (Number(ev.Sequence) !== 1 + possibleValues.indexOf(v)) {
|
|
6579
|
+
sets.push(`Sequence=${1 + possibleValues.indexOf(v)}`);
|
|
6580
|
+
}
|
|
6581
|
+
if (ev.Source !== source) {
|
|
6582
|
+
sets.push(`${this.qi('Source')}='${source}'`);
|
|
6583
|
+
}
|
|
6584
|
+
if (sets.length > 0) {
|
|
6585
|
+
statements.push(`UPDATE ${this.qs(MjCoreSchema(), 'EntityFieldValue')} SET ${sets.join(', ')} WHERE ID='${ev.ID}'`);
|
|
6586
|
+
}
|
|
6587
|
+
}
|
|
6588
|
+
return statements;
|
|
6589
|
+
}
|
|
6136
6590
|
/**
|
|
6137
6591
|
* Parses a column-level CHECK constraint into the list of values it permits, or returns null when the
|
|
6138
6592
|
* constraint is not a simple value list (a range, a `LEN()` predicate, a mixed condition, and so on).
|
|
@@ -6514,21 +6968,20 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
6514
6968
|
const newEntities = newEntitiesResult.recordset;
|
|
6515
6969
|
if (newEntities && newEntities.length > 0) {
|
|
6516
6970
|
const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
|
|
6517
|
-
|
|
6518
|
-
//
|
|
6519
|
-
//
|
|
6971
|
+
// Not atomic: each entity's writes commit as they run, so a failure part-way leaves the
|
|
6972
|
+
// entities before it in place. A re-run repairs that: the SELECT above only returns tables
|
|
6973
|
+
// that have no entity yet.
|
|
6974
|
+
// The in-run list of new entity names is process-static. Names pushed by a batch that then
|
|
6975
|
+
// fails must not survive into the next run of the same process (in-process CodeGen runs
|
|
6520
6976
|
// many times per process), or every one of them reads as "taken" and gets a schema suffix.
|
|
6521
6977
|
const newEntityNamesBefore = ManageMetadataBase.newEntityList.length;
|
|
6522
6978
|
try {
|
|
6523
|
-
// wrap in a transaction so we get all of it or none of it
|
|
6524
6979
|
for (let i = 0; i < newEntities.length; ++i) {
|
|
6525
6980
|
// process each of the new entities
|
|
6526
6981
|
await this.createNewEntity(pool, newEntities[i], md, currentUser);
|
|
6527
6982
|
}
|
|
6528
|
-
await transaction.commit();
|
|
6529
6983
|
}
|
|
6530
6984
|
catch (e) {
|
|
6531
|
-
await transaction.rollback();
|
|
6532
6985
|
ManageMetadataBase.newEntityList.length = newEntityNamesBefore;
|
|
6533
6986
|
throw e;
|
|
6534
6987
|
}
|
|
@@ -9352,6 +9805,26 @@ WHERE
|
|
|
9352
9805
|
* `undefined` (no execution) when nothing remains.
|
|
9353
9806
|
*/
|
|
9354
9807
|
async logSQLBatchAndExecute(pool, statements, description, isRecurringScript = false, includeBatchSeparator = false, batchSeparator = 'GO') {
|
|
9808
|
+
const terminated = ManageMetadataBase.TerminateStatements(statements);
|
|
9809
|
+
if (terminated.length === 0)
|
|
9810
|
+
return undefined;
|
|
9811
|
+
return await this.logSQLAndExecute(pool, terminated.join('\n'), description, isRecurringScript, includeBatchSeparator, batchSeparator);
|
|
9812
|
+
}
|
|
9813
|
+
/**
|
|
9814
|
+
* Like {@link logSQLBatchAndExecute}, but the database applies the batch all or nothing (see
|
|
9815
|
+
* {@link AtomicBatchSQL}). The migration log gets the plain statements, as before: a migration
|
|
9816
|
+
* already runs as one unit, and a transaction wrapper there would have to survive the
|
|
9817
|
+
* PostgreSQL conversion.
|
|
9818
|
+
*/
|
|
9819
|
+
async logSQLBatchAndExecuteAtomically(pool, statements, description) {
|
|
9820
|
+
const terminated = ManageMetadataBase.TerminateStatements(statements);
|
|
9821
|
+
if (terminated.length === 0)
|
|
9822
|
+
return;
|
|
9823
|
+
const logged = this.qsql(terminated.join('\n'));
|
|
9824
|
+
await SQLLogging.LogSQLAndExecute(pool, logged, description, false, false, undefined, false, ManageMetadataBase.AtomicBatchSQL(logged, DbPlatform()));
|
|
9825
|
+
}
|
|
9826
|
+
/** Each statement trimmed of trailing terminators and re-terminated with one `;`; empty ones dropped. */
|
|
9827
|
+
static TerminateStatements(statements) {
|
|
9355
9828
|
const terminated = [];
|
|
9356
9829
|
for (const s of statements) {
|
|
9357
9830
|
const trimmed = TrimTrailingStatementTerminators(s ?? '');
|
|
@@ -9359,9 +9832,26 @@ WHERE
|
|
|
9359
9832
|
continue;
|
|
9360
9833
|
terminated.push(`${trimmed};`);
|
|
9361
9834
|
}
|
|
9362
|
-
|
|
9363
|
-
|
|
9364
|
-
|
|
9835
|
+
return terminated;
|
|
9836
|
+
}
|
|
9837
|
+
/**
|
|
9838
|
+
* The text that makes a batch of terminated statements apply all or nothing.
|
|
9839
|
+
*
|
|
9840
|
+
* - SQL Server: `SET XACT_ABORT ON`, then an explicit transaction inside TRY/CATCH. The CATCH rolls
|
|
9841
|
+
* back and re-throws, so the caller sees the original error. A client-side timeout is an
|
|
9842
|
+
* attention signal that skips the CATCH; `XACT_ABORT` makes the server roll the transaction back
|
|
9843
|
+
* then, so the pooled connection is not handed to later writes with the transaction still open
|
|
9844
|
+
* (those writes would be undone when the connection closes). The option lasts only for this
|
|
9845
|
+
* call: `query()` runs the text through `sp_executesql`, and a SET there ends with it.
|
|
9846
|
+
* - PostgreSQL: the batch unchanged. Several statements sent in one simple query already run as
|
|
9847
|
+
* one implicit transaction that rolls back on any error; an explicit `BEGIN … COMMIT` there would
|
|
9848
|
+
* instead leave the pooled connection in an aborted transaction after a failure.
|
|
9849
|
+
*/
|
|
9850
|
+
static AtomicBatchSQL(batch, platform) {
|
|
9851
|
+
if (platform === 'postgresql') {
|
|
9852
|
+
return batch;
|
|
9853
|
+
}
|
|
9854
|
+
return `SET XACT_ABORT ON;\nBEGIN TRY\nBEGIN TRANSACTION;\n${batch}\nCOMMIT TRANSACTION;\nEND TRY\nBEGIN CATCH\nIF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;\nTHROW;\nEND CATCH`;
|
|
9365
9855
|
}
|
|
9366
9856
|
}
|
|
9367
9857
|
//# sourceMappingURL=manage-metadata.js.map
|