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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +7 -0
  2. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  3. package/dist/Angular/angular-codegen.js +2 -0
  4. package/dist/Angular/angular-codegen.js.map +1 -1
  5. package/dist/Config/config.d.ts +162 -0
  6. package/dist/Config/config.d.ts.map +1 -1
  7. package/dist/Config/config.js +81 -2
  8. package/dist/Config/config.js.map +1 -1
  9. package/dist/Database/codeGenDatabaseProvider.d.ts +205 -6
  10. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  11. package/dist/Database/codeGenDatabaseProvider.js +367 -5
  12. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  13. package/dist/Database/heal-schema-params.d.ts +7 -0
  14. package/dist/Database/heal-schema-params.d.ts.map +1 -1
  15. package/dist/Database/heal-schema-params.js +5 -0
  16. package/dist/Database/heal-schema-params.js.map +1 -1
  17. package/dist/Database/manage-metadata.d.ts +290 -7
  18. package/dist/Database/manage-metadata.d.ts.map +1 -1
  19. package/dist/Database/manage-metadata.js +737 -67
  20. package/dist/Database/manage-metadata.js.map +1 -1
  21. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +61 -8
  22. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  23. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +238 -48
  24. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  25. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts +2 -0
  26. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts.map +1 -0
  27. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +127 -0
  28. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -0
  29. package/dist/Database/providers/postgresql/metadataSupportObjects.js +200 -8
  30. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  31. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +63 -13
  32. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  33. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +204 -72
  34. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  35. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts +2 -0
  36. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts.map +1 -0
  37. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +141 -0
  38. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -0
  39. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
  40. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
  41. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
  42. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
  43. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
  44. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
  45. package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
  46. package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
  47. package/dist/Database/sql.d.ts +13 -0
  48. package/dist/Database/sql.d.ts.map +1 -1
  49. package/dist/Database/sql.js +39 -8
  50. package/dist/Database/sql.js.map +1 -1
  51. package/dist/Database/sql_codegen.d.ts +176 -4
  52. package/dist/Database/sql_codegen.d.ts.map +1 -1
  53. package/dist/Database/sql_codegen.js +676 -37
  54. package/dist/Database/sql_codegen.js.map +1 -1
  55. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +9 -0
  56. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  57. package/dist/Manifest/GenerateClassRegistrationsManifest.js +28 -7
  58. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  59. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  60. package/dist/Misc/entity_subclasses_codegen.js +18 -2
  61. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  62. package/dist/Misc/system_integrity.d.ts +48 -0
  63. package/dist/Misc/system_integrity.d.ts.map +1 -1
  64. package/dist/Misc/system_integrity.js +151 -75
  65. package/dist/Misc/system_integrity.js.map +1 -1
  66. package/dist/runCodeGen.d.ts +35 -3
  67. package/dist/runCodeGen.d.ts.map +1 -1
  68. package/dist/runCodeGen.js +135 -45
  69. package/dist/runCodeGen.js.map +1 -1
  70. package/package.json +29 -29
@@ -4,9 +4,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- import { EntityInfo, ResolveStartupMode, SetProvider, StartupManager } from '@memberjunction/core';
8
- import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
9
- import { CodeGenDatabaseProvider, CRUDType, } from '../../codeGenDatabaseProvider.js';
7
+ import { EntityInfo, IsValidSQLIdentifier, ResolveStartupMode, SetProvider, StartupManager } from '@memberjunction/core';
8
+ import { EscapeSQLString, RegisterClass, UUIDsEqual } from '@memberjunction/global';
9
+ import { CodeGenDatabaseProvider, CRUDType, ExcludedBaseViewFieldNames, OrderAlternateBaseViewsTopologically, } from '../../codeGenDatabaseProvider.js';
10
10
  import { configInfo, MjCoreSchema } from '../../../Config/config.js';
11
11
  import { logError, logStatus, LogWarning, StartSpinner, SucceedSpinner } from '../../../Misc/status_logging.js';
12
12
  import { BuildMetadataSupportObjectsSQL } from './metadataSupportObjects.js';
@@ -619,14 +619,17 @@ $do$;
619
619
  const pkExtractions = entity.PrimaryKeys.map((pk) => ` v_${this.toSnakeCase(pk.CodeName)} ${this.mapSQLType(pk.SQLFullType)} := (p_data->>'${pk.Name}')::${this.mapSQLType(pk.SQLFullType)};`).join('\n');
620
620
  const pkValidation = entity.PrimaryKeys.map((pk) => `p_data ? '${pk.Name}'`).join(' AND ');
621
621
  const whereClause = entity.PrimaryKeys.map((pk) => `${pgDialect.QuoteIdentifier(pk.Name)} = v_${this.toSnakeCase(pk.CodeName)}`).join(' AND ');
