@memberjunction/codegen-lib 6.2.0-edge.2 → 6.2.0-edge.4

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.
Files changed (62) hide show
  1. package/README.md +13 -0
  2. package/dist/Angular/angular-codegen.d.ts +15 -0
  3. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  4. package/dist/Angular/angular-codegen.js +57 -16
  5. package/dist/Angular/angular-codegen.js.map +1 -1
  6. package/dist/Config/config.d.ts +15 -24
  7. package/dist/Config/config.d.ts.map +1 -1
  8. package/dist/Config/config.js +2 -5
  9. package/dist/Config/config.js.map +1 -1
  10. package/dist/Config/integrity-check-schema.d.ts +22 -0
  11. package/dist/Config/integrity-check-schema.d.ts.map +1 -0
  12. package/dist/Config/integrity-check-schema.js +18 -0
  13. package/dist/Config/integrity-check-schema.js.map +1 -0
  14. package/dist/Database/json-check-validators.d.ts +98 -0
  15. package/dist/Database/json-check-validators.d.ts.map +1 -0
  16. package/dist/Database/json-check-validators.js +196 -0
  17. package/dist/Database/json-check-validators.js.map +1 -0
  18. package/dist/Database/manage-metadata.d.ts +121 -8
  19. package/dist/Database/manage-metadata.d.ts.map +1 -1
  20. package/dist/Database/manage-metadata.js +403 -59
  21. package/dist/Database/manage-metadata.js.map +1 -1
  22. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  23. package/dist/Manifest/GenerateClassRegistrationsManifest.js +7 -4
  24. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  25. package/dist/Misc/advanced_generation.d.ts +42 -0
  26. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  27. package/dist/Misc/advanced_generation.js +50 -0
  28. package/dist/Misc/advanced_generation.js.map +1 -1
  29. package/dist/Misc/entity_subclasses_codegen.d.ts +50 -0
  30. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  31. package/dist/Misc/entity_subclasses_codegen.js +185 -68
  32. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  33. package/dist/Misc/graphql_server_codegen.d.ts.map +1 -1
  34. package/dist/Misc/graphql_server_codegen.js +3 -5
  35. package/dist/Misc/graphql_server_codegen.js.map +1 -1
  36. package/dist/Misc/json-type-model.d.ts +148 -0
  37. package/dist/Misc/json-type-model.d.ts.map +1 -0
  38. package/dist/Misc/json-type-model.js +421 -0
  39. package/dist/Misc/json-type-model.js.map +1 -0
  40. package/dist/Misc/json-type-rules.d.ts +90 -0
  41. package/dist/Misc/json-type-rules.d.ts.map +1 -0
  42. package/dist/Misc/json-type-rules.js +274 -0
  43. package/dist/Misc/json-type-rules.js.map +1 -0
  44. package/dist/Misc/json-type-zod.d.ts +41 -0
  45. package/dist/Misc/json-type-zod.d.ts.map +1 -0
  46. package/dist/Misc/json-type-zod.js +390 -0
  47. package/dist/Misc/json-type-zod.js.map +1 -0
  48. package/dist/Misc/runCommand.d.ts.map +1 -1
  49. package/dist/Misc/runCommand.js +13 -5
  50. package/dist/Misc/runCommand.js.map +1 -1
  51. package/dist/Misc/system_integrity.d.ts +27 -0
  52. package/dist/Misc/system_integrity.d.ts.map +1 -1
  53. package/dist/Misc/system_integrity.js +17 -0
  54. package/dist/Misc/system_integrity.js.map +1 -1
  55. package/dist/Misc/validator-text.d.ts +11 -0
  56. package/dist/Misc/validator-text.d.ts.map +1 -0
  57. package/dist/Misc/validator-text.js +15 -0
  58. package/dist/Misc/validator-text.js.map +1 -0
  59. package/dist/runCodeGen.d.ts.map +1 -1
  60. package/dist/runCodeGen.js +34 -13
  61. package/dist/runCodeGen.js.map +1 -1
  62. package/package.json +29 -29
@@ -13,16 +13,17 @@ import './providers/sqlserver/SQLServerCodeGenProvider.js';
13
13
  import { configInfo, currentWorkingDirectory, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir } from '../Config/config.js';
14
14
  import { CodeNameFromString, EntityFieldInfo, EntityInfo, ExternalDataSourceReadRouter, ExtractActualDefaultValue, LogError, LogStatus, Metadata, RunQuerySQLFilterManager, SeverityType } from "@memberjunction/core";
15
15
  import { MJEntityFieldSchema } from "@memberjunction/core-entities";
