@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.
- package/README.md +7 -0
- package/dist/Angular/angular-codegen.d.ts.map +1 -1
- package/dist/Angular/angular-codegen.js +2 -0
- package/dist/Angular/angular-codegen.js.map +1 -1
- package/dist/Config/config.d.ts +162 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +81 -2
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts +205 -6
- package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.js +367 -5
- package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
- package/dist/Database/heal-schema-params.d.ts +7 -0
- package/dist/Database/heal-schema-params.d.ts.map +1 -1
- package/dist/Database/heal-schema-params.js +5 -0
- package/dist/Database/heal-schema-params.js.map +1 -1
- package/dist/Database/manage-metadata.d.ts +290 -7
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +737 -67
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +61 -8
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +238 -48
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts +2 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts.map +1 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +127 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -0
- package/dist/Database/providers/postgresql/metadataSupportObjects.js +200 -8
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +63 -13
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +204 -72
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts +2 -0
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +141 -0
- package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
- package/dist/Database/sql.d.ts +13 -0
- package/dist/Database/sql.d.ts.map +1 -1
- package/dist/Database/sql.js +39 -8
- package/dist/Database/sql.js.map +1 -1
- package/dist/Database/sql_codegen.d.ts +176 -4
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +676 -37
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +9 -0
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.js +28 -7
- package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.js +18 -2
- package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
- package/dist/Misc/system_integrity.d.ts +48 -0
- package/dist/Misc/system_integrity.d.ts.map +1 -1
- package/dist/Misc/system_integrity.js +151 -75
- package/dist/Misc/system_integrity.js.map +1 -1
- package/dist/runCodeGen.d.ts +35 -3
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +135 -45
- package/dist/runCodeGen.js.map +1 -1
- package/package.json +29 -29
|
@@ -5,9 +5,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
7
|
import { EntityInfo, CodeNameFromString, ResolveStartupMode } from '@memberjunction/core';
|
|
8
|
-
import { CodeGenDatabaseProvider, } from '../../codeGenDatabaseProvider.js';
|
|
8
|
+
import { CodeGenDatabaseProvider, ExcludedBaseViewFieldNames, } from '../../codeGenDatabaseProvider.js';
|
|
9
9
|
import { SQLServerDialect } from '@memberjunction/sql-dialect';
|
|
10
|
-
import { ordinalCompare, RegisterClass } from '@memberjunction/global';
|
|
10
|
+
import { EscapeSQLString, ordinalCompare, RegisterClass } from '@memberjunction/global';
|
|
11
11
|
import { SortBySequenceAndCreatedAt } from '../../../Misc/util.js';
|
|
12
12
|
import { configInfo, dbDatabase, MjCoreSchema } from '../../../Config/config.js';
|
|
13
13
|
import { MSSQLConnection, GetSqlConfig } from '../../../Config/db-connection.js';
|
|
@@ -15,6 +15,8 @@ import { logError, logStatus, LogWarning, StartSpinner, SucceedSpinner } from '.
|
|
|
15
15
|
import { SQLServerProviderConfigData, setupSQLServerClient } from '@memberjunction/sqlserver-dataprovider';
|
|
16
16
|
import { UserCache } from '@memberjunction/generic-database-provider';
|
|
17
17
|
import { SQLServerCodeGenConnection } from './SQLServerCodeGenConnection.js';
|
|
18
|
+
import { ClassifySQLServerDefaultValue } from './sqlServerDefaultValues.js';
|
|
19
|
+
import { DescribeSQLBatchObject, NormalizeSQLServerRoutineDefinition, SplitSQLServerBatches } from './sqlServerScriptText.js';
|
|
18
20
|
import * as fs from 'fs';
|
|
19
21
|
import * as path from 'path';
|
|
20
22
|
const ssDialect = new SQLServerDialect();
|
|
@@ -123,6 +125,9 @@ let SQLServerCodeGenProvider = class SQLServerCodeGenProvider extends CodeGenDat
|
|
|
123
125
|
const whereClause = entity.DeleteType === 'Soft'
|
|
124
126
|
? `WHERE\n ${alias}.[${EntityInfo.DeletedAtFieldName}] IS NULL\n`
|
|
125
127
|
: '';
|
|
128
|
+
// `alias.*` unless this entity has a configured base-view column exclusion, in which case the
|
|
129
|
+
// base-table columns are enumerated instead. See baseTableSelectList / ExcludedBaseViewFieldNames.
|
|
130
|
+
const baseTableSelect = this.baseTableSelectList(entity, alias, ExcludedBaseViewFieldNames(entity.Name, configInfo?.baseViewExcludedFields ?? []));
|
|
126
131
|
return `
|
|
127
132
|
------------------------------------------------------------
|
|
128
133
|
----- BASE VIEW FOR ENTITY: ${entity.Name}
|
|
@@ -137,7 +142,7 @@ GO
|
|
|
137
142
|
CREATE VIEW [${entity.SchemaName}].[${viewName}]
|
|
138
143
|
AS
|
|
139
144
|
SELECT
|
|
140
|
-
${
|
|
145
|
+
${baseTableSelect}${context.parentFieldsSelect}${context.relatedFieldsSelect.length > 0 ? ',' : ''}${context.relatedFieldsSelect}${context.rootFieldsSelect}
|
|
141
146
|
FROM
|
|
142
147
|
[${entity.SchemaName}].[${entity.BaseTable}] AS ${alias}${context.parentJoins ? '\n' + context.parentJoins : ''}${context.relatedFieldsJoins ? '\n' + context.relatedFieldsJoins : ''}${context.rootJoins}
|
|
143
148
|
${whereClause}GO`;
|
|
@@ -232,6 +237,10 @@ ${this.trimStatementTerminator(selectSQL)}`;
|
|
|
232
237
|
const identityKey = entity.PrimaryKeys.find(k => k.AutoIncrement);
|
|
233
238
|
const efString = this.generateCRUDParamString(entity.Fields, false);
|
|
234
239
|
const permissions = this.generateCRUDPermissions(entity, spName, 'Create');
|
|
240
|
+
// Expression defaults (#4000) are resolved into their parameters ahead of every INSERT
|
|
241
|
+
// branch below. Empty for the common case, which keeps those procedures byte-identical.
|
|
242
|
+
const assignmentSQL = this.GeneratePreInsertDefaultAssignments(entity);
|
|
243
|
+
const defaultAssignments = assignmentSQL.length > 0 ? `${assignmentSQL}\n ` : '';
|
|
235
244
|
let preInsertCode = '';
|
|
236
245
|
let outputCode = '';
|
|
237
246
|
let selectInsertedRecord = '';
|
|
@@ -245,7 +254,7 @@ ${this.trimStatementTerminator(selectSQL)}`;
|
|
|
245
254
|
additionalFieldList = callerSuppliedKeys.map(k => `[${k.Name}]`).join(',\n ');
|
|
246
255
|
additionalValueList = callerSuppliedKeys.map(k => `@${k.CodeName}`).join(',\n ');
|
|
247
256
|
const callerSuppliedKeyPredicates = callerSuppliedKeys.map(k => ` AND [${k.Name}] = @${k.CodeName}`).join('');
|
|
248
|
-
selectInsertedRecord =
|
|
257
|
+
selectInsertedRecord = this.buildCRUDReturnSelect(entity, `[${identityKey.Name}] = SCOPE_IDENTITY()${callerSuppliedKeyPredicates}`);
|
|
249
258
|
}
|
|
250
259
|
else if (firstKey.Type.toLowerCase().trim() === 'uniqueidentifier' && entity.PrimaryKeys.length === 1) {
|
|
251
260
|
const hasDefaultValue = firstKey.DefaultValue && firstKey.DefaultValue.trim().length > 0;
|
|
@@ -289,7 +298,7 @@ ${this.trimStatementTerminator(selectSQL)}`;
|
|
|
289
298
|
additionalFieldList = '';
|
|
290
299
|
additionalValueList = '';
|
|
291
300
|
outputCode = '';
|
|
292
|
-
selectInsertedRecord =
|
|
301
|
+
selectInsertedRecord = this.buildCRUDReturnSelect(entity, `[${firstKey.Name}] = (SELECT [${firstKey.Name}] FROM @InsertedRow)`);
|
|
293
302
|
}
|
|
294
303
|
else {
|
|
295
304
|
// UUID without DB default: generate via ISNULL(@PK, NEWID()).
|
|
@@ -299,7 +308,7 @@ ${this.trimStatementTerminator(selectSQL)}`;
|
|
|
299
308
|
additionalFieldList = '[' + firstKey.Name + ']';
|
|
300
309
|
additionalValueList = '@ActualID';
|
|
301
310
|
outputCode = '';
|
|
302
|
-
selectInsertedRecord =
|
|
311
|
+
selectInsertedRecord = this.buildCRUDReturnSelect(entity, `[${firstKey.Name}] = @ActualID`);
|
|
303
312
|
}
|
|
304
313
|
}
|
|
305
314
|
else {
|
|
@@ -318,14 +327,8 @@ ${this.trimStatementTerminator(selectSQL)}`;
|
|
|
318
327
|
}
|
|
319
328
|
additionalFieldList = pkColumns.join(',\n ');
|
|
320
329
|
additionalValueList = pkValues.join(',\n ');
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
for (const k of entity.PrimaryKeys) {
|
|
324
|
-
if (!isFirst)
|
|
325
|
-
selectInsertedRecord += ' AND ';
|
|
326
|
-
selectInsertedRecord += `[${k.Name}] = @${k.CodeName}`;
|
|
327
|
-
isFirst = false;
|
|
328
|
-
}
|
|
330
|
+
const pkWhereClause = entity.PrimaryKeys.map(k => `[${k.Name}] = @${k.CodeName}`).join(' AND ');
|
|
331
|
+
selectInsertedRecord = this.buildCRUDReturnSelect(entity, pkWhereClause);
|
|
329
332
|
}
|
|
330
333
|
// Build the INSERT column and value lists. For the non-hasDefaultValue branches,
|
|
331
334
|
// additionalFieldList holds PK columns (without leading commas) and
|
|
@@ -375,19 +378,38 @@ CREATE PROCEDURE [${entity.SchemaName}].[${spName}]
|
|
|
375
378
|
AS
|
|
376
379
|
BEGIN
|
|
377
380
|
SET NOCOUNT ON;
|
|
378
|
-
${preInsertCode}${insertBlock}
|
|
381
|
+
${defaultAssignments}${preInsertCode}${insertBlock}
|
|
379
382
|
-- return the new record from the base view, which might have some calculated fields
|
|
380
383
|
${selectInsertedRecord}
|
|
381
384
|
END
|
|
382
385
|
GO${permissions}
|
|
383
386
|
`;
|
|
384
387
|
}
|
|
388
|
+
/**
|
|
389
|
+
* Builds the post-insert / post-update `SELECT` statement returned by a CRUD stored procedure.
|
|
390
|
+
*
|
|
391
|
+
* - When `entity.SaveReturnMode` is `'full'` (default), queries `SELECT *` (or `SELECT TOP 0 *`)
|
|
392
|
+
* from `[schema].[BaseView]` so calculated and joined columns are returned.
|
|
393
|
+
* - When `entity.SaveReturnMode` is `'datestamps_only'`, queries only the primary key column(s)
|
|
394
|
+
* plus `__mj_CreatedAt` and `__mj_UpdatedAt` (via {@link EntityInfo.DatestampReturnFields})
|
|
395
|
+
* directly from `[schema].[BaseTable]`, avoiding the post-write `BaseView` joins and large
|
|
396
|
+
* payload columns while still returning DB-generated key and timestamp values.
|
|
397
|
+
*/
|
|
398
|
+
buildCRUDReturnSelect(entity, whereClause, topZero = false) {
|
|
399
|
+
const topPrefix = topZero ? 'TOP 0 ' : '';
|
|
400
|
+
if (entity.SaveReturnMode === 'datestamps_only') {
|
|
401
|
+
const cols = entity.DatestampReturnFields.map(f => `[${f.Name}]`).join(', ');
|
|
402
|
+
return `SELECT ${topPrefix}${cols} FROM [${entity.SchemaName}].[${entity.BaseTable}] WHERE ${whereClause}`;
|
|
403
|
+
}
|
|
404
|
+
return `SELECT ${topPrefix}* FROM [${entity.SchemaName}].[${entity.BaseView}] WHERE ${whereClause}`;
|
|
405
|
+
}
|
|
385
406
|
/**
|
|
386
407
|
* Generates the `spUpdate` stored procedure for a SQL Server entity. Performs a standard
|
|
387
408
|
* `UPDATE ... SET ... WHERE PK = @PK` and uses `@@ROWCOUNT` to detect whether the row
|
|
388
409
|
* was found: if no rows were updated (e.g., stale PK or concurrent delete), returns an
|
|
389
410
|
* empty result set with the base view's column structure (`SELECT TOP 0 ... WHERE 1=0`);
|
|
390
|
-
* otherwise returns the updated record from the base view
|
|
411
|
+
* otherwise returns the updated record from the base view (or PK + datestamp columns from
|
|
412
|
+
* the base table when `entity.SaveReturnMode === 'datestamps_only'`). Also generates the
|
|
391
413
|
* `__mj_UpdatedAt` timestamp trigger if the entity has that column.
|
|
392
414
|
*/
|
|
393
415
|
generateCRUDUpdate(entity) {
|
|
@@ -397,13 +419,18 @@ GO${permissions}
|
|
|
397
419
|
const hasUpdatedAtField = entity.Fields.find(f => f.Name.toLowerCase().trim() === EntityInfo.UpdatedAtFieldName.trim().toLowerCase()) !== undefined;
|
|
398
420
|
const updatedAtTrigger = hasUpdatedAtField ? this.generateTimestampTrigger(entity) : '';
|
|
399
421
|
const updateFields = this.generateUpdateFieldString(entity.Fields);
|
|
400
|
-
const
|
|
422
|
+
const pkWhereClause = entity.PrimaryKeys.map(k => `[${k.Name}] = @${k.CodeName}`).join(' AND ');
|
|
423
|
+
const isDatestampsOnly = entity.SaveReturnMode === 'datestamps_only';
|
|
424
|
+
const selectUpdatedRecord = isDatestampsOnly
|
|
425
|
+
? this.buildCRUDReturnSelect(entity, pkWhereClause)
|
|
426
|
+
: `SELECT
|
|
401
427
|
*
|
|
402
428
|
FROM
|
|
403
429
|
[${entity.SchemaName}].[${entity.BaseView}]
|
|
404
430
|
WHERE
|
|
405
|
-
${
|
|
431
|
+
${pkWhereClause}
|
|
406
432
|
`;
|
|
433
|
+
const selectEmptyRecord = this.buildCRUDReturnSelect(entity, '1=0', true);
|
|
407
434
|
// PK-only entities (e.g. junction tables with only PK + __mj timestamp columns)
|
|
408
435
|
// have no updatable fields. Generate a no-op SP that just returns the existing row
|
|
409
436
|
// rather than emitting an invalid UPDATE with an empty SET clause.
|
|
@@ -414,12 +441,12 @@ GO${permissions}
|
|
|
414
441
|
SET
|
|
415
442
|
${updateFields}
|
|
416
443
|
WHERE
|
|
417
|
-
${
|
|
444
|
+
${pkWhereClause}
|
|
418
445
|
|
|
419
446
|
-- Check if the update was successful
|
|
420
447
|
IF @@ROWCOUNT = 0
|
|
421
448
|
-- Nothing was updated, return no rows, but column structure from base view intact, semantically correct this way.
|
|
422
|
-
|
|
449
|
+
${selectEmptyRecord}
|
|
423
450
|
ELSE
|
|
424
451
|
-- Return the updated record so the caller can see the updated values and any calculated fields
|
|
425
452
|
${selectUpdatedRecord}`
|
|
@@ -605,6 +632,14 @@ IF NOT EXISTS (
|
|
|
605
632
|
CREATE INDEX ${indexName} ON [${entity.SchemaName}].[${entity.BaseTable}] (${cols});`;
|
|
606
633
|
}
|
|
607
634
|
// ─── FULL-TEXT SEARCH ────────────────────────────────────────────────
|
|
635
|
+
/**
|
|
636
|
+
* True: the `CREATE FULLTEXT INDEX … KEY INDEX <name>` below names the table's unique
|
|
637
|
+
* primary-key index, so CodeGen must resolve that name before the DDL can be composed.
|
|
638
|
+
* See {@link CodeGenDatabaseProvider.FullTextIndexNeedsPrimaryKeyIndexName}.
|
|
639
|
+
*/
|
|
640
|
+
get FullTextIndexNeedsPrimaryKeyIndexName() {
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
608
643
|
/**
|
|
609
644
|
* Generates SQL Server full-text search infrastructure for an entity, conditionally
|
|
610
645
|
* producing up to three components based on entity metadata flags:
|
|
@@ -618,6 +653,24 @@ CREATE INDEX ${indexName} ON [${entity.SchemaName}].[${entity.BaseTable}] (${col
|
|
|
618
653
|
*
|
|
619
654
|
* @returns The generated SQL and the resolved function name for permission grants.
|
|
620
655
|
*/
|
|
656
|
+
/**
|
|
657
|
+
* SQL Server charges full-text search through the fulltext population service rather than a
|
|
658
|
+
* trigger: `CREATE FULLTEXT INDEX` puts the table under continuous change tracking, so every
|
|
659
|
+
* INSERT/UPDATE/DELETE that touches an indexed column queues crawl work, and the index itself
|
|
660
|
+
* occupies catalog storage. The generated script also DROPs and RECREATEs the index, which means
|
|
661
|
+
* a full re-crawl of the table each time this entity's SQL is applied.
|
|
662
|
+
*/
|
|
663
|
+
FullTextSearchCostDisclosure(entity, searchFields) {
|
|
664
|
+
if (!entity.FullTextIndexGenerated) {
|
|
665
|
+
return null;
|
|
666
|
+
}
|
|
667
|
+
const fields = searchFields.map((f) => f.Name).join(', ');
|
|
668
|
+
return `Full-text search on ${entity.SchemaName}.${entity.BaseTable} adds a PERMANENT cost: the `
|
|
669
|
+
+ `fulltext index over (${fields}) puts the table under change tracking, so every write to an `
|
|
670
|
+
+ `indexed column queues population work, and this script DROPs and RECREATEs the index — a full `
|
|
671
|
+
+ `re-crawl of the table on every apply. Clearing the entity's full-text flags later does not drop `
|
|
672
|
+
+ `the index or the catalog.`;
|
|
673
|
+
}
|
|
621
674
|
generateFullTextSearch(entity, searchFields, primaryKeyIndexName) {
|
|
622
675
|
let sql = '';
|
|
623
676
|
const catalogName = entity.FullTextCatalog && entity.FullTextCatalog.length > 0
|
|
@@ -1060,7 +1113,7 @@ GO
|
|
|
1060
1113
|
* - **Unrestrictable targets** (PKs, `__mj_` columns, the security/identity entities) are
|
|
1061
1114
|
* filtered defensively even though save-time guards should make such rows impossible.
|
|
1062
1115
|
*/
|
|
1063
|
-
generateFieldSecurityDenies(entity) {
|
|
1116
|
+
generateFieldSecurityDenies(entity, targetSchemaName = entity.SchemaName, targetViewName = entity.BaseView) {
|
|
1064
1117
|
const context = this._fieldSecurityRunContext;
|
|
1065
1118
|
if (!context)
|
|
1066
1119
|
return '';
|
|
@@ -1095,16 +1148,16 @@ GO
|
|
|
1095
1148
|
}
|
|
1096
1149
|
let sOutput = '';
|
|
1097
1150
|
for (const [sqlName, columns] of [...deniedColumnsByRole.entries()].sort(([a], [b]) => ordinalCompare(a, b))) {
|
|
1098
|
-
sOutput += `\nDENY SELECT (${columns.map(c => `[${c}]`).join(', ')}) ON [${
|
|
1151
|
+
sOutput += `\nDENY SELECT (${columns.map(c => `[${c}]`).join(', ')}) ON [${targetSchemaName}].[${targetViewName}] TO [${sqlName}]`;
|
|
1099
1152
|
}
|
|
1100
1153
|
return sOutput;
|
|
1101
1154
|
}
|
|
1102
1155
|
/** @inheritdoc */
|
|
1103
|
-
|
|
1156
|
+
GenerateViewPermissionsForTarget(entity, targetSchemaName, targetViewName) {
|
|
1104
1157
|
let sOutput = '';
|
|
1105
1158
|
for (const ep of entity.Permissions) {
|
|
1106
1159
|
if (ep.RoleSQLName && ep.RoleSQLName.length > 0) {
|
|
1107
|
-
sOutput += (sOutput === '' ? `GRANT SELECT ON [${
|
|
1160
|
+
sOutput += (sOutput === '' ? `GRANT SELECT ON [${targetSchemaName}].[${targetViewName}] TO ` : ', ') + `[${ep.RoleSQLName}]`;
|
|
1108
1161
|
}
|
|
1109
1162
|
else {
|
|
1110
1163
|
this.logAppTierOnlyRoleSkip(ep.Role);
|
|
@@ -1112,11 +1165,32 @@ GO
|
|
|
1112
1165
|
}
|
|
1113
1166
|
// Order matters: wipe (REVOKE within the managed scope) → assert grants → assert
|
|
1114
1167
|
// field-security DENYs. The whole body executes every run via applyPermissions.
|
|
1115
|
-
const revokes = this.generateManagedPermissionRevokes(
|
|
1168
|
+
const revokes = this.generateManagedPermissionRevokes(targetSchemaName, targetViewName);
|
|
1116
1169
|
const grants = (sOutput === '' ? '' : '\n') + sOutput;
|
|
1117
|
-
const denies = this.generateFieldSecurityDenies(entity);
|
|
1170
|
+
const denies = this.generateFieldSecurityDenies(entity, targetSchemaName, targetViewName);
|
|
1118
1171
|
return revokes + grants + denies;
|
|
1119
1172
|
}
|
|
1173
|
+
/** @inheritdoc */
|
|
1174
|
+
GenerateDisabledViewRevokePermissionsForTarget(entity, targetSchemaName, targetViewName) {
|
|
1175
|
+
const revokes = this.generateManagedPermissionRevokes(targetSchemaName, targetViewName);
|
|
1176
|
+
if (revokes.trim().length > 0) {
|
|
1177
|
+
return revokes;
|
|
1178
|
+
}
|
|
1179
|
+
const roles = [];
|
|
1180
|
+
for (const ep of entity.Permissions) {
|
|
1181
|
+
if (ep.RoleSQLName && ep.RoleSQLName.length > 0 && !roles.includes(ep.RoleSQLName)) {
|
|
1182
|
+
roles.push(ep.RoleSQLName);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
if (roles.length === 0) {
|
|
1186
|
+
return '';
|
|
1187
|
+
}
|
|
1188
|
+
return `\nREVOKE SELECT ON [${targetSchemaName}].[${targetViewName}] FROM ${roles.map((r) => `[${r}]`).join(', ')}`;
|
|
1189
|
+
}
|
|
1190
|
+
/** @inheritdoc */
|
|
1191
|
+
generateViewPermissions(entity) {
|
|
1192
|
+
return this.GenerateViewPermissionsForTarget(entity, entity.SchemaName, entity.BaseView);
|
|
1193
|
+
}
|
|
1120
1194
|
/**
|
|
1121
1195
|
* Generates `GRANT EXECUTE` SQL for a CRUD stored procedure, granting permission only
|
|
1122
1196
|
* to roles whose `EntityPermission` record allows the specified CRUD operation type.
|
|
@@ -1367,40 +1441,51 @@ WHERE s.name IN (${inList})`;
|
|
|
1367
1441
|
}
|
|
1368
1442
|
// ─── UTILITY ─────────────────────────────────────────────────────────
|
|
1369
1443
|
/**
|
|
1370
|
-
* Formats a
|
|
1371
|
-
*
|
|
1372
|
-
* `
|
|
1373
|
-
* `
|
|
1374
|
-
*
|
|
1375
|
-
*
|
|
1444
|
+
* Formats a column default for embedding in generated SQL. The value is classified by
|
|
1445
|
+
* {@link ClassifySQLServerDefaultValue}: literals keep the long-standing quoting rule
|
|
1446
|
+
* (`needsQuotes`), inline-safe functions such as `GETUTCDATE()` are emitted verbatim, a
|
|
1447
|
+
* bare `NEWSEQUENTIALID()` becomes `NEWID()` (it is legal only in a DEFAULT constraint), and
|
|
1448
|
+
* expressions are emitted verbatim rather than string-quoted. Returns `'NULL'` for empty or
|
|
1449
|
+
* whitespace-only inputs.
|
|
1376
1450
|
*/
|
|
1377
1451
|
formatDefaultValue(defaultValue, needsQuotes) {
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1452
|
+
return ClassifySQLServerDefaultValue(defaultValue, needsQuotes).SQL;
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* An expression default (`NEXT VALUE FOR`, string concatenation, most function calls) is
|
|
1456
|
+
* resolved into its parameter before the INSERT: T-SQL rejects `NEXT VALUE FOR` inside the
|
|
1457
|
+
* `ISNULL`/`CASE` wrap the value list otherwise uses (#4000).
|
|
1458
|
+
*/
|
|
1459
|
+
isPreInsertDefault(ef) {
|
|
1460
|
+
return ClassifySQLServerDefaultValue(ef.DefaultValue, ef.NeedsQuotes).Kind === 'Expression';
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Emits `IF @P IS NULL SET @P = <expr>;` for every create-routine parameter whose default is an
|
|
1464
|
+
* expression. Mirrors the value-list branches of {@link GenerateInsertFieldString}: a NOT NULL
|
|
1465
|
+
* uniqueidentifier also treats the empty GUID as "not supplied", and a nullable column skips the
|
|
1466
|
+
* default when the caller set its `_Clear` companion.
|
|
1467
|
+
*/
|
|
1468
|
+
GeneratePreInsertDefaultAssignments(entity) {
|
|
1469
|
+
const lines = [];
|
|
1470
|
+
for (const ef of entity.Fields) {
|
|
1471
|
+
if (ef.IsPrimaryKey || ef.IsVirtual || !ef.AllowUpdateAPI || ef.AutoIncrement || ef.IsSpecialDateField) {
|
|
1472
|
+
continue;
|
|
1394
1473
|
}
|
|
1474
|
+
if (!ef.HasDefaultValue || !this.isPreInsertDefault(ef)) {
|
|
1475
|
+
continue;
|
|
1476
|
+
}
|
|
1477
|
+
const param = `@${ef.CodeName}`;
|
|
1478
|
+
const expr = this.formatDefaultValue(ef.DefaultValue, ef.NeedsQuotes);
|
|
1479
|
+
let condition = `${param} IS NULL`;
|
|
1480
|
+
if (!ef.AllowsNull && ef.IsUniqueIdentifier) {
|
|
1481
|
+
condition = `(${param} IS NULL OR ${param} = ${this.Dialect.EmptyUUIDLiteral()})`;
|
|
1482
|
+
}
|
|
1483
|
+
else if (ef.AllowsNull && this.needsClearCompanion(ef)) {
|
|
1484
|
+
condition = `${param} IS NULL AND ISNULL(@${ef.CodeName}_Clear, 0) = 0`;
|
|
1485
|
+
}
|
|
1486
|
+
lines.push(`IF ${condition} SET ${param} = ${expr};`);
|
|
1395
1487
|
}
|
|
1396
|
-
|
|
1397
|
-
if (cleanValue.startsWith("'") && cleanValue.endsWith("'")) {
|
|
1398
|
-
cleanValue = cleanValue.substring(1, cleanValue.length - 1);
|
|
1399
|
-
}
|
|
1400
|
-
if (needsQuotes) {
|
|
1401
|
-
return `'${cleanValue}'`;
|
|
1402
|
-
}
|
|
1403
|
-
return cleanValue;
|
|
1488
|
+
return lines.join('\n ');
|
|
1404
1489
|
}
|
|
1405
1490
|
/**
|
|
1406
1491
|
* Builds the four SQL fragments needed to work with an entity's primary key columns
|
|
@@ -1491,6 +1576,25 @@ WHERE s.name IN (${inList})`;
|
|
|
1491
1576
|
AND ic2.index_id = i.index_id) > 1`;
|
|
1492
1577
|
}
|
|
1493
1578
|
/** @inheritdoc */
|
|
1579
|
+
GetUniqueIndexMembershipSQL(schema, tableName, columnName) {
|
|
1580
|
+
return `SELECT ic.is_included_column AS IsIncludedColumn,
|
|
1581
|
+
(SELECT COUNT(*)
|
|
1582
|
+
FROM sys.index_columns k
|
|
1583
|
+
WHERE k.object_id = i.object_id
|
|
1584
|
+
AND k.index_id = i.index_id
|
|
1585
|
+
AND k.is_included_column = 0) AS KeyColumnCount
|
|
1586
|
+
FROM sys.indexes i
|
|
1587
|
+
INNER JOIN sys.tables t ON t.object_id = i.object_id
|
|
1588
|
+
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
|
|
1589
|
+
INNER JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
|
|
1590
|
+
INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
|
|
1591
|
+
WHERE i.is_unique = 1
|
|
1592
|
+
AND i.is_primary_key = 0
|
|
1593
|
+
AND s.name = '${EscapeSQLString(schema)}'
|
|
1594
|
+
AND t.name = '${EscapeSQLString(tableName)}'
|
|
1595
|
+
AND c.name = '${EscapeSQLString(columnName)}'`;
|
|
1596
|
+
}
|
|
1597
|
+
/** @inheritdoc */
|
|
1494
1598
|
getForeignKeyIndexExistsSQL(schema, tableName, indexName) {
|
|
1495
1599
|
return `SELECT 1
|
|
1496
1600
|
FROM sys.indexes
|
|
@@ -1648,6 +1752,18 @@ ORDER BY
|
|
|
1648
1752
|
return `EXEC sp_refreshview '${schema}.${viewName}';`;
|
|
1649
1753
|
}
|
|
1650
1754
|
/** @inheritdoc */
|
|
1755
|
+
getViewDependenciesSQL(schema, viewName) {
|
|
1756
|
+
const escapedSchema = EscapeSQLString(schema);
|
|
1757
|
+
const escapedView = EscapeSQLString(viewName);
|
|
1758
|
+
return `SELECT
|
|
1759
|
+
COALESCE(OBJECT_SCHEMA_NAME(d.referenced_id), d.referenced_schema_name, '${escapedSchema}') AS ReferencedSchema,
|
|
1760
|
+
COALESCE(OBJECT_NAME(d.referenced_id), d.referenced_entity_name) AS ReferencedObject,
|
|
1761
|
+
COALESCE(o.type_desc, 'UNKNOWN') AS ReferencedType
|
|
1762
|
+
FROM sys.sql_expression_dependencies d
|
|
1763
|
+
LEFT JOIN sys.objects o ON o.object_id = d.referenced_id
|
|
1764
|
+
WHERE d.referencing_id = OBJECT_ID('[${escapedSchema}].[${escapedView}]')`;
|
|
1765
|
+
}
|
|
1766
|
+
/** @inheritdoc */
|
|
1651
1767
|
generateIfViewExistsSQL(schema, viewName, innerSQL) {
|
|
1652
1768
|
// sp_executesql rather than the statements inline: the guarded body includes GRANT, and
|
|
1653
1769
|
// routing everything through one dynamic-SQL call keeps the emitted shape uniform no matter
|
|
@@ -1884,32 +2000,44 @@ DROP TABLE #__mj__CodeGen__vwTableUniqueKeys;
|
|
|
1884
2000
|
}
|
|
1885
2001
|
// ─── METADATA MANAGEMENT: SQL FILE EXECUTION ─────────────────────
|
|
1886
2002
|
/**
|
|
1887
|
-
* Executes a SQL file against SQL Server
|
|
1888
|
-
*
|
|
1889
|
-
*
|
|
1890
|
-
*
|
|
1891
|
-
*
|
|
1892
|
-
*
|
|
2003
|
+
* Executes a SQL file against SQL Server over the shared in-process mssql pool, one `GO`
|
|
2004
|
+
* batch at a time. Every batch runs even after one fails, so a single run reports the
|
|
2005
|
+
* complete set of broken objects; each failure is logged as an error naming the object the
|
|
2006
|
+
* batch acts on (`CREATE PROCEDURE [s].[spX]`, `GRANT ON [s].[vwX]`). Returns `false` when
|
|
2007
|
+
* any batch failed or the file could not be read, `true` otherwise. A failed batch used to be
|
|
2008
|
+
* logged as a warning with the file still reported as successful, which hid procedures that
|
|
2009
|
+
* had been dropped and never recreated (#4000).
|
|
1893
2010
|
*/
|
|
1894
2011
|
async executeSQLFileViaShell(filePath) {
|
|
2012
|
+
let sql;
|
|
2013
|
+
try {
|
|
2014
|
+
sql = fs.readFileSync(filePath, 'utf-8');
|
|
2015
|
+
}
|
|
2016
|
+
catch (e) {
|
|
2017
|
+
logError(`[CodeGen] Failed to read SQL file ${filePath}: ${e instanceof Error ? e.message : e}`);
|
|
2018
|
+
return false;
|
|
2019
|
+
}
|
|
2020
|
+
if (!sql.trim())
|
|
2021
|
+
return true;
|
|
1895
2022
|
try {
|
|
1896
|
-
const sql = fs.readFileSync(filePath, 'utf-8');
|
|
1897
|
-
if (!sql.trim())
|
|
1898
|
-
return true;
|
|
1899
|
-
const batches = sql
|
|
1900
|
-
.split(/^\s*GO\s*$/gim)
|
|
1901
|
-
.map(b => b.trim())
|
|
1902
|
-
.filter(b => b.length > 0);
|
|
1903
2023
|
const pool = await MSSQLConnection();
|
|
1904
|
-
|
|
2024
|
+
const failures = [];
|
|
2025
|
+
for (const batch of SplitSQLServerBatches(sql)) {
|
|
1905
2026
|
try {
|
|
1906
2027
|
await pool.request().query(batch);
|
|
1907
2028
|
}
|
|
1908
2029
|
catch (err) {
|
|
1909
|
-
|
|
1910
|
-
|
|
2030
|
+
failures.push({
|
|
2031
|
+
Object: DescribeSQLBatchObject(batch),
|
|
2032
|
+
Message: err instanceof Error ? err.message : String(err),
|
|
2033
|
+
});
|
|
1911
2034
|
}
|
|
1912
2035
|
}
|
|
2036
|
+
if (failures.length > 0) {
|
|
2037
|
+
const list = failures.map(f => ` - ${f.Object}: ${f.Message.substring(0, 400)}`).join('\n');
|
|
2038
|
+
logError(`[CodeGen] ${failures.length} SQL batch(es) failed in ${path.basename(filePath)}:\n${list}`);
|
|
2039
|
+
return false;
|
|
2040
|
+
}
|
|
1913
2041
|
return true;
|
|
1914
2042
|
}
|
|
1915
2043
|
catch (e) {
|
|
@@ -1917,6 +2045,10 @@ DROP TABLE #__mj__CodeGen__vwTableUniqueKeys;
|
|
|
1917
2045
|
return false;
|
|
1918
2046
|
}
|
|
1919
2047
|
}
|
|
2048
|
+
/** @inheritdoc */
|
|
2049
|
+
NormalizeRoutineDefinitionForComparison(definition) {
|
|
2050
|
+
return NormalizeSQLServerRoutineDefinition(definition);
|
|
2051
|
+
}
|
|
1920
2052
|
};
|
|
1921
2053
|
SQLServerCodeGenProvider = __decorate([
|
|
1922
2054
|
RegisterClass(CodeGenDatabaseProvider, 'sqlserver')
|