622
+ const returnType = this.buildCRUDReturnType(entity, viewName);
623
+ const variableConflictDirective = entity.SaveReturnMode === 'datestamps_only' ? '\n#variable_conflict use_column' : '';
624
+ const returnSelect = this.buildCRUDReturnSelect(entity, viewName, whereClause);
622
625
  return `
623
626
  ------------------------------------------------------------
624
627
  ----- UPDATE FUNCTION FOR ${entity.BaseTable} (JSON-arg shape)
625
628
  ------------------------------------------------------------
626
629
  ${this.generateDropAllOverloadsBlock(entity.SchemaName, fnName)}
627
630
  CREATE OR REPLACE FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, fnName)}(p_data JSONB)
628
- RETURNS SETOF ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}
629
- AS $$
631
+ RETURNS ${returnType}
632
+ AS $$${variableConflictDirective}
630
633
  DECLARE
631
634
  ${pkExtractions}
632
635
  v_updated_count INTEGER;
@@ -650,8 +653,7 @@ BEGIN
650
653
 
651
654
  -- Return the updated record from the base view
652
655
  RETURN QUERY
653
- SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}
654
- WHERE ${whereClause};
656
+ ${returnSelect};
655
657
  END;
656
658
  $$ LANGUAGE plpgsql;
657
659
  ${permissions}
@@ -730,14 +732,17 @@ ${trigger}
730
732
  RAISE EXCEPTION '${fnName}: p_data must include "${v.field.Name}"';
731
733
  END IF;
732
734
  ${v.varName} := (p_data->>'${v.field.Name}')::${v.pgType};`).join('\n');
735
+ const returnType = this.buildCRUDReturnType(entity, viewName);
736
+ const variableConflictDirective = entity.SaveReturnMode === 'datestamps_only' ? '\n#variable_conflict use_column' : '';
737
+ const returnSelect = this.buildCRUDReturnSelect(entity, viewName, pkWhere);
733
738
  return `
734
739
  ------------------------------------------------------------
735
740
  ----- CREATE FUNCTION FOR ${entity.BaseTable} (JSON-arg shape)
736
741
  ------------------------------------------------------------
737
742
  ${this.generateDropAllOverloadsBlock(entity.SchemaName, fnName)}
738
743
  CREATE OR REPLACE FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, fnName)}(p_data JSONB)
739
- RETURNS SETOF ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}
740
- AS $$
744
+ RETURNS ${returnType}
745
+ AS $$${variableConflictDirective}
741
746
  DECLARE
742
747
  ${pkDeclarations}
743
748
  v_field_name TEXT;
@@ -775,8 +780,7 @@ ${fieldCastEntries}
775
780
  EXECUTE v_sql USING p_data;
776
781
 
777
782
  RETURN QUERY
778
- SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}
779
- WHERE ${pkWhere};
783
+ ${returnSelect};
780
784
  END;
781
785
  $$ LANGUAGE plpgsql;
782
786
  ${permissions}
@@ -826,6 +830,8 @@ ${permissions}
826
830
  const insertColumns = this.generateInsertFieldString(entity, entity.Fields, '', pkHandledByStrategy);
827
831
  const insertValues = this.generateInsertFieldString(entity, entity.Fields, 'p_', pkHandledByStrategy);
828
832
  const strategy = this.buildCreateInsertStrategy(entity, firstKey, insertColumns, insertValues);
833
+ const returnType = this.buildCRUDReturnType(entity, viewName);
834
+ const variableConflictDirective = entity.SaveReturnMode === 'datestamps_only' ? '\n#variable_conflict use_column' : '';
829
835
  return `
830
836
  ------------------------------------------------------------
831
837
  ----- CREATE FUNCTION FOR ${entity.BaseTable}
@@ -833,7 +839,7 @@ ${permissions}
833
839
  ${this.generateDropAllOverloadsBlock(entity.SchemaName, fnName)}
834
840
  CREATE OR REPLACE FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, fnName)}(
835
841
  ${paramString}
836
- ) RETURNS SETOF ${pgDialect.QuoteSchema(entity.SchemaName, viewName)} AS $$
842
+ ) RETURNS ${returnType} AS $$${variableConflictDirective}
837
843
  DECLARE
838
844
  v_new_id ${this.mapSQLType(generatedKey.SQLFullType)};
839
845
  BEGIN
@@ -854,14 +860,47 @@ $$ LANGUAGE plpgsql;
854
860
  ${permissions}