16
- import { logError, LogMessage, logStatus, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
16
+ import { logError, LogMessage, logStatus, LogWarning, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
17
17
  import { SQLUtilityBase } from "./sql.js";
18
18
  import { ApplyIncludeSchemaScope } from "./schema-scope.js";
19
19
  import { BuildHealSchemaRoutineParams, GetAuthoredExcludeSchemas, SnapshotAuthoredExcludeSchemas } from "./heal-schema-params.js";
20
+ import { JSON_VALIDATOR_CATEGORY_NAME, ResolveJSONCheckValidators } from "./json-check-validators.js";
20
21
  import { AdvancedGeneration, IsPlausibleEntityName } from "../Misc/advanced_generation.js";
21
22
  import { CodeGenReporter } from "../Misc/codegen-reporter.js";
22
23
  import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
23
24
  import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
24
25
  import { SQLParser } from "@memberjunction/sql-parser";
25
- 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";
26
27
  import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
27
28
  import * as fs from 'fs';
28
29
  import path from 'path';
@@ -469,6 +470,23 @@ export class ManageMetadataBase {
469
470
  }
470
471
  }
471
472
  static { this._generatedValidators = []; }
473
+ static { this._generatedJSONValidators = []; }
474
+ /**
475
+ * Globally scoped translations of the SQL `@CHECK` rules of opted-in JSONTypes, loaded from
476
+ * `__mj.GeneratedCode` (and extended by generation). Consumed when entity subclasses are emitted.
477
+ */
478
+ static get GeneratedJSONValidators() {
479
+ return this._generatedJSONValidators;
480
+ }
481
+ static { this._entitiesWithNewJSONValidators = []; }
482
+ /**
483
+ * Entities bound to a JSONType whose SQL `@CHECK` translation was newly generated this run. Their
484
+ * generated files must be rebuilt even though no column changed, or a full run pays for the
485
+ * translation and then skips emitting it (dirty-schema scoped emit only sees schema changes).
486
+ */
487
+ static get EntitiesWithNewJSONValidators() {
488
+ return this._entitiesWithNewJSONValidators;
489
+ }
472
490
  /**
473
491
  * Globally scoped list of validators that have been generated during the metadata management process.
474
492
  */
@@ -1147,7 +1165,7 @@ export class ManageMetadataBase {
1147
1165
  * Processes Entity attribute configurations from the additionalSchemaInfo config.
1148
1166
  * For each entry in the top-level "Entities" array, looks up the entity by
1149
1167
  * BaseTable + SchemaName and applies any declared attribute updates to the Entity table.
1150
- * Reserved keys (BaseTable, SchemaName) are excluded from the UPDATE statement.
1168
+ * Reserved keys (BaseTable, SchemaName, AutoAddPermissions) are excluded from the UPDATE statement.
1151
1169
  * Must run AFTER entities are created.
1152
1170
  */
1153
1171
  async processEntityConfigs(pool) {
@@ -1159,7 +1177,8 @@ export class ManageMetadataBase {
1159
1177
  return { success: true, updatedCount: 0 };
1160
1178
  let updatedCount = 0;
1161
1179
  const schema = MjCoreSchema();
1162
- const reservedKeys = new Set(['BaseTable', 'SchemaName']);
1180
+ // AutoAddPermissions is a creation-time option, not an Entity column (see resolveCreationTimeAutoAddPermissions).
1181
+ const reservedKeys = new Set(['BaseTable', 'SchemaName', 'AutoAddPermissions']);
1163
1182
  for (const ec of entityConfigs) {
1164
1183
  try {
1165
1184
  // Collect the attribute columns to update (everything except BaseTable/SchemaName)
@@ -3371,12 +3390,12 @@ export class ManageMetadataBase {
3371
3390
  // individually caused a ping-pong bug where multi-FK pairs swapped JoinFields
3372
3391
  // on every CodeGen run.
3373
3392
  const entityPairGroups = this.groupFieldsByEntityPair(entityFields);
3393
+ const relationshipsForPair = ManageMetadataBase.relationshipsByEntityPair(allRelationships);
3374
3394
  let batchSQL = '';
3375
3395
  let batchCount = 0;
3376
3396
  for (const [_pairKey, fkFields] of entityPairGroups) {
3377
3397
  const firstField = fkFields[0];
3378
- const relationships = allRelationships.filter((r) => UUIDsEqual(r.EntityID, firstField.RelatedEntityID) &&
3379
- UUIDsEqual(r.RelatedEntityID, firstField.EntityID));
3398
+ const relationships = relationshipsForPair(firstField.RelatedEntityID, firstField.EntityID);
3380
3399
  if (relationships.length === 0) {
3381
3400
  // No relationships exist for this pair — create one per FK field
3382
3401
  for (const f of fkFields) {
@@ -3465,6 +3484,24 @@ export class ManageMetadataBase {
3465
3484
  }
3466
3485
  return groups;
3467
3486
  }
3487
+ /**
3488
+ * Indexes relationship rows by their (EntityID, RelatedEntityID) pair, so each FK pair finds its
3489
+ * relationships without scanning every relationship in the database. IDs match in any case, and
3490
+ * each pair's rows keep their original order — exactly what a `filter` over the full list returns.
3491
+ */
3492
+ static relationshipsByEntityPair(relationships) {
3493
+ const pairKey = (entityID, relatedEntityID) => `${NormalizeUUID(entityID)}|${NormalizeUUID(relatedEntityID)}`;
3494
+ const byPair = new Map();
3495
+ for (const r of relationships) {
3496
+ const key = pairKey(r.EntityID, r.RelatedEntityID);
3497
+ const group = byPair.get(key);
3498
+ if (group)
3499
+ group.push(r);
3500
+ else
3501
+ byPair.set(key, [r]);
3502
+ }
3503
+ return (entityID, relatedEntityID) => byPair.get(pairKey(entityID, relatedEntityID)) ?? [];
3504
+ }
3468
3505
  /**
3469
3506
  * Handles relationship management for an entire entity pair at once.
3470
3507
  * Matches N FK fields to N existing relationship records using a 1:1 mapping:
@@ -4923,13 +4960,14 @@ export class ManageMetadataBase {
4923
4960
  const emitValidators = skipDBUpdate || ag.featureEnabled('ParseCheckConstraints');
4924
4961
  const columnLevelResults = result.filter((r) => r.EntityFieldID); // get the column level constraints
4925
4962
  const tableLevelResults = result.filter((r) => !r.EntityFieldID); // get the table level constraints
4963
+ const entityFieldsByID = IndexByUUID(allEntityFields);
4926
4964
  for (const r of columnLevelResults) {
4927
4965
  // 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
4928
4966
  if (r.ConstraintDefinition && r.ConstraintDefinition.length > 0) {
4929
4967
  // parse first, then decide whether THIS field should carry the list (bit, PK singleton guards).
4930
- // UUIDsEqual, not ===: PG returns lowercase UUIDs and SQL Server uppercase, and a missed
4931
- // lookup here fails OPEN (the exclusions stop applying), so a case mismatch would be silent.
4932
- const field = allEntityFields.find((f) => UUIDsEqual(f.ID, r.EntityFieldID));
4968
+ // Case-insensitive (the index normalizes IDs), not ===: PG returns lowercase UUIDs and SQL Server
4969
+ // uppercase, and a missed lookup here fails OPEN (the exclusions stop applying), so a case mismatch would be silent.
4970
+ const field = entityFieldsByID.Get(r.EntityFieldID);
4933
4971
  const parsedValues = ManageMetadataBase.valueListForField(field, this.parseCheckConstraintValues(r.ConstraintDefinition, r.ColumnName, r.EntityName));
4934
4972
  if (parsedValues) {
4935
4973
  if (!skipDBUpdate) {
@@ -4979,6 +5017,8 @@ export class ManageMetadataBase {
4979
5017
  }
4980
5018
  // await the completion of all generation promises here
4981
5019
  await Promise.all(generationPromises);
5020
+ // SQL @CHECK rules on opted-in JSONTypes: same load-always / generate-when-allowed contract
5021
+ await this.manageJSONCheckValidators(pool, allEntityFields, currentUser, !skipDBUpdate);
4982
5022
  return true;
4983
5023
  }
4984
5024
  catch (e) {
@@ -4986,6 +5026,73 @@ export class ManageMetadataBase {
4986
5026
  return false;
4987
5027
  }
4988
5028
  }
5029
+ /**
5030
+ * Loads (always) and generates (only when `generateNewCode` and the `ParseCheckConstraints`
5031
+ * feature allow) the TypeScript translations of SQL `@CHECK` rules written on opted-in JSONTypes,
5032
+ * then publishes them on {@link GeneratedJSONValidators} for the entity emitter.
5033
+ *
5034
+ * Failures are logged and never fail the run: a missing translation only means that one rule is
5035
+ * not emitted, which the emitter reports.
5036
+ */
5037
+ async manageJSONCheckValidators(pool, allEntityFields, currentUser, generateNewCode) {
5038
+ try {
5039
+ const store = this.buildJSONCheckStore(pool);
5040
+ const resolved = await ResolveJSONCheckValidators({
5041
+ Fields: allEntityFields,
5042
+ GenerateNew: generateNewCode,
5043
+ Store: store,
5044
+ Translator: this.createJSONCheckTranslator(),
5045
+ CurrentUser: currentUser,
5046
+ ReportError: (message) => logError(message),
5047
+ ReportWarning: (message) => LogWarning(message),
5048
+ });
5049
+ const newTypes = new Set(resolved.filter((r) => r.WasGenerated).map((r) => r.JSONTypeName));
5050
+ const newEntities = allEntityFields.filter((f) => f.JSONType && newTypes.has(f.JSONType.trim())).map((f) => f.Entity);
5051
+ ManageMetadataBase._entitiesWithNewJSONValidators = [...new Set([...ManageMetadataBase._entitiesWithNewJSONValidators, ...newEntities])];
5052
+ const resolvedKeys = new Set(resolved.map((r) => r.Key));
5053
+ ManageMetadataBase._generatedJSONValidators = [
5054
+ ...ManageMetadataBase._generatedJSONValidators.filter((r) => !resolvedKeys.has(r.Key)),
5055
+ ...resolved,
5056
+ ];
5057
+ }
5058
+ catch (e) {
5059
+ logError(`Error resolving JSON @CHECK validators: ${e instanceof Error ? e.message : String(e)}`);
5060
+ }
5061
+ }
5062
+ /** The model-backed translator for SQL `@CHECK` rules; a seam so tests can supply a stub. */
5063
+ createJSONCheckTranslator() {
5064
+ return new AdvancedGeneration();
5065
+ }
5066
+ /** `__mj.GeneratedCode` access for the JSON-validators category. */
5067
+ buildJSONCheckStore(pool) {
5068
+ const lit = (v) => this.dialect.QuoteStringLiteral(v);
5069
+ const codes = this.qs(MjCoreSchema(), 'GeneratedCode');
5070
+ const categories = this.qs(MjCoreSchema(), 'vwGeneratedCodeCategories');
5071
+ const categoryLookup = `(SELECT ${this.qi('ID')} FROM ${categories} WHERE ${this.qi('Name')}=${lit(JSON_VALIDATOR_CATEGORY_NAME)})`;
5072
+ return {
5073
+ LoadCached: async () => {
5074
+ const sql = `SELECT ${this.qi('ID')}, ${this.qi('Source')}, ${this.qi('Name')}, ${this.qi('Code')}, ${this.qi('Description')} FROM ${codes} WHERE ${this.qi('CategoryID')} = ${categoryLookup} AND ${this.qi('Status')}=${lit('Approved')}`;
5075
+ const result = await this.runQuery(pool, sql);
5076
+ return result.recordset.map((r) => ({
5077
+ ID: String(r.ID), Source: String(r.Source), Name: String(r.Name), Code: String(r.Code), Description: r.Description == null ? null : String(r.Description),
5078
+ }));
5079
+ },
5080
+ Persist: async (entry) => {
5081
+ const categoryRows = (await this.runQuery(pool, `SELECT ${this.qi('ID')} FROM ${categories} WHERE ${this.qi('Name')}=${lit(JSON_VALIDATOR_CATEGORY_NAME)}`)).recordset;
5082
+ if (categoryRows.length === 0) {
5083
+ LogWarning(`GeneratedCode category '${JSON_VALIDATOR_CATEGORY_NAME}' does not exist in this database (run 'mj sync push' for metadata/generated-code-categories); the validator generated for '${entry.Key}' is used for this run only and will be regenerated next time`);
5084
+ return;
5085
+ }
5086
+ entry.GeneratedCodeID = uuidv4();
5087
+ // Scoped to Approved exactly like LoadCached: otherwise a non-Approved row with this key makes
5088
+ // every run regenerate (LoadCached misses it) and then skip the insert (this check hits it).
5089
+ const checkQuery = `SELECT 1 FROM ${codes} WHERE ${this.qi('CategoryID')} = ${categoryLookup} AND ${this.qi('Source')} = ${lit(entry.Key)} AND ${this.qi('Status')}=${lit('Approved')}`;
5090
+ const insertSQL = `INSERT INTO ${codes} (${['ID', 'CategoryID', 'GeneratedByModelID', 'GeneratedAt', 'Language', 'Status', 'Source', 'Code', 'Description', 'Name'].map((c) => this.qi(c)).join(', ')})
5091
+ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)}, ${this.utcNow()}, ${lit('TypeScript')}, ${lit('Approved')}, ${lit(entry.Key)}, ${lit(entry.FunctionText)}, ${lit(entry.FunctionDescription)}, ${lit(entry.FunctionName)})`;
5092
+ await this.logSQLAndExecute(pool, `${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};`, `Generated JSON @CHECK validator ${entry.Key}`);
5093
+ },
5094
+ };
5095
+ }
4989
5096
  /**
4990
5097
  * This method will load all generated code from the database - this is intended to be used when you are bypassing managing the metadata.
4991
5098
  * @param pool
@@ -5139,7 +5246,7 @@ export class ManageMetadataBase {
5139
5246
  * back quoted — `([Status]='Active' OR [Status]='Inactive')` — but numeric and `bit` literals come back
5140
5247
  * **unquoted and parenthesized**: `([Level]=(3) OR [Level]=(2) OR [Level]=(1))`. Matching only the quoted
5141
5248
  * form left a numeric IN-list with no value list at all, and so no dropdown in Explorer either (#3978).
5142
- * PostgreSQL's `= ANY (ARRAY[...])` rendering is handled separately, by parsePgArrayConstraint.
5249
+ * PostgreSQL's renderings are handled separately, by parsePostgreSQLConstraint.
5143
5250
  *
5144
5251
  * A single-value list is captured too: `CHECK (Status='Active')` — which is also how SQL Server renders
5145
5252
  * `IN ('Active')` — permits exactly one value, which is a one-item list.
@@ -5151,12 +5258,12 @@ export class ManageMetadataBase {
5151
5258
  // Normalize N'literal' to 'literal' so one pattern handles both.
5152
5259
  // Note: Assuming fieldName does not contain regex special characters; otherwise, it needs to be escaped as well.
5153
5260
  const processedConstraint = constraintDefinition.replace(/(^|[=(\s])N'([^']*)'/g, "$1'$2'");
5154
- // PostgreSQL ANY (ARRAY[...]) pattern:
5155
- // CHECK ((("FieldName")::text = ANY ((ARRAY['Val1'::character varying, 'Val2'::character varying])::text[])))
5156
- // Also handles simpler forms: ("FieldName" = ANY (ARRAY['Val1', 'Val2']))
5157
- const pgArrayValues = this.parsePgArrayConstraint(processedConstraint);
5158
- if (pgArrayValues) {
5159
- return pgArrayValues;
5261
+ // PostgreSQL writes every one of these shapes differently from SQL Server, so it gets its own
5262
+ // anchored parse (#4713). It runs first because a PG definition cannot match the SQL Server
5263
+ // patterns below, and returning null here must NOT fall through to them.
5264
+ const pgValues = this.parsePostgreSQLConstraint(processedConstraint, fieldName);
5265
+ if (pgValues) {
5266
+ return pgValues;
5160
5267
  }
5161
5268
  // Build a regex fragment that matches the field name in any quoting style:
5162
5269
  // [FieldName] (SQL Server) or "FieldName" (PostgreSQL) or bare FieldName
@@ -5213,7 +5320,10 @@ export class ManageMetadataBase {
5213
5320
  if (!parsedValues || !field) {
5214
5321
  return parsedValues;
5215
5322
  }
5216
- if (field.Type?.trim().toLowerCase() === 'bit') {
5323
+ // `bit` on SQL Server, `boolean`/`bool` on PostgreSQL — the same column, the same reasoning.
5324
+ // The PG parser cannot currently produce a boolean list anyway (true/false are neither quoted
5325
+ // nor numeric literals), so that half is a second line of defence rather than load-bearing.
5326
+ if (['bit', 'boolean', 'bool'].includes(field.Type?.trim().toLowerCase() ?? '')) {
5217
5327
  return null;
5218
5328
  }
5219
5329
  if (field.IsPrimaryKey && parsedValues.length === 1) {
@@ -5249,29 +5359,211 @@ export class ManageMetadataBase {
5249
5359
  return inner.endsWith('.') ? inner.slice(0, -1) : inner;
5250
5360
  }
5251
5361
  /**
5252
- * Parses PostgreSQL ANY (ARRAY[...]) CHECK constraint syntax.
5253
- * PG's pg_get_constraintdef() returns constraints like:
5254
- * CHECK ((("Status")::text = ANY ((ARRAY['Confirmed'::character varying, 'Cancelled'::character varying])::text[])))
5255
- * This method extracts the string values from the ARRAY literal.
5362
+ * A PostgreSQL `::type` cast as `pg_get_constraintdef()` writes it — `::text`, `::bigint`,
5363
+ * `::character varying`, `::double precision`, `::text[]`.
5364
+ *
5365
+ * Spelled as explicit space-separated words rather than the obvious `[A-Za-z0-9 ]*`, because that
5366
+ * form lets two quantifiers consume the same run of spaces (`[A-Za-z0-9 ]*` then `\\s*`), which is
5367
+ * polynomial backtracking on input like `::A` followed by many spaces. CodeQL flags it as
5368
+ * js/polynomial-redos, and it is right to: a constraint definition is input this library does not
5369
+ * control. Requiring a letter after every space removes the ambiguity — a run of spaces can be
5370
+ * split exactly one way.
5256
5371
  */
5257
- parsePgArrayConstraint(constraintDefinition) {
5258
- // Match the ARRAY[...] portion, handling optional type casts
5259
- const arrayMatch = constraintDefinition.match(/\bARRAY\s*\[([^\]]+)\]/i);
5260
- if (!arrayMatch) {
5372
+ static { this.PG_CAST = `::[A-Za-z][A-Za-z0-9]*(?: [A-Za-z][A-Za-z0-9]*)*(?:\\[\\])?`; }
5373
+ /**
5374
+ * Parses PostgreSQL's renderings of a value-list CHECK into the values it permits, or null when the
5375
+ * constraint is not a plain value list (#4713 — the other dialect of #3978).
5376
+ *
5377
+ * `pg_get_constraintdef()` writes these shapes, all captured from a live PostgreSQL 16:
5378
+ *
5379
+ * (((s)::text = ANY ((ARRAY['Active'::character varying, ...])::text[]))) multi, varchar
5380
+ * ((level = ANY (ARRAY[1, 2, 3]))) multi, numeric
5381
+ * ((bi = ANY (ARRAY['100000000000'::bigint, (2)::bigint]))) multi, mixed quoting
5382
+ * (((x IS NULL) OR (x = ANY (ARRAY[1, 2])))) nullable
5383
+ * ((one = 7)) / (((s)::text = 'OnlyOne'::text)) single value
5384
+ *
5385
+ * ANCHORED ON PURPOSE, and that is the whole design. The previous version searched for `ARRAY[...]`
5386
+ * anywhere in the definition and read only QUOTED elements, which was safe only by accident: both
5387
+ * `(x <> ALL (ARRAY[1, 2]))` (NOT IN) and `((x = ANY (ARRAY[1, 2])) OR (x > 100))` contain an ARRAY
5388
+ * whose elements are NOT the field's legal values — the first inverts the meaning, the second is a
5389
+ * subset. Reading numeric elements without anchoring the whole constraint would have turned both
5390
+ * into wrong value lists, and a wrong list makes `Validate()` refuse what the database accepts.
5391
+ *
5392
+ * Booleans are excluded by construction: `true`/`false` are neither quoted nor numeric, so an
5393
+ * `ARRAY[true, false]` yields no elements. That matches the `bit` exclusion on SQL Server — the
5394
+ * constraint is vacuous, and a checkbox is not a dropdown.
5395
+ */
5396
+ parsePostgreSQLConstraint(constraintDefinition, fieldName) {
5397
+ // Strip the `CHECK (...)` wrapper pg_get_constraintdef() adds, then any balanced outer parens.
5398
+ const checkMatch = /^\s*CHECK\s*\((.*)\)\s*$/is.exec(constraintDefinition);
5399
+ let body = ManageMetadataBase.stripOuterParens(checkMatch ? checkMatch[1] : constraintDefinition);
5400
+ if (body.length === 0) {
5261
5401
  return null;
5262
5402
  }
5263
- // Extract individual values from the array content
5264
- // Each element looks like: 'Value'::character varying or just 'Value'
5265
- const arrayContent = arrayMatch[1];
5266
- const valueRegex = /'([^']+)'(?:::[^,\]]*)?/g;
5267
- const possibleValues = [];
5268
- let match;
5269
- while ((match = valueRegex.exec(arrayContent)) !== null) {
5270
- if (match[1]) {
5271
- possibleValues.push(match[1]);
5403
+ const field = ManageMetadataBase.escapeForRegex(fieldName);
5404
+ // The left-hand side: the bare column, optionally double-quoted, optionally parenthesized and
5405
+ // cast (`(status)::text`) — which is how PG compares a varchar.
5406
+ const lhs = `\\(?"?${field}"?\\)?(?:${ManageMetadataBase.PG_CAST})?`;
5407
+ // `(x IS NULL) OR <rest>` — the nullable form. Unwrap it and judge <rest> on its own.
5408
+ const nullable = new RegExp(`^\\(?\\s*${lhs}\\s+IS\\s+NULL\\s*\\)?\\s+OR\\s+(.*)$`, 'is').exec(body);
5409
+ if (nullable) {
5410
+ body = ManageMetadataBase.stripOuterParens(nullable[1]);
5411
+ }
5412
+ // Anything still carrying a second condition or a non-equality operator is not a value list.
5413
+ // `<> ALL` is NOT IN; ` OR `/` AND ` means the list is not the whole story. Tested with the
5414
+ // string literals blanked first, so a constraint whose VALUES contain an operator —
5415
+ // `CHECK (op = ANY (ARRAY['<'::text, '>'::text]))` — is judged on its structure, not its data.
5416
+ const structure = body.replace(/'(?:[^']|'')*'/g, "''");
5417
+ if (/\s(OR|AND)\s/i.test(structure) || /<>|!=|>|</.test(structure) || /\bALL\s*\(/i.test(structure)) {
5418
+ return null;
5419
+ }
5420
+ // Multi-value: <lhs> = ANY (ARRAY[ ... ]) (the ARRAY may itself be parenthesized and cast).
5421
+ // The closing bracket is found by matching, not by regex: the varchar form ends `])::text[]`,
5422
+ // so a greedy `.*\]` swallows the cast and a lazy one would break on a value containing `]`.
5423
+ const anyMatch = new RegExp(`^${lhs}\\s*=\\s*ANY\\s*\\(\\s*\\(?\\s*ARRAY\\s*\\[`, 'is').exec(body);
5424
+ if (anyMatch) {
5425
+ const elements = ManageMetadataBase.readToMatchingBracket(body, anyMatch[0].length);
5426
+ return elements === null ? null : ManageMetadataBase.pgArrayElements(elements);
5427
+ }
5428
+ // Single value: <lhs> = <literal>. PG renders `IN (x)` this way, and it permits exactly x.
5429
+ const singleMatch = new RegExp(`^${lhs}\\s*=\\s*(.+)$`, 'is').exec(body);
5430
+ if (singleMatch) {
5431
+ const value = ManageMetadataBase.pgLiteralValue(singleMatch[1]);
5432
+ return value === null ? null : [value];
5433
+ }
5434
+ return null;
5435
+ }
5436
+ /**
5437
+ * Returns the text between an already-consumed `[` and its matching `]`, ignoring brackets that sit
5438
+ * inside quoted literals, or null when the bracket never closes.
5439
+ */
5440
+ static readToMatchingBracket(text, startIndex) {
5441
+ let depth = 1, inQuote = false;
5442
+ for (let i = startIndex; i < text.length; i++) {
5443
+ const ch = text[i];
5444
+ if (inQuote) {
5445
+ if (ch === "'") {
5446
+ if (text[i + 1] === "'")
5447
+ i++;
5448
+ else
5449
+ inQuote = false;
5450
+ }
5451
+ continue;
5452
+ }
5453
+ if (ch === "'")
5454
+ inQuote = true;
5455
+ else if (ch === '[')
5456
+ depth++;
5457
+ else if (ch === ']') {
5458
+ depth--;
5459
+ if (depth === 0) {
5460
+ return text.slice(startIndex, i);
5461
+ }
5272
5462
  }
5273
5463
  }
5274
- return possibleValues.length > 0 ? possibleValues : null;
5464
+ return null;
5465
+ }
5466
+ /**
5467
+ * Splits an ARRAY[...] body into its elements and reads each one's literal value, or returns null
5468
+ * when any element is not a literal this can read (a boolean, a function call, a column reference).
5469
+ * All-or-nothing on purpose: a PARTIAL list is worse than none, because the values it drops are
5470
+ * legal ones that `Validate()` would then refuse. That is the bug this replaces — PG writes
5471
+ * `ARRAY['100000000000'::bigint, (2)::bigint]`, and reading only quoted elements captured the first
5472
+ * value and silently dropped the second.
5473
+ */
5474
+ static pgArrayElements(arrayBody) {
5475
+ const values = [];
5476
+ for (const element of ManageMetadataBase.splitTopLevel(arrayBody)) {
5477
+ const value = ManageMetadataBase.pgLiteralValue(element);
5478
+ if (value === null) {
5479
+ return null;
5480
+ }
5481
+ values.push(value);
5482
+ }
5483
+ return values.length > 0 ? values : null;
5484
+ }
5485
+ /**
5486
+ * Reads one PostgreSQL literal, unwrapping the parentheses and `::type` casts it may be dressed in —
5487
+ * `'Active'::character varying`, `(2)::bigint`, `('1e30'::numeric)::double precision`, `2.25`.
5488
+ * Returns null for anything that is not a quoted or numeric literal, which is what keeps booleans,
5489
+ * function calls and column references out of a value list.
5490
+ */
5491
+ static pgLiteralValue(element) {
5492
+ let text = element.trim();
5493
+ // Peel casts and wrapping parens until neither is left: ('x'::numeric)::double precision
5494
+ for (let i = 0; i < 10; i++) {
5495
+ const castAtEnd = new RegExp(`${ManageMetadataBase.PG_CAST}$`);
5496
+ const stripped = ManageMetadataBase.stripOuterParens(text.replace(castAtEnd, '').trim());
5497
+ if (stripped === text) {
5498
+ break;
5499
+ }
5500
+ text = stripped;
5501
+ }
5502
+ const quoted = /^'((?:[^']|'')*)'$/s.exec(text);
5503
+ if (quoted) {
5504
+ return quoted[1].replace(/''/g, "'");
5505
+ }
5506
+ return /^-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(text) ? text : null;
5507
+ }
5508
+ /** Splits on commas that sit outside quotes, parentheses and brackets. */
5509
+ static splitTopLevel(text) {
5510
+ const parts = [];
5511
+ let depth = 0, inQuote = false, current = '';
5512
+ for (let i = 0; i < text.length; i++) {
5513
+ const ch = text[i];
5514
+ if (inQuote) {
5515
+ inQuote = ch !== "'" || text[i + 1] === "'";
5516
+ if (ch === "'" && text[i + 1] === "'") {
5517
+ current += ch;
5518
+ i++;
5519
+ }
5520
+ }
5521
+ else if (ch === "'") {
5522
+ inQuote = true;
5523
+ }
5524
+ else if (ch === '(' || ch === '[') {
5525
+ depth++;
5526
+ }
5527
+ else if (ch === ')' || ch === ']') {
5528
+ depth--;
5529
+ }
5530
+ else if (ch === ',' && depth === 0) {
5531
+ parts.push(current);
5532
+ current = '';
5533
+ continue;
5534
+ }
5535
+ current += text[i];
5536
+ }
5537
+ if (current.trim().length > 0) {
5538
+ parts.push(current);
5539
+ }
5540
+ return parts;
5541
+ }
5542
+ /** Removes balanced parentheses that wrap the whole expression, however many layers deep. */
5543
+ static stripOuterParens(text) {
5544
+ let result = text.trim();
5545
+ while (result.startsWith('(') && result.endsWith(')')) {
5546
+ let depth = 0, wrapsWhole = true;
5547
+ for (let i = 0; i < result.length; i++) {
5548
+ if (result[i] === '(')
5549
+ depth++;
5550
+ else if (result[i] === ')')
5551
+ depth--;
5552
+ if (depth === 0 && i < result.length - 1) {
5553
+ wrapsWhole = false;
5554
+ break;
5555
+ }
5556
+ }
5557
+ if (!wrapsWhole) {
5558
+ break;
5559
+ }
5560
+ result = result.slice(1, -1).trim();
5561
+ }
5562
+ return result;
5563
+ }
5564
+ /** Escapes regex metacharacters so an identifier can be embedded in a pattern. */
5565
+ static escapeForRegex(value) {
5566
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5275
5567
  }
5276
5568
  createExcludeTablesAndSchemasFilter(fieldPrefix) {
5277
5569
  let sExcludeTables = '';
@@ -5625,7 +5917,11 @@ export class ManageMetadataBase {
5625
5917
  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}'.`);
5626
5918
  }
5627
5919
  // next up, we need to check if we're configured to add permissions for new entities, and if so, add them
5628
- if (configInfo.newEntityDefaults.PermissionDefaults && configInfo.newEntityDefaults.PermissionDefaults.AutoAddPermissionsForNewEntities) {
5920
+ // A per-table `Entities` entry can opt a table out of the default grants (AutoAddPermissions: false),
5921
+ // e.g. a table only server code may touch. Applied here because grants made now would otherwise
5922
+ // have to be removed by a later migration.
5923
+ if (configInfo.newEntityDefaults.PermissionDefaults && configInfo.newEntityDefaults.PermissionDefaults.AutoAddPermissionsForNewEntities
5924
+ && this.resolveCreationTimeAutoAddPermissions(newEntity.SchemaName, newEntity.TableName)) {
5629
5925
  // we are asked to add permissions for new entities, so do that by looping through the permissions and adding them
5630
5926
  const permissions = configInfo.newEntityDefaults.PermissionDefaults.Permissions;
5631
5927
  for (const p of permissions) {
@@ -6244,11 +6540,79 @@ export class ManageMetadataBase {
6244
6540
  ${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)}, 'int', ${this.utcNow()}, ${this.utcNow()}
6245
6541
  )`;
6246
6542
  }
6543
+ /**
6544
+ * Returns the creation-time attribute overrides declared for one table in the additionalSchemaInfo
6545
+ * `Entities` array (matched case-insensitively on SchemaName + BaseTable).
6546
+ *
6547
+ * Applying these at creation — not only in the later {@link processEntityConfigs} pass — matters
6548
+ * for flags CodeGen acts on in the same run. The clearest case is `TrackRecordChanges`:
6549
+ * `ensureCreatedAtUpdatedAtFieldsExist` runs before `processEntityConfigs`, so a table declared
6550
+ * `TrackRecordChanges: false` used to receive `__mj_CreatedAt` / `__mj_UpdatedAt` columns on its
6551
+ * first CodeGen run anyway.
6552
+ *
6553
+ * Only the attributes in {@link EntityInfo.ConfigurableAtCreationAttributes} are returned, and only with a value of the right type
6554
+ * (boolean, or number for `UserViewMaxRows`); anything else is left to `processEntityConfigs`.
6555
+ */
6556
+ resolveCreationTimeEntityConfig(schemaName, tableName) {
6557
+ const config = ManageMetadataBase.getSoftPKFKConfig();
6558
+ if (!config)
6559
+ return {};
6560
+ const match = this.extractEntitiesFromConfig(config).find(ec => ec.SchemaName.trim().toLowerCase() === schemaName.trim().toLowerCase() &&
6561
+ ec.BaseTable.trim().toLowerCase() === tableName.trim().toLowerCase());
6562
+ if (!match)
6563
+ return {};
6564
+ const overrides = {};
6565
+ for (const attr of EntityInfo.ConfigurableAtCreationAttributes) {
6566
+ const value = match[attr];
6567
+ if (attr === 'UserViewMaxRows' ? typeof value === 'number' : typeof value === 'boolean') {
6568
+ overrides[attr] = value;
6569
+ }
6570
+ }
6571
+ return overrides;
6572
+ }
6573
+ /**
6574
+ * Whether CodeGen should grant the default role permissions (`newEntityDefaults.PermissionDefaults`)
6575
+ * when it creates the entity for this table. A per-table `Entities` entry may set
6576
+ * `"AutoAddPermissions": false` for a table that only server code may touch; the entity is then
6577
+ * created with no role permissions at all. Anything other than the boolean `false` keeps the default.
6578
+ */
6579
+ resolveCreationTimeAutoAddPermissions(schemaName, tableName) {
6580
+ const config = ManageMetadataBase.getSoftPKFKConfig();
6581
+ if (!config)
6582
+ return true;
6583
+ const match = this.extractEntitiesFromConfig(config).find(ec => ec.SchemaName.trim().toLowerCase() === schemaName.trim().toLowerCase() &&
6584
+ ec.BaseTable.trim().toLowerCase() === tableName.trim().toLowerCase());
6585
+ return match?.AutoAddPermissions !== false;
6586
+ }
6247
6587
  createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
6248
6588
  const newEntityDefaults = configInfo.newEntityDefaults;
6589
+ const overrides = this.resolveCreationTimeEntityConfig(newEntity.SchemaName, newEntity.TableName);
6249
6590
  const newEntityDescriptionEscaped = newEntity.EntityDescription ? `'${newEntity.EntityDescription.replace(/'/g, "''")}'` : null;
6250
- const allowCaching = this.resolveAllowCachingForSchema(newEntity.SchemaName);
6251
6591
  const q = (name) => this.qi(name);
6592
+ // Effective value for each optional flag: per-table config first, then the global default.
6593
+ // `undefined` leaves the column out of the INSERT so the table default applies.
6594
+ const flag = (attr, globalDefault) => overrides[attr] !== undefined ? overrides[attr] : globalDefault;
6595
+ const literal = (value) => typeof value === 'boolean' ? this.boolLit(value) : String(value);
6596
+ const columns = [
6597
+ ['IncludeInAPI', literal(flag('IncludeInAPI', true))],
6598
+ ['AllowUserSearchAPI', literal(flag('AllowUserSearchAPI', newEntityDefaults.AllowUserSearchAPI ?? true))],
6599
+ ['AllowCaching', literal(flag('AllowCaching', this.resolveAllowCachingForSchema(newEntity.SchemaName)))],
6600
+ ];
6601
+ const optional = [
6602
+ ['TrackRecordChanges', newEntityDefaults.TrackRecordChanges],
6603
+ ['AuditRecordAccess', newEntityDefaults.AuditRecordAccess],
6604
+ ['AuditViewRuns', newEntityDefaults.AuditViewRuns],
6605
+ ['AllowAllRowsAPI', newEntityDefaults.AllowAllRowsAPI],
6606
+ ['AllowCreateAPI', newEntityDefaults.AllowCreateAPI],
6607
+ ['AllowUpdateAPI', newEntityDefaults.AllowUpdateAPI],
6608
+ ['AllowDeleteAPI', newEntityDefaults.AllowDeleteAPI],
6609
+ ['UserViewMaxRows', newEntityDefaults.UserViewMaxRows],
6610
+ ];
6611
+ for (const [attr, globalDefault] of optional) {
6612
+ const value = flag(attr, globalDefault);
6613
+ if (value !== undefined)
6614
+ columns.push([attr, literal(value)]);
6615
+ }
6252
6616
  const sSQLInsert = `
6253
6617
  INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
6254
6618
  ${q('ID')},
@@ -6259,17 +6623,7 @@ export class ManageMetadataBase {
6259
6623
  ${q('BaseTable')},
6260
6624
  ${q('BaseView')},
6261
6625
  ${q('SchemaName')},
6262
- ${q('IncludeInAPI')},
6263
- ${q('AllowUserSearchAPI')},
6264
- ${q('AllowCaching')}
6265
- ${newEntityDefaults.TrackRecordChanges === undefined ? '' : ', ' + q('TrackRecordChanges')}
6266
- ${newEntityDefaults.AuditRecordAccess === undefined ? '' : ', ' + q('AuditRecordAccess')}
6267
- ${newEntityDefaults.AuditViewRuns === undefined ? '' : ', ' + q('AuditViewRuns')}
6268
- ${newEntityDefaults.AllowAllRowsAPI === undefined ? '' : ', ' + q('AllowAllRowsAPI')}
6269
- ${newEntityDefaults.AllowCreateAPI === undefined ? '' : ', ' + q('AllowCreateAPI')}
6270
- ${newEntityDefaults.AllowUpdateAPI === undefined ? '' : ', ' + q('AllowUpdateAPI')}
6271
- ${newEntityDefaults.AllowDeleteAPI === undefined ? '' : ', ' + q('AllowDeleteAPI')}
6272
- ${newEntityDefaults.UserViewMaxRows === undefined ? '' : ', ' + q('UserViewMaxRows')}
6626
+ ${columns.map(([col]) => q(col)).join(',\n ')}
6273
6627
  , ${q('__mj_CreatedAt')}
6274
6628
  , ${q('__mj_UpdatedAt')}
6275
6629
  )
@@ -6282,17 +6636,7 @@ export class ManageMetadataBase {
6282
6636
  '${newEntity.TableName}',
6283
6637
  'vw${generatePluralName(newEntity.TableName, { capitalizeFirstLetterOnly: true }) + (newEntitySuffix && newEntitySuffix.length > 0 ? newEntitySuffix : '')}',
6284
6638
  '${newEntity.SchemaName}',
6285
- ${this.boolLit(true)},
6286
- ${newEntityDefaults.AllowUserSearchAPI === undefined ? this.boolLit(true) : this.boolLit(newEntityDefaults.AllowUserSearchAPI)},
6287
- ${this.boolLit(allowCaching)}
6288
- ${newEntityDefaults.TrackRecordChanges === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.TrackRecordChanges)}
6289
- ${newEntityDefaults.AuditRecordAccess === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AuditRecordAccess)}
6290
- ${newEntityDefaults.AuditViewRuns === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AuditViewRuns)}
6291
- ${newEntityDefaults.AllowAllRowsAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowAllRowsAPI)}
6292
- ${newEntityDefaults.AllowCreateAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowCreateAPI)}
6293
- ${newEntityDefaults.AllowUpdateAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowUpdateAPI)}
6294
- ${newEntityDefaults.AllowDeleteAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowDeleteAPI)}
6295
- ${newEntityDefaults.UserViewMaxRows === undefined ? '' : ', ' + (newEntityDefaults.UserViewMaxRows)}
6639
+ ${columns.map(([, value]) => value).join(',\n ')}
6296
6640
  , ${this.utcNow()}
6297
6641
  , ${this.utcNow()}
6298
6642
  )