@memberjunction/codegen-lib 6.2.0-edge.3 → 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.
@@ -23,7 +23,7 @@ import { CodeGenReporter } from "../Misc/codegen-reporter.js";
23
23
  import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
24
24
  import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
25
25
  import { SQLParser } from "@memberjunction/sql-parser";
26
- import { createDisplayName, EscapeSQLString, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
26
+ import { createDisplayName, EscapeSQLString, generatePluralName, IndexByUUID, MJGlobal, NormalizeUUID, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
27
27
  import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
28
28
  import * as fs from 'fs';
29
29
  import path from 'path';
@@ -1165,7 +1165,7 @@ export class ManageMetadataBase {
1165
1165
  * Processes Entity attribute configurations from the additionalSchemaInfo config.
1166
1166
  * For each entry in the top-level "Entities" array, looks up the entity by
1167
1167
  * BaseTable + SchemaName and applies any declared attribute updates to the Entity table.
1168
- * Reserved keys (BaseTable, SchemaName) are excluded from the UPDATE statement.
1168
+ * Reserved keys (BaseTable, SchemaName, AutoAddPermissions) are excluded from the UPDATE statement.
1169
1169
  * Must run AFTER entities are created.
1170
1170
  */
1171
1171
  async processEntityConfigs(pool) {
@@ -1177,7 +1177,8 @@ export class ManageMetadataBase {
1177
1177
  return { success: true, updatedCount: 0 };
1178
1178
  let updatedCount = 0;
1179
1179
  const schema = MjCoreSchema();
1180
- 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']);
1181
1182
  for (const ec of entityConfigs) {
1182
1183
  try {
1183
1184
  // Collect the attribute columns to update (everything except BaseTable/SchemaName)
@@ -3389,12 +3390,12 @@ export class ManageMetadataBase {
3389
3390
  // individually caused a ping-pong bug where multi-FK pairs swapped JoinFields
3390
3391
  // on every CodeGen run.
3391
3392
  const entityPairGroups = this.groupFieldsByEntityPair(entityFields);
3393
+ const relationshipsForPair = ManageMetadataBase.relationshipsByEntityPair(allRelationships);
3392
3394
  let batchSQL = '';
3393
3395
  let batchCount = 0;
3394
3396
  for (const [_pairKey, fkFields] of entityPairGroups) {
3395
3397
  const firstField = fkFields[0];
3396
- const relationships = allRelationships.filter((r) => UUIDsEqual(r.EntityID, firstField.RelatedEntityID) &&
3397
- UUIDsEqual(r.RelatedEntityID, firstField.EntityID));
3398
+ const relationships = relationshipsForPair(firstField.RelatedEntityID, firstField.EntityID);
3398
3399
  if (relationships.length === 0) {
3399
3400
  // No relationships exist for this pair — create one per FK field
3400
3401
  for (const f of fkFields) {
@@ -3483,6 +3484,24 @@ export class ManageMetadataBase {
3483
3484
  }
3484
3485
  return groups;
3485
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
+ }
3486
3505
  /**
3487
3506
  * Handles relationship management for an entire entity pair at once.
3488
3507
  * Matches N FK fields to N existing relationship records using a 1:1 mapping:
@@ -4941,13 +4960,14 @@ export class ManageMetadataBase {
4941
4960
  const emitValidators = skipDBUpdate || ag.featureEnabled('ParseCheckConstraints');
4942
4961
  const columnLevelResults = result.filter((r) => r.EntityFieldID); // get the column level constraints
4943
4962
  const tableLevelResults = result.filter((r) => !r.EntityFieldID); // get the table level constraints
4963
+ const entityFieldsByID = IndexByUUID(allEntityFields);
4944
4964
  for (const r of columnLevelResults) {
4945
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
4946
4966
  if (r.ConstraintDefinition && r.ConstraintDefinition.length > 0) {
4947
4967
  // parse first, then decide whether THIS field should carry the list (bit, PK singleton guards).
4948
- // UUIDsEqual, not ===: PG returns lowercase UUIDs and SQL Server uppercase, and a missed
4949
- // lookup here fails OPEN (the exclusions stop applying), so a case mismatch would be silent.
4950
- 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);
4951
4971
  const parsedValues = ManageMetadataBase.valueListForField(field, this.parseCheckConstraintValues(r.ConstraintDefinition, r.ColumnName, r.EntityName));
4952
4972
  if (parsedValues) {
4953
4973
  if (!skipDBUpdate) {
@@ -5226,7 +5246,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5226
5246
  * back quoted — `([Status]='Active' OR [Status]='Inactive')` — but numeric and `bit` literals come back
5227
5247
  * **unquoted and parenthesized**: `([Level]=(3) OR [Level]=(2) OR [Level]=(1))`. Matching only the quoted
5228
5248
  * form left a numeric IN-list with no value list at all, and so no dropdown in Explorer either (#3978).
5229
- * PostgreSQL's `= ANY (ARRAY[...])` rendering is handled separately, by parsePgArrayConstraint.
5249
+ * PostgreSQL's renderings are handled separately, by parsePostgreSQLConstraint.
5230
5250
  *
5231
5251
  * A single-value list is captured too: `CHECK (Status='Active')` — which is also how SQL Server renders
5232
5252
  * `IN ('Active')` — permits exactly one value, which is a one-item list.
@@ -5238,12 +5258,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5238
5258
  // Normalize N'literal' to 'literal' so one pattern handles both.
5239
5259
  // Note: Assuming fieldName does not contain regex special characters; otherwise, it needs to be escaped as well.
5240
5260
  const processedConstraint = constraintDefinition.replace(/(^|[=(\s])N'([^']*)'/g, "$1'$2'");
5241
- // PostgreSQL ANY (ARRAY[...]) pattern:
5242
- // CHECK ((("FieldName")::text = ANY ((ARRAY['Val1'::character varying, 'Val2'::character varying])::text[])))
5243
- // Also handles simpler forms: ("FieldName" = ANY (ARRAY['Val1', 'Val2']))
5244
- const pgArrayValues = this.parsePgArrayConstraint(processedConstraint);
5245
- if (pgArrayValues) {
5246
- 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;
5247
5267
  }
5248
5268
  // Build a regex fragment that matches the field name in any quoting style:
5249
5269
  // [FieldName] (SQL Server) or "FieldName" (PostgreSQL) or bare FieldName
@@ -5300,7 +5320,10 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5300
5320
  if (!parsedValues || !field) {
5301
5321
  return parsedValues;
5302
5322
  }
5303
- 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() ?? '')) {
5304
5327
  return null;
5305
5328
  }
5306
5329
  if (field.IsPrimaryKey && parsedValues.length === 1) {
@@ -5336,29 +5359,211 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5336
5359
  return inner.endsWith('.') ? inner.slice(0, -1) : inner;
5337
5360
  }
5338
5361
  /**
5339
- * Parses PostgreSQL ANY (ARRAY[...]) CHECK constraint syntax.
5340
- * PG's pg_get_constraintdef() returns constraints like:
5341
- * CHECK ((("Status")::text = ANY ((ARRAY['Confirmed'::character varying, 'Cancelled'::character varying])::text[])))
5342
- * 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.
5343
5371
  */
5344
- parsePgArrayConstraint(constraintDefinition) {
5345
- // Match the ARRAY[...] portion, handling optional type casts
5346
- const arrayMatch = constraintDefinition.match(/\bARRAY\s*\[([^\]]+)\]/i);
5347
- 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) {
5348
5401
  return null;
5349
5402
  }
5350
- // Extract individual values from the array content
5351
- // Each element looks like: 'Value'::character varying or just 'Value'
5352
- const arrayContent = arrayMatch[1];
5353
- const valueRegex = /'([^']+)'(?:::[^,\]]*)?/g;
5354
- const possibleValues = [];
5355
- let match;
5356
- while ((match = valueRegex.exec(arrayContent)) !== null) {
5357
- if (match[1]) {
5358
- 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
+ }
5359
5462
  }
5360
5463
  }
5361
- 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, '\\$&');
5362
5567
  }
5363
5568
  createExcludeTablesAndSchemasFilter(fieldPrefix) {
5364
5569
  let sExcludeTables = '';
@@ -5712,7 +5917,11 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5712
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}'.`);
5713
5918
  }
5714
5919
  // next up, we need to check if we're configured to add permissions for new entities, and if so, add them
5715
- 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)) {
5716
5925
  // we are asked to add permissions for new entities, so do that by looping through the permissions and adding them
5717
5926
  const permissions = configInfo.newEntityDefaults.PermissionDefaults.Permissions;
5718
5927
  for (const p of permissions) {
@@ -6331,11 +6540,79 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6331
6540
  ${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)}, 'int', ${this.utcNow()}, ${this.utcNow()}
6332
6541
  )`;
6333
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
+ }
6334
6587
  createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
6335
6588
  const newEntityDefaults = configInfo.newEntityDefaults;
6589
+ const overrides = this.resolveCreationTimeEntityConfig(newEntity.SchemaName, newEntity.TableName);
6336
6590
  const newEntityDescriptionEscaped = newEntity.EntityDescription ? `'${newEntity.EntityDescription.replace(/'/g, "''")}'` : null;