855
861
  `;
856
862
  }
863
+ /**
864
+ * Builds the `RETURNS` clause type for a PostgreSQL CRUD create/update function.
865
+ *
866
+ * - When `entity.SaveReturnMode` is `'full'` (default), returns `SETOF "schema"."vwBaseView"`.
867
+ * - When `entity.SaveReturnMode` is `'datestamps_only'`, returns `TABLE(...)` listing only the
868
+ * primary key column(s) plus `__mj_CreatedAt` and `__mj_UpdatedAt` (via {@link EntityInfo.DatestampReturnFields}).
869
+ */
870
+ buildCRUDReturnType(entity, viewName) {
871
+ if (entity.SaveReturnMode === 'datestamps_only') {
872
+ const cols = entity.DatestampReturnFields
873
+ .map((f) => `${pgDialect.QuoteIdentifier(f.Name)} ${this.mapSQLType(f.SQLFullType)}`)
874
+ .join(', ');
875
+ return `TABLE(${cols})`;
876
+ }
877
+ return `SETOF ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}`;
878
+ }
879
+ /**
880
+ * Builds the post-insert / post-update `SELECT` statement returned by a PostgreSQL CRUD function.
881
+ *
882
+ * - When `entity.SaveReturnMode` is `'full'` (default), queries `SELECT * FROM "schema"."vwBaseView"`.
883
+ * - When `entity.SaveReturnMode` is `'datestamps_only'`, queries only the primary key column(s)
884
+ * plus `__mj_CreatedAt` and `__mj_UpdatedAt` (via {@link EntityInfo.DatestampReturnFields})
885
+ * directly from `"schema"."BaseTable"`, avoiding the post-write `BaseView` joins and large
886
+ * payload columns while still returning DB-generated key and timestamp values.
887
+ */
888
+ buildCRUDReturnSelect(entity, viewName, whereClause) {
889
+ if (entity.SaveReturnMode === 'datestamps_only') {
890
+ const cols = entity.DatestampReturnFields.map((f) => pgDialect.QuoteIdentifier(f.Name)).join(', ');
891
+ return `SELECT ${cols} FROM ${pgDialect.QuoteSchema(entity.SchemaName, entity.BaseTable)}\n WHERE ${whereClause}`;
892
+ }
893
+ return `SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}\n WHERE ${whereClause}`;
894
+ }
857
895
  // ─── CRUD UPDATE ─────────────────────────────────────────────────────
858
896
  /**
859
897
  * Generates a PostgreSQL `CREATE OR REPLACE FUNCTION` for updating an existing record.
860
898
  * The function accepts typed parameters for all updatable fields plus primary key(s),
861
899
  * performs an `UPDATE ... SET ... WHERE PK = param`, checks `ROW_COUNT` to detect
862
- * missing rows, and returns the updated record from the base view via `RETURN QUERY
863
- * SELECT`. Also generates the `__mj_UpdatedAt` timestamp trigger for the entity
864
- * and emits `GRANT EXECUTE` permissions.
900
+ * missing rows, and returns the updated record from the base view (or PK + datestamp
901
+ * columns from the base table when `entity.SaveReturnMode === 'datestamps_only'`) via
902
+ * `RETURN QUERY SELECT`. Also generates the `__mj_UpdatedAt` timestamp trigger for the
903
+ * entity and emits `GRANT EXECUTE` permissions.
865
904
  */
866
905
  generateCRUDUpdate(entity) {
867
906
  if (this.shouldUseJsonArgShape(entity, 'update')) {
@@ -874,6 +913,9 @@ ${permissions}
874
913
  const updateFields = this.generateUpdateFieldString(entity.Fields);
875
914
  const whereClause = this.buildPrimaryKeyWhereClause(entity);
876
915
  const selectWhereClause = this.buildPrimaryKeyWhereClause(entity);
916
+ const returnType = this.buildCRUDReturnType(entity, viewName);
917
+ const variableConflictDirective = entity.SaveReturnMode === 'datestamps_only' ? '\n#variable_conflict use_column' : '';
918
+ const returnSelect = this.buildCRUDReturnSelect(entity, viewName, selectWhereClause);
877
919
  const trigger = this.generateTimestampTrigger(entity);
878
920
  // PK-only entities (e.g. junction tables with only PK + __mj timestamp columns)
879
921
  // have no updatable fields. Generate a no-op function that just returns the
@@ -895,12 +937,10 @@ ${permissions}
895
937
 
896
938
  -- Return the updated record from the base view
897
939
  RETURN QUERY
898
- SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}
899
- WHERE ${selectWhereClause};`
940
+ ${returnSelect};`
900
941
  : ` -- No updatable fields (PK-only entity, e.g. junction table). Return the existing row.
901
942
  RETURN QUERY
902
- SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}
903
- WHERE ${selectWhereClause};`;
943
+ ${returnSelect};`;
904
944
  // Only declare v_updated_count when we actually perform an UPDATE.
905
945
  const declareBlock = hasUpdatableFields ? '\n v_updated_count INTEGER;' : '';
906
946
  return `
@@ -910,7 +950,7 @@ ${permissions}
910
950
  ${this.generateDropAllOverloadsBlock(entity.SchemaName, fnName)}
911
951
  CREATE OR REPLACE FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, fnName)}(
912
952
  ${paramString}
913
- ) RETURNS SETOF ${pgDialect.QuoteSchema(entity.SchemaName, viewName)} AS $$
953
+ ) RETURNS ${returnType} AS $$${variableConflictDirective}
914
954
  DECLARE${declareBlock}
915
955
  BEGIN
916
956
  ${fnBody}
@@ -1049,6 +1089,24 @@ EXECUTE FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, trigFnName)}();
1049
1089
  *
1050
1090
  * @returns A {@link FullTextSearchResult} with the generated SQL and the search function name.
1051
1091
  */
1092
+ /**
1093
+ * PostgreSQL charges full-text search on the WRITE path, not the read path: the emitted objects
1094
+ * include a row-level `BEFORE INSERT OR UPDATE OF <fields>` trigger that recomputes
1095
+ * `to_tsvector` for the row, a GIN index that is maintained on every one of those writes, and a
1096
+ * one-off backfill `UPDATE` across the existing table at apply time. None of that is reversed by
1097
+ * clearing the entity's full-text flags later — the column, trigger and index stay until someone
1098
+ * drops them.
1099
+ */
1100
+ FullTextSearchCostDisclosure(entity, searchFields) {
1101
+ const trigName = `trg_fts_${this.toSnakeCase(entity.BaseTable)}`;
1102
+ const indexName = `idx_fts_${this.toSnakeCase(entity.BaseTable)}`;
1103
+ const fields = searchFields.map((f) => f.Name).join(', ');
1104
+ return `Full-text search on ${entity.SchemaName}.${entity.BaseTable} adds a PERMANENT per-write cost: `
1105
+ + `trigger ${trigName} recomputes to_tsvector on every INSERT and on every UPDATE of (${fields}), `
1106
+ + `GIN index ${indexName} is maintained on each of those writes, and a one-off backfill UPDATE `
1107
+ + `rewrites every existing row when this script is applied. Clearing the entity's full-text flags `
1108
+ + `later does not drop the column, trigger or index.`;
1109
+ }
1052
1110
  generateFullTextSearch(entity, searchFields, _primaryKeyIndexName) {
1053
1111
  const ftsColName = '__mj_fts_vector';
1054
1112
  const trigName = `trg_fts_${this.toSnakeCase(entity.BaseTable)}`;
@@ -1430,12 +1488,23 @@ $$ LANGUAGE sql STABLE;
1430
1488
  }
1431
1489
  // ─── PERMISSIONS ─────────────────────────────────────────────────────
1432
1490
  /** @inheritdoc */