6337
- const allowCaching = this.resolveAllowCachingForSchema(newEntity.SchemaName);
6338
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
+ }
6339
6616
  const sSQLInsert = `
6340
6617
  INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
6341
6618
  ${q('ID')},
@@ -6346,17 +6623,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6346
6623
  ${q('BaseTable')},
6347
6624
  ${q('BaseView')},
6348
6625
  ${q('SchemaName')},
6349
- ${q('IncludeInAPI')},
6350
- ${q('AllowUserSearchAPI')},
6351
- ${q('AllowCaching')}
6352
- ${newEntityDefaults.TrackRecordChanges === undefined ? '' : ', ' + q('TrackRecordChanges')}
6353
- ${newEntityDefaults.AuditRecordAccess === undefined ? '' : ', ' + q('AuditRecordAccess')}
6354
- ${newEntityDefaults.AuditViewRuns === undefined ? '' : ', ' + q('AuditViewRuns')}
6355
- ${newEntityDefaults.AllowAllRowsAPI === undefined ? '' : ', ' + q('AllowAllRowsAPI')}
6356
- ${newEntityDefaults.AllowCreateAPI === undefined ? '' : ', ' + q('AllowCreateAPI')}
6357
- ${newEntityDefaults.AllowUpdateAPI === undefined ? '' : ', ' + q('AllowUpdateAPI')}
6358
- ${newEntityDefaults.AllowDeleteAPI === undefined ? '' : ', ' + q('AllowDeleteAPI')}
6359
- ${newEntityDefaults.UserViewMaxRows === undefined ? '' : ', ' + q('UserViewMaxRows')}
6626
+ ${columns.map(([col]) => q(col)).join(',\n ')}
6360
6627
  , ${q('__mj_CreatedAt')}
6361
6628
  , ${q('__mj_UpdatedAt')}
6362
6629
  )
@@ -6369,17 +6636,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6369
6636
  '${newEntity.TableName}',
6370
6637
  'vw${generatePluralName(newEntity.TableName, { capitalizeFirstLetterOnly: true }) + (newEntitySuffix && newEntitySuffix.length > 0 ? newEntitySuffix : '')}',
6371
6638
  '${newEntity.SchemaName}',
6372
- ${this.boolLit(true)},
6373
- ${newEntityDefaults.AllowUserSearchAPI === undefined ? this.boolLit(true) : this.boolLit(newEntityDefaults.AllowUserSearchAPI)},
6374
- ${this.boolLit(allowCaching)}
6375
- ${newEntityDefaults.TrackRecordChanges === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.TrackRecordChanges)}
6376
- ${newEntityDefaults.AuditRecordAccess === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AuditRecordAccess)}
6377
- ${newEntityDefaults.AuditViewRuns === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AuditViewRuns)}
6378
- ${newEntityDefaults.AllowAllRowsAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowAllRowsAPI)}
6379
- ${newEntityDefaults.AllowCreateAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowCreateAPI)}
6380
- ${newEntityDefaults.AllowUpdateAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowUpdateAPI)}
6381
- ${newEntityDefaults.AllowDeleteAPI === undefined ? '' : ', ' + this.boolLit(newEntityDefaults.AllowDeleteAPI)}
6382
- ${newEntityDefaults.UserViewMaxRows === undefined ? '' : ', ' + (newEntityDefaults.UserViewMaxRows)}
6639
+ ${columns.map(([, value]) => value).join(',\n ')}
6383
6640
  , ${this.utcNow()}
6384
6641
  , ${this.utcNow()}
6385
6642
  )