1433
- generateViewPermissions(entity) {
1434
- const viewName = this.getBaseViewName(entity);
1491
+ GenerateViewPermissionsForTarget(entity, targetSchemaName, targetViewName) {
1492
+ const roles = this.collectPermissionRoles(entity.Permissions);
1493
+ if (roles.length === 0)
1494
+ return '';
1495
+ return roles.map((role) => `GRANT SELECT ON ${pgDialect.QuoteSchema(targetSchemaName, targetViewName)} TO ${pgDialect.QuoteIdentifier(role)};`).join('\n');
1496
+ }
1497
+ /** @inheritdoc */
1498
+ GenerateDisabledViewRevokePermissionsForTarget(entity, targetSchemaName, targetViewName) {
1435
1499
  const roles = this.collectPermissionRoles(entity.Permissions);
1436
1500
  if (roles.length === 0)
1437
1501
  return '';
1438
- return roles.map((role) => `GRANT SELECT ON ${pgDialect.QuoteSchema(entity.SchemaName, viewName)} TO ${pgDialect.QuoteIdentifier(role)};`).join('\n');
1502
+ return roles.map((role) => `REVOKE SELECT ON ${pgDialect.QuoteSchema(targetSchemaName, targetViewName)} FROM ${pgDialect.QuoteIdentifier(role)};`).join('\n');
1503
+ }
1504
+ /** @inheritdoc */
1505
+ generateViewPermissions(entity) {
1506
+ const viewName = this.getBaseViewName(entity);
1507
+ return this.GenerateViewPermissionsForTarget(entity, entity.SchemaName, viewName);
1439
1508
  }
1440
1509
  /**
1441
1510
  * Generates `GRANT EXECUTE ON FUNCTION` statements for the given CRUD function,
@@ -1464,7 +1533,27 @@ $$ LANGUAGE sql STABLE;
1464
1533
  const roles = this.collectPermissionRoles(entity.Permissions);
1465
1534
  if (roles.length === 0)
1466
1535
  return '';
1467
- return roles.map((role) => `GRANT EXECUTE ON FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, functionName)} TO ${pgDialect.QuoteIdentifier(role)};`).join('\n');
1536
+ // Each GRANT is guarded by an existence check rather than issued bare.
1537
+ // The permissions file is replayed for EVERY full-text-enabled entity,
1538
+ // including entities whose DDL phase did not run in this pass, and the
1539
+ // 42P16 view-recovery fallback's `DROP ... CASCADE` can take the search
1540
+ // function with it. A GRANT on a function that is not there raises 42883,
1541
+ // which aborts the ENTIRE CodeGen run — an absent function now logs a
1542
+ // NOTICE and the run carries on.
1543
+ const schemaLiteral = entity.SchemaName.replace(/'/g, "''");
1544
+ const functionLiteral = functionName.replace(/'/g, "''");
1545
+ return roles.map((role) => `DO $mjfts$
1546
+ BEGIN
1547
+ IF EXISTS (
1548
+ SELECT 1 FROM pg_proc p
1549
+ JOIN pg_namespace n ON n.oid = p.pronamespace
1550
+ WHERE n.nspname = '${schemaLiteral}' AND p.proname = '${functionLiteral}'
1551
+ ) THEN
1552
+ GRANT EXECUTE ON FUNCTION ${pgDialect.QuoteSchema(entity.SchemaName, functionName)} TO ${pgDialect.QuoteIdentifier(role)};
1553
+ ELSE
1554
+ RAISE NOTICE 'Skipping GRANT on missing full-text search function %.%', '${schemaLiteral}', '${functionLiteral}';
1555
+ END IF;
1556
+ END $mjfts$;`).join('\n');
1468
1557
  }
1469
1558
  // ─── CASCADE DELETES ─────────────────────────────────────────────────
1470
1559
  /** @inheritdoc */
@@ -1872,6 +1961,10 @@ ORDER BY ordinal_position`;
1872
1961
  if (!entity.HasLayeredBaseView) {
1873
1962
  return '';
1874
1963
  }
1964
+ return this.GenerateAlternateBaseViewRebindSQL(entity, entity.SchemaName, entity.BaseView, entity.GeneratedViewName);
1965
+ }
1966
+ /** @inheritdoc */
1967
+ GenerateAlternateBaseViewRebindSQL(_entity, altViewSchema, altViewName, innerViewName) {
1875
1968
  let core = '__mj';
1876
1969
  try {
1877
1970
  core = (MjCoreSchema() || '__mj').replace(/"/g, '""');
@@ -1879,11 +1972,30 @@ ORDER BY ordinal_position`;
1879
1972
  catch {
1880
1973
  core = '__mj';
1881
1974
  }
1882
- const schema = entity.SchemaName.replace(/'/g, "''");
1883
- const outer = entity.BaseView.replace(/'/g, "''");
1884
- const inner = entity.GeneratedViewName.replace(/'/g, "''");
1975
+ const schema = altViewSchema.replace(/'/g, "''");
1976
+ const outer = altViewName.replace(/'/g, "''");
1977
+ const inner = innerViewName.replace(/'/g, "''");
1885
1978
  return `SELECT "${core}"."spRebindLayeredOuterView"('${schema}', '${outer}', '${inner}');`;
1886
1979
  }
1980
+ /** @inheritdoc */
1981
+ getViewDependenciesSQL(schema, viewName) {
1982
+ const escapedSchema = EscapeSQLString(schema);
1983
+ const escapedView = EscapeSQLString(viewName);
1984
+ return `SELECT DISTINCT
1985
+ ns.nspname AS "ReferencedSchema",
1986
+ cl.relname AS "ReferencedObject",
1987
+ cl.relkind AS "ReferencedType"
1988
+ FROM pg_depend d
1989
+ JOIN pg_rewrite r ON r.oid = d.objid
1990
+ JOIN pg_class v ON v.oid = r.ev_class
1991
+ JOIN pg_namespace vns ON vns.oid = v.relnamespace
1992
+ JOIN pg_class cl ON cl.oid = d.refobjid
1993
+ JOIN pg_namespace ns ON ns.oid = cl.relnamespace
1994
+ WHERE vns.nspname = '${escapedSchema}'
1995
+ AND v.relname = '${escapedView}'
1996
+ AND cl.oid <> v.oid
1997
+ AND cl.relkind IN ('r', 'v', 'm', 'f', 'p')`;
1998
+ }
1887
1999
  /**
1888
2000
  * After the inner generated view is current, restar the application-owned
1889
2001
  * outer wrapper so `g.*` re-expands. No-op when the entity is not layered
@@ -1893,23 +2005,56 @@ ORDER BY ordinal_position`;
1893
2005
  if (!entity.HasLayeredBaseView) {
1894
2006
  return;
1895
2007
  }
1896
- const schemaLit = entity.SchemaName.replace(/'/g, "''").replace(/"/g, '""');
1897
- const outerLit = entity.BaseView.replace(/'/g, "''").replace(/"/g, '""');
1898
- const innerLit = entity.GeneratedViewName.replace(/'/g, "''").replace(/"/g, '""');
1899
- const existsResult = await client.query(`SELECT to_regclass('"${schemaLit}"."${outerLit}"') IS NOT NULL AS present`);
2008
+ await this.rebindOuterViewAgainstInnerIfPresent(client, entity.SchemaName, entity.BaseView, entity.SchemaName, entity.GeneratedViewName, willRegenerate);
2009
+ }
2010
+ /**
2011
+ * Rebinds each registered alternate base view on `entity` in topological
2012
+ * `ParentID` order so `SELECT *` / `alias.*` re-expands after the entity's
2013
+ * `BaseView` (or parent alternate view) is regenerated. Wrapped per-view in
2014
+ * `try/catch` so a single broken alternate view logs a warning without
2015
+ * failing the owning entity's view phase.
2016
+ */
2017
+ async rebindAlternateBaseViewsIfPresent(client, entity, willRegenerate) {
2018
+ const orderedAltViews = OrderAlternateBaseViewsTopologically(entity.AlternateBaseViews ?? []);
2019
+ if (orderedAltViews.length === 0) {
2020
+ return;
2021
+ }
2022
+ const defaultInnerName = this.getBaseViewName(entity);
2023
+ for (const altView of orderedAltViews) {
2024
+ if (!IsValidSQLIdentifier(altView.EffectiveSchemaName) || !IsValidSQLIdentifier(altView.ViewName)) {
2025
+ logError(`[AlternateBaseView] Skipping rebind for alternate view '${altView.Name}' on '${entity.Name}': invalid SQL identifier '${altView.EffectiveSchemaName}.${altView.ViewName}'.`);
2026
+ continue;
2027
+ }
2028
+ const parentView = altView.ParentView;
2029
+ const innerSchema = parentView ? parentView.EffectiveSchemaName : entity.SchemaName;
2030
+ const innerName = parentView ? parentView.ViewName : defaultInnerName;
2031
+ try {
2032
+ await this.rebindOuterViewAgainstInnerIfPresent(client, altView.EffectiveSchemaName, altView.ViewName, innerSchema, innerName, willRegenerate);
2033
+ }
2034
+ catch (e) {
2035
+ LogWarning(` ⚠️ [AlternateBaseView] Failed to rebind alternate view '${altView.Name}' (${altView.EffectiveSchemaName}.${altView.ViewName}) on '${entity.Name}': ${e instanceof Error ? e.message : String(e)}`);
2036
+ }
2037
+ }
2038
+ }
2039
+ async rebindOuterViewAgainstInnerIfPresent(client, outerSchema, outerViewName, innerSchema, innerViewName, willRegenerate) {
2040
+ const outerSchemaLit = outerSchema.replace(/'/g, "''").replace(/"/g, '""');
2041
+ const outerLit = outerViewName.replace(/'/g, "''").replace(/"/g, '""');
2042
+ const innerSchemaLit = innerSchema.replace(/'/g, "''").replace(/"/g, '""');
2043
+ const innerLit = innerViewName.replace(/'/g, "''").replace(/"/g, '""');
2044
+ const existsResult = await client.query(`SELECT to_regclass('"${outerSchemaLit}"."${outerLit}"') IS NOT NULL AS present`);
1900
2045
  if (!existsResult.rows?.[0]?.['present']) {
1901
2046
  return;
1902
2047
  }
1903
- const defResult = await client.query(this.getViewDefinitionSQL(entity.SchemaName, entity.BaseView));
2048
+ const defResult = await client.query(this.getViewDefinitionSQL(outerSchema, outerViewName));
1904
2049
  const viewDefinition = String(defResult.rows?.[0]?.['ViewDefinition'] ?? defResult.rows?.[0]?.['viewdefinition'] ?? '');
1905
2050
  if (!viewDefinition) {
1906
- throw new LayeredOuterRestarError(`Could not read pg_get_viewdef for layered outer view ${entity.SchemaName}.${entity.BaseView}`);
2051
+ throw new LayeredOuterRestarError(`Could not read pg_get_viewdef for layered outer view ${outerSchema}.${outerViewName}`);
1907
2052
  }
1908
2053
  const colResult = await client.query(`SELECT a.attname AS "Name"
1909
2054
  FROM pg_attribute a
1910
2055
  JOIN pg_class c ON c.oid = a.attrelid
1911
2056
  JOIN pg_namespace n ON n.oid = c.relnamespace
1912
- WHERE n.nspname = '${schemaLit}'
2057
+ WHERE n.nspname = '${innerSchemaLit}'
1913
2058
  AND c.relname = '${innerLit}'
1914
2059
  AND a.attnum > 0
1915
2060
  AND NOT a.attisdropped
@@ -1917,14 +2062,14 @@ ORDER BY ordinal_position`;
1917
2062
  const innerColumns = (colResult.rows ?? []).map((r) => String(r['Name'] ?? r['name'] ?? ''));
1918
2063
  const restarred = restarLayeredOuterView({
1919
2064
  viewDefinition,
1920
- innerViewName: entity.GeneratedViewName,
2065
+ innerViewName,
1921
2066
  innerColumns,
1922
2067
  });
1923
- const createSQL = buildCreateOrReplaceLayeredOuterViewSQL(entity.SchemaName, entity.BaseView, restarred);
2068
+ const createSQL = buildCreateOrReplaceLayeredOuterViewSQL(outerSchema, outerViewName, restarred);
1924
2069
  await ExecuteWithFallback({
1925
2070
  Client: client,
1926
- schema: entity.SchemaName,
1927
- ViewName: entity.BaseView,
2071
+ schema: outerSchema,
2072
+ ViewName: outerViewName,
1928
2073
  CreateOrReplaceSQL: createSQL,
1929
2074
  WillRegenerate: willRegenerate,
1930
2075
  });
@@ -2157,23 +2302,26 @@ WHERE p.prokind IN ('f', 'p')
2157
2302
  BaseTableQualified: pgDialect.QuoteSchema(entity.SchemaName, entity.BaseTable),
2158
2303
  });
2159
2304
  await this.rebindLayeredOuterIfPresent(client, entity, willRegenerate);
2305
+ await this.rebindAlternateBaseViewsIfPresent(client, entity, willRegenerate);
2160
2306
  }
2161
2307
  finally {
2162
2308
  client.release();
2163
2309
  }
2164
2310
  }
2165
2311
  /**
2166
- * Phased per-entity execution for PG. Runs view → CRUD functions → view
2167
- * permissions against the target DB, guaranteeing phase 2 is skipped if
2168
- * phase 1 failed (so we never leave `fn_create_*` functions pointing at
2169
- * a missing or stale view's rowtype).
2312
+ * Phased per-entity execution for PG. Runs view → CRUD functions →
2313
+ * full-text search → view permissions against the target DB, guaranteeing
2314
+ * phase 2 is skipped if phase 1 failed (so we never leave `fn_create_*`
2315
+ * functions pointing at a missing or stale view's rowtype).
2170
2316
  *
2171
2317
  * Phase 1 routes through `executeWithFallback` so a 42P16 triggers the
2172
2318
  * capture/drop/recreate/restore flow rather than blowing up. Phase 2 runs
2173
2319
  * each CRUD function's CREATE individually — we do NOT concatenate them
2174
2320
  * because node-pg's simple query protocol would then abort the whole
2175
2321
  * batch on the first failure; running them separately gives a per-routine
2176
- * error signal. Phase 3 applies view-level GRANTs.
2322
+ * error signal. Phase 3 installs the full-text objects, whose search
2323
+ * function returns the base view's rowtype and so depends on phase 1.
2324
+ * Phase 4 applies view-level GRANTs.
2177
2325
  */
2178
2326
  async executeEntityPhased(opts) {
2179
2327
  // [Large Schema Series] pooled client (was `new pg.Client()` per entity —
@@ -2209,6 +2357,7 @@ WHERE p.prokind IN ('f', 'p')
2209
2357
  BaseTableQualified: pgDialect.QuoteSchema(opts.entity.SchemaName, opts.entity.BaseTable),
2210
2358
  });
2211
2359
  await this.rebindLayeredOuterIfPresent(client, opts.entity, opts.willRegenerate);
2360
+ await this.rebindAlternateBaseViewsIfPresent(client, opts.entity, opts.willRegenerate);
2212
2361
  }
2213
2362
  catch (e) {
2214
2363
  return {
@@ -2235,7 +2384,25 @@ WHERE p.prokind IN ('f', 'p')
2235
2384
  };
2236
2385
  }
2237
2386
  }
2238
- // ── Phase 3: view permissions ────────────────────────────────
2387
+ // ── Phase 3: full-text search DDL ────────────────────────────
2388
+ // The search function is declared `RETURNS SETOF <baseview>`, so it
2389
+ // can only be created once phase 1 has put the view in place — and it
2390
+ // must be created before the permissions replay, which GRANTs EXECUTE
2391
+ // on it. Before this phase existed the generated full-text SQL was
2392
+ // written to a file and never executed on PostgreSQL at all.
2393
+ if (opts.ftsSQL && opts.ftsSQL.trim()) {
2394
+ try {
2395
+ await client.query(opts.ftsSQL);
2396
+ }
2397
+ catch (e) {
2398
+ return {
2399
+ success: false,
2400
+ phase: 'fulltext',
2401
+ error: e instanceof Error ? e : new Error(String(e)),
2402
+ };
2403
+ }
2404
+ }
2405
+ // ── Phase 4: view permissions ────────────────────────────────
2239
2406
  if (opts.viewPermSQL && opts.viewPermSQL.trim()) {
2240
2407
  try {
2241
2408
  await client.query(opts.viewPermSQL);
@@ -2340,7 +2507,9 @@ WHERE p.prokind IN ('f', 'p')
2340
2507
  buildBaseViewSelectParts(context, alias) {
2341
2508
  // parentFieldsSelect and rootFieldsSelect have leading commas (e.g. ",\n Field AS Alias").
2342
2509
  // relatedFieldsSelect does NOT have a leading comma for the first field (starts with "\n Field...").
2343
- let select = `${alias}.*`;
2510
+ // `alias.*` unless this entity has a configured base-view column exclusion, in which case the
2511
+ // base-table columns are enumerated instead. See baseTableSelectList / ExcludedBaseViewFieldNames.
2512
+ let select = this.baseTableSelectList(context.entity, alias, ExcludedBaseViewFieldNames(context.entity.Name, configInfo?.baseViewExcludedFields ?? []));
2344
2513
  if (context.parentFieldsSelect)
2345
2514
  select += context.parentFieldsSelect;
2346
2515
  if (context.relatedFieldsSelect)
@@ -2406,7 +2575,7 @@ WHERE p.prokind IN ('f', 'p')
2406
2575
  return {
2407
2576
  preInsert: '',
2408
2577
  returningClause: `RETURNING ${identityCol} INTO v_new_id`,
2409
- selectClause: `SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}\n WHERE ${identityCol} = v_new_id${keyPredicates}`,
2578
+ selectClause: this.buildCRUDReturnSelect(entity, viewName, `${identityCol} = v_new_id${keyPredicates}`),
2410
2579
  finalColumns: callerSuppliedKeys.length === 0 ? insertColumns : (hasNonPkColumns ? `${keyColumns},\n ${insertColumns}` : keyColumns),
2411
2580
  finalValues: callerSuppliedKeys.length === 0 ? insertValues : (hasNonPkColumns ? `${keyValues},\n ${insertValues}` : keyValues),
2412
2581
  };
@@ -2417,7 +2586,7 @@ WHERE p.prokind IN ('f', 'p')
2417
2586
  return {
2418
2587
  preInsert: `v_new_id := COALESCE(${paramName}, gen_random_uuid());\n `,
2419
2588
  returningClause: '',
2420
- selectClause: `SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}\n WHERE ${pkCol} = v_new_id`,
2589
+ selectClause: this.buildCRUDReturnSelect(entity, viewName, `${pkCol} = v_new_id`),
2421
2590
  // Include the PK column in the INSERT so caller-provided IDs are respected.
2422
2591
  // When there are no non-PK columns, omit the trailing comma.
2423
2592
  finalColumns: hasNonPkFields ? `${pkCol},\n ${insertColumns}` : pkCol,
@@ -2447,7 +2616,7 @@ WHERE p.prokind IN ('f', 'p')
2447
2616
  return {
2448
2617
  preInsert: '',
2449
2618
  returningClause: '',
2450
- selectClause: `SELECT * FROM ${pgDialect.QuoteSchema(entity.SchemaName, viewName)}\n WHERE ${selectWhere}`,
2619
+ selectClause: this.buildCRUDReturnSelect(entity, viewName, selectWhere),
2451
2620
  finalColumns,
2452
2621
  finalValues,
2453
2622
  };
@@ -2608,6 +2777,27 @@ WHERE p.prokind IN ('f', 'p')
2608
2777
  )
2609
2778
  AND array_length(ix.indkey, 1) > 1`;
2610
2779
  }
2780
+ /**
2781
+ * @inheritdoc
2782
+ * `indkey` lists the key columns first, then the INCLUDE columns; `indnkeyatts` is how many are keys.
2783
+ */
2784
+ GetUniqueIndexMembershipSQL(schema, tableName, columnName) {
2785
+ return `SELECT
2786
+ NOT EXISTS (
2787
+ SELECT 1 FROM generate_series(0, ix.indnkeyatts - 1) AS k(pos)
2788
+ WHERE ix.indkey[k.pos] = a.attnum
2789
+ ) AS "IsIncludedColumn",
2790
+ ix.indnkeyatts AS "KeyColumnCount"
2791
+ FROM pg_catalog.pg_index ix
2792
+ INNER JOIN pg_catalog.pg_class t ON t.oid = ix.indrelid
2793
+ INNER JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
2794
+ INNER JOIN pg_catalog.pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
2795
+ WHERE ix.indisunique
2796
+ AND NOT ix.indisprimary
2797
+ AND n.nspname = '${EscapeSQLString(schema)}'
2798
+ AND t.relname = '${EscapeSQLString(tableName)}'
2799
+ AND a.attname = '${EscapeSQLString(columnName)}'`;
2800
+ }
2611
2801
  /** @inheritdoc */
2612
2802
  getForeignKeyIndexExistsSQL(schema, tableName, indexName) {
2613
2803
  return `SELECT 1