From 188d48dcbc0974843eeb2245966224658f6f224b Mon Sep 17 00:00:00 2001 From: Zi Chen <13544267+zijchen@users.noreply.github.com> Date: Mon, 7 Jul 2025 10:00:07 -0700 Subject: [PATCH 01/45] Create 170.64.0.md (#143) Signed-off-by: Zi Chen <13544267+zijchen@users.noreply.github.com> --- release-notes/170/170.64.0.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 release-notes/170/170.64.0.md diff --git a/release-notes/170/170.64.0.md b/release-notes/170/170.64.0.md new file mode 100644 index 00000000..8f63da34 --- /dev/null +++ b/release-notes/170/170.64.0.md @@ -0,0 +1,27 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 170.64.0 +This update brings the below changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates.NET SDK to latest patch version 8.0.411 + +#### .NET Framework +#### .NET Core + +### New Features +* Adds support for `MANUAL_CUTOVER` and `PERFORM_CUTOVER` in `ALTER DATABASE` options. +* Adds supports for `ORDER` clause on nonclustered columnstore indexes. + +### Fixed + +### Changes +* Updated Fabric DW syntax to better match the definition for identity columns. + +### Known Issues From e0a6eb2565507f1e5fc36bb951a4c0ed6f607fb4 Mon Sep 17 00:00:00 2001 From: Zi Chen <13544267+zijchen@users.noreply.github.com> Date: Tue, 22 Jul 2025 10:15:44 -0700 Subject: [PATCH 02/45] Update CODEOWNERS (#142) Signed-off-by: Zi Chen <13544267+zijchen@users.noreply.github.com> --- .github/CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 59aa5b57..1a133c2d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @barbaravaldez @dzsquared @zijchen @chlafreniere @llali \ No newline at end of file +* @dzsquared @zijchen @chlafreniere @llali @ssreerama @kburtram From 003271e65d28d33c7fbabe787918865d414a4755 Mon Sep 17 00:00:00 2001 From: Zi Chen <13544267+zijchen@users.noreply.github.com> Date: Tue, 22 Jul 2025 10:15:56 -0700 Subject: [PATCH 03/45] Sync repos: Release 170.64.0 (#141) * Merged PR 1696252: Changes to support Manual-cutover and Perform-cutover in ScriptDOM ## Description The changes are done to support new parameters in TSQL ALTER DATABASE command to add new parameters MANUAL_CUTOVER and PERFORM_CUTOVER. **Functional spec** of feature FMv2: https://microsoft-my.sharepoint-df.com/:w:/p/blakhani/ERKCMOUx59ZIjfSJ_eIyLfQB--YQbcRDPoSNiiUtWvS1bg?e=vWg0vP **Design doc** of feature FMv2: https://microsoft.sharepoint.com/:w:/t/sqlstormr/Eb0o3p3MNB1CmdS7NByqHkQB11bGrU9PNVg5GE98Z6yhhg?e=reyHi3 ## Code Change - [X] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [X] Code changes are accompanied by appropriate unit tests - [X] Identified and included SMEs needed to review code changes - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature Newly added tests are passing successfully: ![image.png](https://msdata.visualstudio.com/c6789c20-b819-4bfd-9917-11471655156e/_apis/git/repositories/2247f543-55d8-45df-a9fe-23820ae656af/pullRequests/1696252/attachments/image.png) Ran all tests which are passing successfully: ![image.png](https://msdata.visualstudio.com/c6789c20-b819-4bfd-9917-11471655156e/_apis/git/repositories/2247f543-55d8-45df-a9fe-23820ae656af/pullRequests/1696252/attachments/image.png) ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers ---- #### AI description (iteration 1) #### PR Classification New feature implementation to support manual and perform cutover options in ScriptDOM. #### PR Summary This pull request extends ScriptDOM to accommodate the MANUAL_CUTOVER and PERFORM_CUTOVER options as required for the Forward Migration v2 feature. The enhancements include grammar updates, AST modifications, option kind extensions, code generation adjustments, and new SQL tests. - **`TSql170.g`**: Added production rules for `alterDbManualCutover` and `alterDbPerformCutover` to parse the new options. - **`Ast.xml`**: Introduced new classes (`ManualCutoverDatabaseOption` and `PerformCutoverDatabaseOption`) to represent the cutover options. - **`DatabaseOptionKind.cs` & Helpers**: Extended the enum and updated mappings in `DatabaseOptionKindHelper.cs` and `OnOffSimpleDbOptionsHelper.cs` with the new option kinds. - **`CodeGenerationSupporter.cs` & `SqlVersionFlags.cs`**: Incorporate... * Merged PR 1704129: support ORDER clause for NonClustered ColumnStore Index ## Description Support Order clause on NONClustered ColumnStore Index. CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI ON T(A, B, C) ORDER(A, B); CREATE COLUMNSTORE INDEX idx_ntccitrim_prim2 ON dbo.nttrim_prim (i1, c1, nvc1) ORDER (i1, c1); We already support CLUSTERED COLUMNSTORE INDEX Order clause, we need add support for NonClustered right now. ## Code Change - [x] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [x] Code changes are accompanied by appropriate unit tests - [x] Identified and included SMEs needed to review code changes - [x] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [x] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ![image.png](https://msdata.visualstudio.com/c6789c20-b819-4bfd-9917-11471655156e/_apis/git/repositories/2247f543-55d8-45df-a9fe-23820ae656af/pullRequests/1704129/attachments/image.png) ## Documentation - [x] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers support ORDER clause for NonClustered ColumnStore Index ---- #### AI description (iteration 1) #### PR Classification New feature enabling the ORDER clause for both clustered and non-clustered columnstore indexes. #### PR Summary This pull request enhances the SQL script generator to support the ORDER clause for columnstore indexes and adds tests to verify the new syntax. - `SqlScriptGeneratorVisitor.CreateColumnStoreIndexStatement.cs`: Modified condition to generate ordered columns for both clustered and non-clustered indexes. - `Only170SyntaxTests.cs`: Updated test suite to include a new parser test for the CreateColumnStoreIndex syntax. - `Baselines170/CreateColumnStoreIndexTests170.sql` & `TestScripts/CreateColumnStoreIndexTests170.sql`: Added new test files to validate the ORDER clause support. Related work items: #3876240 * Merged PR 1702087: Identity Column - Fabric DW In this PR we delete options for Identity Columns in TSqlFabricDW.g since they are not supported by the Fabric SQL engine. i.e. Fabric warehouse does not support seed and increment.. Hence the supported TSQL syntax would change from: `IDENTITY [ (seed , increment) ]` to the new syntax: `CREATE TABLE table1 ( ID BIGINT IDENTITY );` Related work items: #4314344 * [Security] Update .NET SDK to latest patch version * Fix test on Linux --------- Co-authored-by: Mohit Agarwal Co-authored-by: May Wen Co-authored-by: Dhruv Relwani Co-authored-by: MerlinBot --- SqlScriptDom/Parser/TSql/Ast.xml | 4 +++ .../Parser/TSql/CodeGenerationSupporter.cs | 2 ++ .../Parser/TSql/DatabaseOptionKind.cs | 5 ++- .../Parser/TSql/DatabaseOptionKindHelper.cs | 4 +++ SqlScriptDom/Parser/TSql/SqlVersionFlags.cs | 1 + SqlScriptDom/Parser/TSql/TSql170.g | 20 +++++++++++ SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 23 ------------ ...rVisitor.AlterDbPerformCutoverStatement.cs | 21 +++++++++++ ...iptGeneratorVisitor.AlterDbSetStatement.cs | 13 +++++-- ...Visitor.CreateColumnStoreIndexStatement.cs | 6 ++-- .../AlterDatabaseManualCutoverTests170.sql | 10 ++++++ .../CreateColumnStoreIndexTests170.sql | 8 +++++ .../IdentityColumnTestsFabricDW.sql | 27 ++++++++++++++ Test/SqlDom/CommonSyntaxTests.cs | 17 +++++++++ Test/SqlDom/Only170SyntaxTests.cs | 4 ++- Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 5 +-- Test/SqlDom/ParserErrorsTests.cs | 36 +++++++++++++++++-- .../AlterDatabaseManualCutoverTests170.sql | 10 ++++++ .../CreateColumnStoreIndexTests170.sql | 8 +++++ .../IdentityColumnTestsFabricDW.sql | 27 ++++++++++++++ global.json | 2 +- 21 files changed, 218 insertions(+), 35 deletions(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbPerformCutoverStatement.cs create mode 100644 Test/SqlDom/Baselines170/AlterDatabaseManualCutoverTests170.sql create mode 100644 Test/SqlDom/Baselines170/CreateColumnStoreIndexTests170.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/IdentityColumnTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AlterDatabaseManualCutoverTests170.sql create mode 100644 Test/SqlDom/TestScripts/CreateColumnStoreIndexTests170.sql create mode 100644 Test/SqlDom/TestScripts/IdentityColumnTestsFabricDW.sql diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index d02bc3b5..ffeec7c8 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -2404,6 +2404,7 @@ + @@ -2576,6 +2577,9 @@ + + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index daa8b35e..7c00dbef 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -564,6 +564,7 @@ internal static class CodeGenerationSupporter internal const string LSquareParen = "["; internal const string MaintainIndex = "MAINTAIN_INDEX"; internal const string Manual = "MANUAL"; + internal const string ManualCutover = "MANUAL_CUTOVER"; internal const string Mark = "MARK"; internal const string MarkInUseForRemoval = "MARK_IN_USE_FOR_REMOVAL"; internal const string Masked = "MASKED"; @@ -728,6 +729,7 @@ internal static class CodeGenerationSupporter internal const string Paused = "PAUSED"; internal const string Percentage = "PERCENTAGE"; internal const string PerCpu = "PER_CPU"; + internal const string PerformCutover = "PERFORM_CUTOVER"; internal const string Period = "PERIOD"; internal const string PermissionSet = "PERMISSION_SET"; internal const string PerNode = "PER_NODE"; diff --git a/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs b/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs index 2cdeec34..c3118e2c 100644 --- a/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs +++ b/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs @@ -95,7 +95,10 @@ public enum DatabaseOptionKind // T-SQL 150 On/Off options DataRetention = 67, - Ledger = 68 + Ledger = 68, + + ManualCutover = 69, + PerformCutover = 70 } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/DatabaseOptionKindHelper.cs b/SqlScriptDom/Parser/TSql/DatabaseOptionKindHelper.cs index 612f3b03..c46471b1 100644 --- a/SqlScriptDom/Parser/TSql/DatabaseOptionKindHelper.cs +++ b/SqlScriptDom/Parser/TSql/DatabaseOptionKindHelper.cs @@ -32,6 +32,10 @@ private DatabaseOptionKindHelper() // 140 Options AddOptionMapping(DatabaseOptionKind.AutomaticTuning, CodeGenerationSupporter.AutomaticTuning, SqlVersionFlags.TSql140AndAbove); + + // 170 Options + AddOptionMapping(DatabaseOptionKind.ManualCutover, CodeGenerationSupporter.ManualCutover, SqlVersionFlags.TSql170AndAbove); + AddOptionMapping(DatabaseOptionKind.PerformCutover, CodeGenerationSupporter.PerformCutover, SqlVersionFlags.TSql170AndAbove); } internal static readonly DatabaseOptionKindHelper Instance = new DatabaseOptionKindHelper(); diff --git a/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs b/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs index 522413d6..23bb379f 100644 --- a/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs +++ b/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs @@ -35,6 +35,7 @@ internal enum SqlVersionFlags TSql140AndAbove = TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, TSql150AndAbove = TSql150 | TSql160 | TSqlFabricDW | TSql170, TSql160AndAbove = TSql160 | TSqlFabricDW | TSql170, + TSql170AndAbove = TSql170, TSqlFabricDWAndAbove = TSql160 | TSqlFabricDW | TSql170, TSqlUnder110 = TSql80 | TSql90 | TSql100, TSqlUnder120 = TSql80 | TSql90 | TSql100 | TSql110, diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 367fc110..b5b4a2b1 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -2896,6 +2896,7 @@ alterDatabase [IToken tAlter] returns [AlterDatabaseStatement vResult = null] | vResult = alterDbSet | vResult = alterDbCollate | vResult = alterDbRebuild // Undocumented - for PSS only + | vResult = alterDbPerformCutover ) { if(vUseCurrent) @@ -3057,8 +3058,19 @@ alterDbModify returns [AlterDatabaseStatement vResult = null] ; alterDbModifyAzureOptions returns [AlterDatabaseSetStatement vResult = FragmentFactory.CreateFragment()] +{ + bool hasManualCutover = false; +} : azureOptions[vResult, vResult.Options] + ( + With tManualCutover:Identifier + { + Match(tManualCutover, CodeGenerationSupporter.ManualCutover); + hasManualCutover = true; + vResult.WithManualCutover = true; + } + )? ; // MODIFY File syntax @@ -3143,6 +3155,14 @@ toFilegroup returns [Identifier vResult] } ; +alterDbPerformCutover returns [AlterDatabasePerformCutoverStatement vResult = FragmentFactory.CreateFragment()] + : tPerformCutover:Identifier + { + Match(tPerformCutover, CodeGenerationSupporter.PerformCutover); + UpdateTokenInfo(vResult, tPerformCutover); + } + ; + xactTermination returns [AlterDatabaseTermination vResult = FragmentFactory.CreateFragment()] { Literal vInteger; diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index 0923abc7..137a318f 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -29587,33 +29587,10 @@ rowguidcolConstraint [ColumnDefinition vParent] ; identityConstraint [IndexAffectingStatement statementType] returns [IdentityOptions vResult = FragmentFactory.CreateFragment()] -{ - ScalarExpression vExpression; - bool vNotForReplication; -} : tIdentity:Identity { UpdateTokenInfo(vResult,tIdentity); } - ( - (LeftParenthesis seedIncrement)=> // necessary because select statement can start with LeftParenthesis - LeftParenthesis vExpression=seedIncrement - { - vResult.IdentitySeed = vExpression; - } - Comma vExpression=seedIncrement - { - vResult.IdentityIncrement = vExpression; - } - tRParen:RightParenthesis - { - UpdateTokenInfo(vResult,tRParen); - } - )? - vNotForReplication = replicationClauseOpt[statementType, vResult] - { - vResult.IsIdentityNotForReplication = vNotForReplication; - } ; // Same as column_definition in SQL YACC grammar diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbPerformCutoverStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbPerformCutoverStatement.cs new file mode 100644 index 00000000..e8b6393d --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbPerformCutoverStatement.cs @@ -0,0 +1,21 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System; + +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(AlterDatabasePerformCutoverStatement node) + { + GenerateAlterDbStatementHead(node); + + GenerateSpaceAndIdentifier(CodeGenerationSupporter.PerformCutover); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbSetStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbSetStatement.cs index 6ca6ef80..08499f9e 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbSetStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterDbSetStatement.cs @@ -15,9 +15,11 @@ public override void ExplicitVisit(AlterDatabaseSetStatement node) NewLineAndIndent(); bool azureOnlyOption = true; - foreach(DatabaseOption option in node.Options) + foreach (DatabaseOption option in node.Options) { - if (option.OptionKind != DatabaseOptionKind.MaxSize && option.OptionKind != DatabaseOptionKind.Edition && option.OptionKind != DatabaseOptionKind.ServiceObjective) + if (option.OptionKind != DatabaseOptionKind.MaxSize && + option.OptionKind != DatabaseOptionKind.Edition && + option.OptionKind != DatabaseOptionKind.ServiceObjective) { azureOnlyOption = false; break; @@ -31,6 +33,13 @@ public override void ExplicitVisit(AlterDatabaseSetStatement node) MarkAndPushAlignmentPoint(items); GenerateParenthesisedCommaSeparatedList(node.Options, true); PopAlignmentPoint(); + + // Emit "WITH MANUAL_CUTOVER" if the statement includes the optional manual cutover clause + if (node.WithManualCutover) + { + GenerateSpaceAndKeyword(TSqlTokenType.With); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.ManualCutover); + } } else { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateColumnStoreIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateColumnStoreIndexStatement.cs index d37ab562..cce64f40 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateColumnStoreIndexStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateColumnStoreIndexStatement.cs @@ -36,8 +36,10 @@ public override void ExplicitVisit(CreateColumnStoreIndexStatement node) GenerateParenthesisedCommaSeparatedList(node.Columns); } - // If clustered columstore index, generate ordered columns if any - if(node.Clustered.GetValueOrDefault() && node.OrderedColumns != null && node.OrderedColumns.Count > 0) + // Generate ordered columns if any, for both clustered and non-clustered indexes + // If node.Clustered is null or false, it indicates index type is non-clustered. + // If node.Clustered is true, it indicates index type is clustered. + if (node.OrderedColumns != null && node.OrderedColumns.Count > 0) { GenerateSpaceAndKeyword(TSqlTokenType.Order); GenerateParenthesisedCommaSeparatedList(node.OrderedColumns); diff --git a/Test/SqlDom/Baselines170/AlterDatabaseManualCutoverTests170.sql b/Test/SqlDom/Baselines170/AlterDatabaseManualCutoverTests170.sql new file mode 100644 index 00000000..71a106f3 --- /dev/null +++ b/Test/SqlDom/Baselines170/AlterDatabaseManualCutoverTests170.sql @@ -0,0 +1,10 @@ +ALTER DATABASE db + MODIFY (SERVICE_OBJECTIVE = 'HS_Gen5_16') WITH MANUAL_CUTOVER; + +ALTER DATABASE db + MODIFY (EDITION = 'Hyperscale') WITH MANUAL_CUTOVER; + +ALTER DATABASE db + MODIFY (SERVICE_OBJECTIVE = ELASTIC_POOL (NAME = [hspool])) WITH MANUAL_CUTOVER; + +ALTER DATABASE db PERFORM_CUTOVER; diff --git a/Test/SqlDom/Baselines170/CreateColumnStoreIndexTests170.sql b/Test/SqlDom/Baselines170/CreateColumnStoreIndexTests170.sql new file mode 100644 index 00000000..d9201bf4 --- /dev/null +++ b/Test/SqlDom/Baselines170/CreateColumnStoreIndexTests170.sql @@ -0,0 +1,8 @@ +CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI + ON T(A, B, C) ORDER(A, B); + +CREATE COLUMNSTORE INDEX NCCI + ON T(A, B, C) ORDER(A, B); + +CREATE CLUSTERED COLUMNSTORE INDEX CCI + ON T ORDER(A, B); diff --git a/Test/SqlDom/BaselinesFabricDW/IdentityColumnTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/IdentityColumnTestsFabricDW.sql new file mode 100644 index 00000000..43988f97 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/IdentityColumnTestsFabricDW.sql @@ -0,0 +1,27 @@ +CREATE TABLE table1 ( + ID BIGINT IDENTITY +); + + +GO +CREATE TABLE Employees ( + EmployeeID BIGINT IDENTITY, + FirstName NVARCHAR (50), + LastName NVARCHAR (50) +); + + +GO +CREATE TABLE Orders ( + OrderID INT IDENTITY, + CustomerName VARCHAR (100) , + OrderDate DATETIME , + TotalAmount DECIMAL (10, 2) +); + + +GO +CREATE TABLE Products ( + ProductID BIGINT IDENTITY, + ProductName NVARCHAR (100) +); \ No newline at end of file diff --git a/Test/SqlDom/CommonSyntaxTests.cs b/Test/SqlDom/CommonSyntaxTests.cs index 39fa64ed..8b280db9 100644 --- a/Test/SqlDom/CommonSyntaxTests.cs +++ b/Test/SqlDom/CommonSyntaxTests.cs @@ -7,6 +7,8 @@ using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.VisualStudio.TestTools.UnitTesting; using SqlStudio.Tests.AssemblyTools.TestCategory; +using System; +using System.Collections.Generic; namespace SqlStudio.Tests.UTSqlScriptDom { @@ -238,8 +240,23 @@ public void CommonSyntaxInFabricDWParserTest() TSqlFabricDWParser parser = new TSqlFabricDWParser(true); SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.SqlFabricDW); + // Some syntaxes that are not supported in Fabric DW + var skippedTests = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "ColumnDefinitionTests.sql", + "IntegerTests.sql", + "TSqlParserTestScript1.sql", + "TSqlParserTestScript2.sql", + "ExpressionTests.sql" + }; + foreach (ParserTest ti in CommonTestInfos) { + if (skippedTests.Contains(ti._scriptFilename)) + { + continue; // Skip tests that are not applicable to Fabric DW + } + ParserTest.ParseAndVerify(parser, scriptGen, ti._scriptFilename, ti._resultFabricDW); } } diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 4b352d57..bd84d403 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -9,7 +9,9 @@ public partial class SqlDomTests // Note: These filenames are case sensitive, make sure they match the checked-in file exactly private static readonly ParserTest[] Only170TestInfos = { - new ParserTest170("RegexpTVFTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0) + new ParserTest170("RegexpTVFTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), + new ParserTest170("AlterDatabaseManualCutoverTests170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), + new ParserTest170("CreateColumnStoreIndexTests170.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0) }; private static readonly ParserTest[] SqlAzure170_TestInfos = diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index 58537c4e..043340ec 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -10,10 +10,11 @@ public partial class SqlDomTests private static readonly ParserTest[] OnlyFabricDWTestInfos = { new ParserTestFabricDW("CloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), - new ParserTestFabricDW("CreateProcedureCloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), - new ParserTestFabricDW("ScalarFunctionTestsFabricDW.sql", nErrors80: 3, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), new ParserTestFabricDW("CreateAlterTableClusterByTestsFabricDW.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 6), new ParserTestFabricDW("CreateExternalTableStatementTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("CreateProcedureCloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), + new ParserTestFabricDW("IdentityColumnTestsFabricDW.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("ScalarFunctionTestsFabricDW.sql", nErrors80: 3, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0) }; [TestMethod] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 7474efd6..57f6264d 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -3524,9 +3524,17 @@ public void NotForReplicationNotAllowedInTableVariablesFunctionsTypesErrorTest() new ParserErrorInfo(39, "SQL46010", "not")); // Column identity constraint - ParserTestUtils.ErrorTestAllParsers("declare @v1 table (c1 int identity(1,1) not for replication)", + ParserTestUtils.ErrorTestAllParsersUntil150("declare @v1 table (c1 int identity(1,1) not for replication)", new ParserErrorInfo(40, "SQL46010", "not")); - ParserTestUtils.ErrorTestAllParsers("create function f1() returns @v1 table (c1 int identity(1,1) not for replication) begin return end", + ParserTestUtils.ErrorTest160("declare @v1 table (c1 int identity(1,1) not for replication)", + new ParserErrorInfo(40, "SQL46010", "not")); + ParserTestUtils.ErrorTest170("declare @v1 table (c1 int identity(1,1) not for replication)", + new ParserErrorInfo(40, "SQL46010", "not")); + ParserTestUtils.ErrorTestAllParsersUntil150("create function f1() returns @v1 table (c1 int identity(1,1) not for replication) begin return end", + new ParserErrorInfo(61, "SQL46010", "not")); + ParserTestUtils.ErrorTest160("create function f1() returns @v1 table (c1 int identity(1,1) not for replication) begin return end", + new ParserErrorInfo(61, "SQL46010", "not")); + ParserTestUtils.ErrorTest170("create function f1() returns @v1 table (c1 int identity(1,1) not for replication) begin return end", new ParserErrorInfo(61, "SQL46010", "not")); ParserTestUtils.ErrorTest100("create type t1 as table (c1 int identity(1,1) not for replication)", new ParserErrorInfo(46, "SQL46010", "not")); @@ -6838,7 +6846,6 @@ RETURNS NVARCHAR(101) RETURN @first + ' ' + @last END;"; ParserTestUtils.ErrorTestFabricDW(scalarFunctionSyntax2, new ParserErrorInfo(scalarFunctionSyntax2.IndexOf("INLINE"), "SQL46010", "INLINE")); - string scalarFunctionSyntax3 = @"CREATE OR ALTER FUNCTION dbo.CountProducts ( @ProductTable AS dbo.ProductType READONLY @@ -6868,5 +6875,28 @@ FROM @SalesData END;"; ParserTestUtils.ErrorTestFabricDW(scalarFunctionSyntax4, new ParserErrorInfo(scalarFunctionSyntax4.IndexOf("NULL"), "SQL46010", "NULL")); } + + /// + /// Negative tests for Scalar Functions in Fabric DW. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void IdentityColumnNegativeTestsFabricDW() + { + string identityColumnSyntax = @"CREATE TABLE TestTable1 ( + ID INT IDENTITY(1,1), + Name VARCHAR(50) + ); + "; + ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax, new ParserErrorInfo(identityColumnSyntax.IndexOf("IDENTITY(") + 8, "SQL46010", "(")); + + string identityColumnSyntax2 = @"CREATE TABLE TestTable2 ( + RecordID BIGINT IDENTITY(100,5), + Description NVARCHAR(200) + ); + "; + ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax2, new ParserErrorInfo(identityColumnSyntax2.IndexOf("IDENTITY(") + 8, "SQL46010", "(")); + } } } diff --git a/Test/SqlDom/TestScripts/AlterDatabaseManualCutoverTests170.sql b/Test/SqlDom/TestScripts/AlterDatabaseManualCutoverTests170.sql new file mode 100644 index 00000000..71a106f3 --- /dev/null +++ b/Test/SqlDom/TestScripts/AlterDatabaseManualCutoverTests170.sql @@ -0,0 +1,10 @@ +ALTER DATABASE db + MODIFY (SERVICE_OBJECTIVE = 'HS_Gen5_16') WITH MANUAL_CUTOVER; + +ALTER DATABASE db + MODIFY (EDITION = 'Hyperscale') WITH MANUAL_CUTOVER; + +ALTER DATABASE db + MODIFY (SERVICE_OBJECTIVE = ELASTIC_POOL (NAME = [hspool])) WITH MANUAL_CUTOVER; + +ALTER DATABASE db PERFORM_CUTOVER; diff --git a/Test/SqlDom/TestScripts/CreateColumnStoreIndexTests170.sql b/Test/SqlDom/TestScripts/CreateColumnStoreIndexTests170.sql new file mode 100644 index 00000000..d9201bf4 --- /dev/null +++ b/Test/SqlDom/TestScripts/CreateColumnStoreIndexTests170.sql @@ -0,0 +1,8 @@ +CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI + ON T(A, B, C) ORDER(A, B); + +CREATE COLUMNSTORE INDEX NCCI + ON T(A, B, C) ORDER(A, B); + +CREATE CLUSTERED COLUMNSTORE INDEX CCI + ON T ORDER(A, B); diff --git a/Test/SqlDom/TestScripts/IdentityColumnTestsFabricDW.sql b/Test/SqlDom/TestScripts/IdentityColumnTestsFabricDW.sql new file mode 100644 index 00000000..43988f97 --- /dev/null +++ b/Test/SqlDom/TestScripts/IdentityColumnTestsFabricDW.sql @@ -0,0 +1,27 @@ +CREATE TABLE table1 ( + ID BIGINT IDENTITY +); + + +GO +CREATE TABLE Employees ( + EmployeeID BIGINT IDENTITY, + FirstName NVARCHAR (50), + LastName NVARCHAR (50) +); + + +GO +CREATE TABLE Orders ( + OrderID INT IDENTITY, + CustomerName VARCHAR (100) , + OrderDate DATETIME , + TotalAmount DECIMAL (10, 2) +); + + +GO +CREATE TABLE Products ( + ProductID BIGINT IDENTITY, + ProductName NVARCHAR (100) +); \ No newline at end of file diff --git a/global.json b/global.json index 17e2f860..0e56f422 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.410", + "version": "8.0.411", "rollForward": "latestMajor" }, "msbuild-sdks": { From 0a26b6d6a8483efedff464f77fadf140290beef0 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 30 Jul 2025 10:21:13 -0700 Subject: [PATCH 04/45] Add support for JSON Index creation syntax in SQL Server 2025 (TSql170) (#147) * Initial plan * Initial planning and exploration for JSON Index support Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Add JSON Index support - AST definitions, grammar rules, and script generation Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Complete JSON Index implementation - fix parser recognition and add correct baseline Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Final fix - correct error count expectations for older SQL parser versions Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Remove antlr-2.7.5.jar file from repository Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Remove tmp folder from repository and add to .gitignore Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Revert global.json SDK version back to 8.0.410 Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Remove NUL file - ANTLR build artifact Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Use CreateXmlIndexStatement pattern - inherit from IndexStatement instead of TSqlStatement Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Address reviewer feedback: rename JsonPaths to ForJsonPaths and add comprehensive error tests Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> * Fix error test position calculations for accurate error reporting Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> * Change JSON Index column from ColumnReferenceExpression to Identifier type Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Remove ErrorTest90/ErrorTest100 calls and fix missing comma in Only170SyntaxTests Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Fix parser error test offsets - correct positions for JSON keyword errors Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Remove ErrorTest80 call from ParserErrorsTests as requested Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Remove ErrorTest160 calls from ParserErrorsTests for JSON Index - only TSql170 tests needed Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> * fixing the test * Remove filegroup support from JSON Index syntax Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Fix JSON Index error count in Only170SyntaxTests - correct to 8 errors after filegroup removal Co-authored-by: llali <17187348+llali@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: llali <17187348+llali@users.noreply.github.com> Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> Co-authored-by: Leila Lali --- .gitignore | 5 +- SqlScriptDom/Parser/TSql/Ast.xml | 7 +++ SqlScriptDom/Parser/TSql/TSql170.g | 56 +++++++++++++++++++ ...neratorVisitor.CreateJsonIndexStatement.cs | 49 ++++++++++++++++ .../SqlDom/Baselines170/JsonIndexTests170.sql | 29 ++++++++++ Test/SqlDom/Only170SyntaxTests.cs | 1 + Test/SqlDom/ParserErrorsTests.cs | 52 +++++++++++++++++ Test/SqlDom/TestScripts/JsonIndexTests170.sql | 31 ++++++++++ global.json | 2 +- 9 files changed, 230 insertions(+), 2 deletions(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateJsonIndexStatement.cs create mode 100644 Test/SqlDom/Baselines170/JsonIndexTests170.sql create mode 100644 Test/SqlDom/TestScripts/JsonIndexTests170.sql diff --git a/.gitignore b/.gitignore index c606ba98..997c1729 100644 --- a/.gitignore +++ b/.gitignore @@ -356,4 +356,7 @@ MigrationBackup/ out/ # Project packages folder -.packages/ \ No newline at end of file +.packages/ + +# Temporary build artifacts +tmp/ \ No newline at end of file diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index ffeec7c8..e5764b29 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -4600,6 +4600,13 @@ + + + + + + + diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index b5b4a2b1..031bc61b 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -883,6 +883,9 @@ create2005Statements returns [TSqlStatement vResult = null] | {NextTokenMatches(CodeGenerationSupporter.ColumnStore)}? vResult=createColumnStoreIndexStatement[null, null] + | + {NextTokenMatches(CodeGenerationSupporter.Json)}? + vResult=createJsonIndexStatement[null, null] | {NextTokenMatches(CodeGenerationSupporter.Contract)}? vResult=createContractStatement @@ -16844,6 +16847,7 @@ createIndexStatement returns [TSqlStatement vResult = null] ( vResult=createRelationalIndexStatement[tUnique, isClustered] | vResult=createColumnStoreIndexStatement[tUnique, isClustered] + | vResult=createJsonIndexStatement[tUnique, isClustered] ) ) | @@ -16980,6 +16984,58 @@ createColumnStoreIndexStatement [IToken tUnique, bool? isClustered] returns [Cre )? ; +createJsonIndexStatement [IToken tUnique, bool? isClustered] returns [CreateJsonIndexStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + SchemaObjectName vSchemaObjectName; + Identifier vJsonColumn; + StringLiteral vPath; + + if (tUnique != null) + { + ThrowIncorrectSyntaxErrorException(tUnique); + } + if (isClustered.HasValue) + { + ThrowIncorrectSyntaxErrorException(LT(1)); + } +} + : tJson:Identifier tIndex:Index vIdentifier=identifier + { + Match(tJson, CodeGenerationSupporter.Json); + vResult.Name = vIdentifier; + } + tOn:On vSchemaObjectName=schemaObjectThreePartName + { + vResult.OnName = vSchemaObjectName; + } + LeftParenthesis vJsonColumn=identifier tRParen:RightParenthesis + { + vResult.JsonColumn = vJsonColumn; + UpdateTokenInfo(vResult, tRParen); + } + ( + tFor:For LeftParenthesis + vPath=stringLiteral + { + AddAndUpdateTokenInfo(vResult, vResult.ForJsonPaths, vPath); + } + ( + Comma vPath=stringLiteral + { + AddAndUpdateTokenInfo(vResult, vResult.ForJsonPaths, vPath); + } + )* + RightParenthesis + )? + ( + // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + With + indexOptionList[IndexAffectingStatement.CreateIndex, vResult.IndexOptions, vResult] + )? + ; + indexKeyColumnList[CreateIndexStatement vParent] { ColumnWithSortOrder vColumnWithSortOrder; diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateJsonIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateJsonIndexStatement.cs new file mode 100644 index 00000000..e7665dd7 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateJsonIndexStatement.cs @@ -0,0 +1,49 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(CreateJsonIndexStatement node) + { + GenerateKeyword(TSqlTokenType.Create); + + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Json); + + GenerateSpaceAndKeyword(TSqlTokenType.Index); + + // name + GenerateSpaceAndFragmentIfNotNull(node.Name); + + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.On); + GenerateSpaceAndFragmentIfNotNull(node.OnName); + + // JSON column + if (node.JsonColumn != null) + { + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.JsonColumn); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + + // FOR clause with JSON paths + if (node.ForJsonPaths != null && node.ForJsonPaths.Count > 0) + { + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.For); + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.ForJsonPaths); + } + + GenerateIndexOptions(node.IndexOptions); + } + } +} \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/JsonIndexTests170.sql b/Test/SqlDom/Baselines170/JsonIndexTests170.sql new file mode 100644 index 00000000..f6010ded --- /dev/null +++ b/Test/SqlDom/Baselines170/JsonIndexTests170.sql @@ -0,0 +1,29 @@ +CREATE JSON INDEX IX_JSON_Basic + ON dbo.Users (JsonData); + +CREATE JSON INDEX IX_JSON_SinglePath + ON dbo.Users (JsonData) + FOR ('$.name'); + +CREATE JSON INDEX IX_JSON_MultiplePaths + ON dbo.Users (JsonData) + FOR ('$.name', '$.email', '$.age'); + +CREATE JSON INDEX IX_JSON_WithOptions + ON dbo.Users (JsonData) WITH (FILLFACTOR = 90, ONLINE = OFF); + +CREATE JSON INDEX IX_JSON_Complete + ON dbo.Users (JsonData) + FOR ('$.profile.name', '$.profile.email') WITH (MAXDOP = 4, DATA_COMPRESSION = ROW); + +CREATE JSON INDEX IX_JSON_Schema + ON MySchema.MyTable (JsonColumn) + FOR ('$.properties.value'); + +CREATE JSON INDEX [IX JSON Index] + ON [dbo].[Users] ([Json Data]) + FOR ('$.data.attributes'); + +CREATE JSON INDEX IX_JSON_Complex + ON dbo.Documents (Content) + FOR ('$.metadata.title', '$.content.sections[*].text', '$.tags[*]'); \ No newline at end of file diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index bd84d403..654fcdb4 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -10,6 +10,7 @@ public partial class SqlDomTests private static readonly ParserTest[] Only170TestInfos = { new ParserTest170("RegexpTVFTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), + new ParserTest170("JsonIndexTests170.sql", nErrors80: 2, nErrors90: 8, nErrors100: 8, nErrors110: 8, nErrors120: 8, nErrors130: 8, nErrors140: 8, nErrors150: 8, nErrors160: 8), new ParserTest170("AlterDatabaseManualCutoverTests170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("CreateColumnStoreIndexTests170.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0) }; diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 57f6264d..f7632b52 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -4384,6 +4384,58 @@ public void CreateIndexStatementErrorTest() new ParserErrorInfo(47, "SQL46010", "col1")); } + /// + /// JSON Index error tests - ensure JSON Index syntax is rejected in older versions and malformed syntax produces appropriate errors + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CreateJsonIndexStatementErrorTest() + { + // JSON Index syntax should not be supported in SQL Server versions prior to 2025 (TSql170) + // Test basic JSON Index syntax in older versions + ParserTestUtils.ErrorTest160("CREATE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(7, "SQL46010", "JSON")); + ParserTestUtils.ErrorTest150("CREATE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(7, "SQL46010", "JSON")); + ParserTestUtils.ErrorTest140("CREATE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(7, "SQL46010", "JSON")); + ParserTestUtils.ErrorTest130("CREATE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(7, "SQL46010", "JSON")); + ParserTestUtils.ErrorTest120("CREATE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(7, "SQL46010", "JSON")); + ParserTestUtils.ErrorTest110("CREATE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(7, "SQL46010", "JSON")); + + + + // Test that UNIQUE and CLUSTERED/NONCLUSTERED are not allowed with JSON indexes in TSql170 + TSql170Parser parser170 = new TSql170Parser(true); + ParserTestUtils.ErrorTest(parser170, "CREATE UNIQUE JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(14, "SQL46010", "JSON")); + ParserTestUtils.ErrorTest(parser170, "CREATE CLUSTERED JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(17, "SQL46005", "COLUMNSTORE", "JSON")); + ParserTestUtils.ErrorTest(parser170, "CREATE NONCLUSTERED JSON INDEX idx1 ON table1 (jsonColumn)", + new ParserErrorInfo(20, "SQL46005", "COLUMNSTORE", "JSON")); + + // Test malformed JSON Index syntax in TSql170 + // Missing column specification + ParserTestUtils.ErrorTest(parser170, "CREATE JSON INDEX idx1 ON table1", + new ParserErrorInfo(32, "SQL46029")); + + // Empty FOR clause + ParserTestUtils.ErrorTest(parser170, "CREATE JSON INDEX idx1 ON table1 (jsonColumn) FOR ()", + new ParserErrorInfo(51, "SQL46010", ")")); + + // Invalid JSON path (missing quotes) + ParserTestUtils.ErrorTest(parser170, "CREATE JSON INDEX idx1 ON table1 (jsonColumn) FOR ($.name)", + new ParserErrorInfo(51, "SQL46010", "$")); + + // Missing table name + ParserTestUtils.ErrorTest(parser170, "CREATE JSON INDEX idx1 ON (jsonColumn)", + new ParserErrorInfo(26, "SQL46010", "(")); + } + /// /// Check that the value of MAXDOP index option is within range /// diff --git a/Test/SqlDom/TestScripts/JsonIndexTests170.sql b/Test/SqlDom/TestScripts/JsonIndexTests170.sql new file mode 100644 index 00000000..2a0f1ad7 --- /dev/null +++ b/Test/SqlDom/TestScripts/JsonIndexTests170.sql @@ -0,0 +1,31 @@ +-- Basic JSON index creation +CREATE JSON INDEX IX_JSON_Basic ON dbo.Users (JsonData); + +-- JSON index with FOR clause (single path) +CREATE JSON INDEX IX_JSON_SinglePath ON dbo.Users (JsonData) +FOR ('$.name'); + +-- JSON index with FOR clause (multiple paths) +CREATE JSON INDEX IX_JSON_MultiplePaths ON dbo.Users (JsonData) +FOR ('$.name', '$.email', '$.age'); + +-- JSON index with WITH options +CREATE JSON INDEX IX_JSON_WithOptions ON dbo.Users (JsonData) +WITH (FILLFACTOR = 90, ONLINE = OFF); + +-- JSON index with FOR clause and WITH options +CREATE JSON INDEX IX_JSON_Complete ON dbo.Users (JsonData) +FOR ('$.profile.name', '$.profile.email') +WITH (MAXDOP = 4, DATA_COMPRESSION = ROW); + +-- JSON index on schema-qualified table +CREATE JSON INDEX IX_JSON_Schema ON MySchema.MyTable (JsonColumn) +FOR ('$.properties.value'); + +-- JSON index with quoted identifiers +CREATE JSON INDEX [IX JSON Index] ON [dbo].[Users] ([Json Data]) +FOR ('$.data.attributes'); + +-- JSON index with complex path expressions +CREATE JSON INDEX IX_JSON_Complex ON dbo.Documents (Content) +FOR ('$.metadata.title', '$.content.sections[*].text', '$.tags[*]'); \ No newline at end of file diff --git a/global.json b/global.json index 0e56f422..457d429d 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.411", + "version": "8.0.117", "rollForward": "latestMajor" }, "msbuild-sdks": { From 44764473c75cee13c33037efef5bd9d7c3c271f7 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Mon, 4 Aug 2025 14:21:14 -0700 Subject: [PATCH 05/45] Add support for Vector index syntax in T-SQL parser with separate index option classes (#150) * Initial plan * Implement vector index support - add grammar, AST classes, and script generators Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Consolidate vector index options and remove duplicate Vector constant Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Revert to original design with separate VectorMetricIndexOption and VectorTypeIndexOption classes Co-authored-by: llali <17187348+llali@users.noreply.github.com> * fixing the parser * Update vector index option values to uppercase in baseline test file Co-authored-by: llali <17187348+llali@users.noreply.github.com> * Add comprehensive vector index error test cases to ParserErrorsTests Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> * Remove invalid negative test case for vector index - CREATE INDEX syntax is valid for regular indexes Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> * fixing the test --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: llali <17187348+llali@users.noreply.github.com> Co-authored-by: Leila Lali Co-authored-by: zijchen <13544267+zijchen@users.noreply.github.com> --- SqlScriptDom/Parser/TSql/Ast.xml | 15 ++++ .../Parser/TSql/CodeGenerationSupporter.cs | 5 ++ SqlScriptDom/Parser/TSql/IndexOptionHelper.cs | 3 + SqlScriptDom/Parser/TSql/IndexOptionKind.cs | 2 + SqlScriptDom/Parser/TSql/OptionsHelper.cs | 2 +- SqlScriptDom/Parser/TSql/TSql170.g | 75 +++++++++++++++++ SqlScriptDom/Parser/TSql/VectorIndexType.cs | 23 ++++++ .../Parser/TSql/VectorIndexTypeHelper.cs | 21 +++++ SqlScriptDom/Parser/TSql/VectorMetricType.cs | 25 ++++++ .../Parser/TSql/VectorMetricTypeHelper.cs | 25 ++++++ ...ratorVisitor.CreateVectorIndexStatement.cs | 48 +++++++++++ ...eneratorVisitor.VectorMetricIndexOption.cs | 19 +++++ ...tGeneratorVisitor.VectorTypeIndexOption.cs | 19 +++++ .../Baselines170/VectorIndexTests170.sql | 37 +++++++++ Test/SqlDom/Only170SyntaxTests.cs | 1 + Test/SqlDom/ParserErrorsTests.cs | 81 +++++++++++++++++++ .../TestScripts/VectorIndexTests170.sql | 46 +++++++++++ 17 files changed, 446 insertions(+), 1 deletion(-) create mode 100644 SqlScriptDom/Parser/TSql/VectorIndexType.cs create mode 100644 SqlScriptDom/Parser/TSql/VectorIndexTypeHelper.cs create mode 100644 SqlScriptDom/Parser/TSql/VectorMetricType.cs create mode 100644 SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateVectorIndexStatement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorMetricIndexOption.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorTypeIndexOption.cs create mode 100644 Test/SqlDom/Baselines170/VectorIndexTests170.sql create mode 100644 Test/SqlDom/TestScripts/VectorIndexTests170.sql diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index e5764b29..c8ebb38e 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -4607,6 +4607,13 @@ + + + + + + + @@ -4639,6 +4646,14 @@ + + + + + + + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 7c00dbef..4deaa86e 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -225,6 +225,7 @@ internal static class CodeGenerationSupporter internal const string CompressionDelay = "COMPRESSION_DELAY"; internal const string CompressAllRowGroups = "COMPRESS_ALL_ROW_GROUPS"; internal const string Concat = "CONCAT"; + internal const string Cosine = "COSINE"; internal const string Configuration = "CONFIGURATION"; internal const string ConnectionOptions = "CONNECTION_OPTIONS"; internal const string Contained = "CONTAINED"; @@ -299,6 +300,8 @@ internal static class CodeGenerationSupporter internal const string Dependents = "DEPENDENTS"; internal const string Description = "DESCRIPTION"; internal const string DesiredState = "DESIRED_STATE"; + internal const string DiskANN = "DISKANN"; + internal const string Dot = "DOT"; internal const string Delay = "DELAY"; internal const string DelayedDurability = "DELAYED_DURABILITY"; internal const string DelimitedText = "DELIMITEDTEXT"; @@ -347,6 +350,7 @@ internal static class CodeGenerationSupporter internal const string EnvironmentVariables = "ENVIRONMENT_VARIABLES"; internal const string Equal = "="; internal const string Error = "ERROR"; + internal const string Euclidean = "EUCLIDEAN"; internal const string ErrorBrokerConversations = "ERROR_BROKER_CONVERSATIONS"; internal const string ErrorDataSource = "ERRORFILE_DATA_SOURCE"; internal const string ErrorFile = "ERRORFILE"; @@ -612,6 +616,7 @@ internal static class CodeGenerationSupporter internal const string MessageForwarding = "MESSAGE_FORWARDING"; internal const string MessageForwardSize = "MESSAGE_FORWARD_SIZE"; internal const string MigrationState = "MIGRATION_STATE"; + internal const string Metric = "METRIC"; internal const string Min = "MIN"; internal const string MinGrantPercent = "MIN_GRANT_PERCENT"; internal const string MinCpuPercent = "MIN_CPU_PERCENT"; diff --git a/SqlScriptDom/Parser/TSql/IndexOptionHelper.cs b/SqlScriptDom/Parser/TSql/IndexOptionHelper.cs index d5529338..1a0545ff 100644 --- a/SqlScriptDom/Parser/TSql/IndexOptionHelper.cs +++ b/SqlScriptDom/Parser/TSql/IndexOptionHelper.cs @@ -43,6 +43,9 @@ private IndexOptionHelper() AddOptionMapping(IndexOptionKind.XmlCompression, CodeGenerationSupporter.XmlCompression, SqlVersionFlags.TSql160AndAbove); + AddOptionMapping(IndexOptionKind.VectorMetric, CodeGenerationSupporter.Metric, SqlVersionFlags.TSql170AndAbove); + AddOptionMapping(IndexOptionKind.VectorType, CodeGenerationSupporter.Type, SqlVersionFlags.TSql170AndAbove); + } internal static readonly IndexOptionHelper Instance = new IndexOptionHelper(); diff --git a/SqlScriptDom/Parser/TSql/IndexOptionKind.cs b/SqlScriptDom/Parser/TSql/IndexOptionKind.cs index 795fa3f9..7f2914aa 100644 --- a/SqlScriptDom/Parser/TSql/IndexOptionKind.cs +++ b/SqlScriptDom/Parser/TSql/IndexOptionKind.cs @@ -38,6 +38,8 @@ public enum IndexOptionKind WaitAtLowPriority = 21, OptimizeForSequentialKey = 22, XmlCompression = 23, + VectorMetric = 24, + VectorType = 25, } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/OptionsHelper.cs b/SqlScriptDom/Parser/TSql/OptionsHelper.cs index 284ec4e3..7262ab68 100644 --- a/SqlScriptDom/Parser/TSql/OptionsHelper.cs +++ b/SqlScriptDom/Parser/TSql/OptionsHelper.cs @@ -135,7 +135,7 @@ internal SqlVersionFlags MapSqlVersionToSqlVersionFlags(SqlVersion sqlVersion) } } - internal OptionType ParseOption(antlr.IToken token, SqlVersionFlags version) + internal virtual OptionType ParseOption(antlr.IToken token, SqlVersionFlags version) { OptionInfo optionInfo; if (_stringToOptionInfo.TryGetValue(token.getText(), out optionInfo) && diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 031bc61b..1ef43398 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -886,6 +886,9 @@ create2005Statements returns [TSqlStatement vResult = null] | {NextTokenMatches(CodeGenerationSupporter.Json)}? vResult=createJsonIndexStatement[null, null] + | + {NextTokenMatches(CodeGenerationSupporter.Vector)}? + vResult=createVectorIndexStatement[null, null] | {NextTokenMatches(CodeGenerationSupporter.Contract)}? vResult=createContractStatement @@ -16848,6 +16851,7 @@ createIndexStatement returns [TSqlStatement vResult = null] vResult=createRelationalIndexStatement[tUnique, isClustered] | vResult=createColumnStoreIndexStatement[tUnique, isClustered] | vResult=createJsonIndexStatement[tUnique, isClustered] + | vResult=createVectorIndexStatement[tUnique, isClustered] ) ) | @@ -17036,6 +17040,50 @@ createJsonIndexStatement [IToken tUnique, bool? isClustered] returns [CreateJson )? ; +createVectorIndexStatement [IToken tUnique, bool? isClustered] returns [CreateVectorIndexStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + SchemaObjectName vSchemaObjectName; + Identifier vVectorColumn; + FileGroupOrPartitionScheme vFileGroupOrPartitionScheme; + + if (tUnique != null) + { + ThrowIncorrectSyntaxErrorException(tUnique); + } + if (isClustered.HasValue) + { + ThrowIncorrectSyntaxErrorException(LT(1)); + } +} + : tVector:Identifier tIndex:Index vIdentifier=identifier + { + Match(tVector, CodeGenerationSupporter.Vector); + vResult.Name = vIdentifier; + } + tOn:On vSchemaObjectName=schemaObjectThreePartName + { + vResult.OnName = vSchemaObjectName; + } + LeftParenthesis vVectorColumn=identifier tRParen:RightParenthesis + { + vResult.VectorColumn = vVectorColumn; + UpdateTokenInfo(vResult, tRParen); + } + ( + // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + With + indexOptionList[IndexAffectingStatement.CreateIndex, vResult.IndexOptions, vResult] + )? + ( + On vFileGroupOrPartitionScheme=filegroupOrPartitionScheme + { + vResult.OnFileGroupOrPartitionScheme = vFileGroupOrPartitionScheme; + } + )? + ; + indexKeyColumnList[CreateIndexStatement vParent] { ColumnWithSortOrder vColumnWithSortOrder; @@ -17680,6 +17728,12 @@ indexOption returns [IndexOption vResult = null] | {NextTokenMatches(CodeGenerationSupporter.WaitAtLowPriority)}? vResult=waitAtLowPriorityOption + | + {NextTokenMatches(CodeGenerationSupporter.Metric)}? + vResult=vectorMetricOption + | + {NextTokenMatches(CodeGenerationSupporter.Type)}? + vResult=vectorTypeOption | vResult=indexStateOption ; @@ -27669,6 +27723,27 @@ xmlCompressionOption returns [XmlCompressionOption vResult = FragmentFactory.Cre )? ; +vectorMetricOption returns [VectorMetricIndexOption vResult = FragmentFactory.CreateFragment()] + : tMetric:Identifier EqualsSign tMetricValue:AsciiStringLiteral + { + Match(tMetric, CodeGenerationSupporter.Metric); + vResult.OptionKind = IndexOptionKind.VectorMetric; + vResult.MetricType = VectorMetricTypeHelper.Instance.ParseOption(tMetricValue); + + UpdateTokenInfo(vResult, tMetric); + } + ; + +vectorTypeOption returns [VectorTypeIndexOption vResult = FragmentFactory.CreateFragment()] + : tType:Identifier EqualsSign tTypeValue:AsciiStringLiteral + { + Match(tType, CodeGenerationSupporter.Type); + vResult.OptionKind = IndexOptionKind.VectorType; + vResult.VectorType = VectorIndexTypeHelper.Instance.ParseOption(tTypeValue); + UpdateTokenInfo(vResult, tType); + } + ; + compressionPartitionRange returns [CompressionPartitionRange vResult = FragmentFactory.CreateFragment()] { ScalarExpression vExpression; diff --git a/SqlScriptDom/Parser/TSql/VectorIndexType.cs b/SqlScriptDom/Parser/TSql/VectorIndexType.cs new file mode 100644 index 00000000..8f70a021 --- /dev/null +++ b/SqlScriptDom/Parser/TSql/VectorIndexType.cs @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + + + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ +#pragma warning disable 1591 + + /// + /// The possible values for vector index type + /// + public enum VectorIndexType + { + DiskANN = 0 + } + +#pragma warning restore 1591 +} + \ No newline at end of file diff --git a/SqlScriptDom/Parser/TSql/VectorIndexTypeHelper.cs b/SqlScriptDom/Parser/TSql/VectorIndexTypeHelper.cs new file mode 100644 index 00000000..602617f6 --- /dev/null +++ b/SqlScriptDom/Parser/TSql/VectorIndexTypeHelper.cs @@ -0,0 +1,21 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + + + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + + internal class VectorIndexTypeHelper : OptionsHelper + { + private VectorIndexTypeHelper() + { + AddOptionMapping(VectorIndexType.DiskANN, "'" + CodeGenerationSupporter.DiskANN + "'"); + } + + public static readonly VectorIndexTypeHelper Instance = new VectorIndexTypeHelper(); + } +} \ No newline at end of file diff --git a/SqlScriptDom/Parser/TSql/VectorMetricType.cs b/SqlScriptDom/Parser/TSql/VectorMetricType.cs new file mode 100644 index 00000000..44b24a8d --- /dev/null +++ b/SqlScriptDom/Parser/TSql/VectorMetricType.cs @@ -0,0 +1,25 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + + + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ +#pragma warning disable 1591 + + /// + /// The possible values for vector index metric + /// + public enum VectorMetricType + { + Cosine = 0, + Dot = 1, + Euclidean = 2 + } + +#pragma warning restore 1591 +} + \ No newline at end of file diff --git a/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs b/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs new file mode 100644 index 00000000..6b1479ad --- /dev/null +++ b/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs @@ -0,0 +1,25 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + + + +using static Microsoft.SqlServer.TransactSql.ScriptDom.SensitivityClassification; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + + internal class VectorMetricTypeHelper : OptionsHelper + { + private VectorMetricTypeHelper() + { + AddOptionMapping(VectorMetricType.Cosine, "'" + CodeGenerationSupporter.Cosine + "'"); + AddOptionMapping(VectorMetricType.Dot, "'" + CodeGenerationSupporter.Dot + "'"); + AddOptionMapping(VectorMetricType.Euclidean, "'" + CodeGenerationSupporter.Euclidean + "'"); + } + + public static readonly VectorMetricTypeHelper Instance = new VectorMetricTypeHelper(); + } +} \ No newline at end of file diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateVectorIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateVectorIndexStatement.cs new file mode 100644 index 00000000..cb47a2f2 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateVectorIndexStatement.cs @@ -0,0 +1,48 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(CreateVectorIndexStatement node) + { + GenerateKeyword(TSqlTokenType.Create); + + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Vector); + + GenerateSpaceAndKeyword(TSqlTokenType.Index); + + // name + GenerateSpaceAndFragmentIfNotNull(node.Name); + + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.On); + GenerateSpaceAndFragmentIfNotNull(node.OnName); + + // Vector column + if (node.VectorColumn != null) + { + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.VectorColumn); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + + GenerateIndexOptions(node.IndexOptions); + + if (node.OnFileGroupOrPartitionScheme != null) + { + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.On); + + GenerateSpaceAndFragmentIfNotNull(node.OnFileGroupOrPartitionScheme); + } + } + } +} \ No newline at end of file diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorMetricIndexOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorMetricIndexOption.cs new file mode 100644 index 00000000..9beeeaf7 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorMetricIndexOption.cs @@ -0,0 +1,19 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(VectorMetricIndexOption node) + { + IndexOptionHelper.Instance.GenerateSourceForOption(_writer, node.OptionKind); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + VectorMetricTypeHelper.Instance.GenerateSourceForOption(_writer, node.MetricType); + } + } +} \ No newline at end of file diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorTypeIndexOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorTypeIndexOption.cs new file mode 100644 index 00000000..85bcadba --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorTypeIndexOption.cs @@ -0,0 +1,19 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(VectorTypeIndexOption node) + { + IndexOptionHelper.Instance.GenerateSourceForOption(_writer, node.OptionKind); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + VectorIndexTypeHelper.Instance.GenerateSourceForOption(_writer, node.VectorType); + } + } +} \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/VectorIndexTests170.sql b/Test/SqlDom/Baselines170/VectorIndexTests170.sql new file mode 100644 index 00000000..729b3abc --- /dev/null +++ b/Test/SqlDom/Baselines170/VectorIndexTests170.sql @@ -0,0 +1,37 @@ +CREATE VECTOR INDEX IX_Vector_Basic + ON dbo.Documents (VectorData); + +CREATE VECTOR INDEX IX_Vector_Cosine + ON dbo.Documents (VectorData) WITH (METRIC = 'COSINE'); + +CREATE VECTOR INDEX IX_Vector_Dot + ON dbo.Documents (VectorData) WITH (METRIC = 'DOT'); + +CREATE VECTOR INDEX IX_Vector_Euclidean + ON dbo.Documents (VectorData) WITH (METRIC = 'EUCLIDEAN'); + +CREATE VECTOR INDEX IX_Vector_DiskANN + ON dbo.Documents (VectorData) WITH (TYPE = 'DISKANN'); + +CREATE VECTOR INDEX IX_Vector_Complete + ON dbo.Documents (VectorData) WITH (METRIC = 'COSINE', TYPE = 'DISKANN'); + +CREATE VECTOR INDEX IX_Vector_MaxDop + ON dbo.Documents (VectorData) WITH (MAXDOP = 4); + +CREATE VECTOR INDEX IX_Vector_AllOptions + ON dbo.Documents (VectorData) WITH (METRIC = 'DOT', TYPE = 'DISKANN', MAXDOP = 8); + +CREATE VECTOR INDEX IX_Vector_Schema + ON MySchema.MyTable (VectorColumn) WITH (METRIC = 'EUCLIDEAN'); + +CREATE VECTOR INDEX [IX Vector Index] + ON [dbo].[Documents] ([Vector Data]) WITH (METRIC = 'COSINE'); + +CREATE VECTOR INDEX IX_Vector_Filegroup + ON dbo.Documents (VectorData) WITH (METRIC = 'COSINE') + ON [PRIMARY]; + +CREATE VECTOR INDEX IX_Vector_DefaultFG + ON dbo.Documents (VectorData) WITH (METRIC = 'DOT') + ON "default"; \ No newline at end of file diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 654fcdb4..05ade644 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -11,6 +11,7 @@ public partial class SqlDomTests { new ParserTest170("RegexpTVFTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), new ParserTest170("JsonIndexTests170.sql", nErrors80: 2, nErrors90: 8, nErrors100: 8, nErrors110: 8, nErrors120: 8, nErrors130: 8, nErrors140: 8, nErrors150: 8, nErrors160: 8), + new ParserTest170("VectorIndexTests170.sql", nErrors80: 2, nErrors90: 12, nErrors100: 12, nErrors110: 12, nErrors120: 12, nErrors130: 12, nErrors140: 12, nErrors150: 12, nErrors160: 12), new ParserTest170("AlterDatabaseManualCutoverTests170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("CreateColumnStoreIndexTests170.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0) }; diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index f7632b52..23d2be16 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -6950,5 +6950,86 @@ Description NVARCHAR(200) "; ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax2, new ParserErrorInfo(identityColumnSyntax2.IndexOf("IDENTITY(") + 8, "SQL46010", "(")); } + + /// + /// Negative tests for VECTOR INDEX syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void VectorIndexNegativeTests() + { + // Missing INDEX keyword + ParserTestUtils.ErrorTest170("CREATE VECTOR IX_Test ON dbo.Documents (VectorData)", + new ParserErrorInfo(7, "SQL46010", "VECTOR")); + + // Missing table name + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON (VectorData)", + new ParserErrorInfo(31, "SQL46010", "(")); + + // Missing column specification + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents", + new ParserErrorInfo(44, "SQL46029", "")); + + // Empty column list + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents ()", + new ParserErrorInfo(46, "SQL46010", ")")); + + // Multiple columns (not supported for vector indexes) + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData, OtherColumn)", + new ParserErrorInfo(56, "SQL46010", ",")); + + // Invalid metric value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = 'invalid')", + new ParserErrorInfo(73, "SQL46010", "'invalid'")); + + // Invalid type value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (TYPE = 'invalid')", + new ParserErrorInfo(71, "SQL46010", "'invalid'")); + + // Missing option value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = )", + new ParserErrorInfo(73, "SQL46010", ")")); + + // Empty option value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = '')", + new ParserErrorInfo(73, "SQL46010", "''")); + + // Missing WITH keyword when options are present + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) (METRIC = 'cosine')", + new ParserErrorInfo(59, "SQL46010", "METRIC")); + + // Missing parentheses around options + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH METRIC = 'cosine'", + new ParserErrorInfo(63, "SQL46010", "METRIC")); + + // Invalid option name + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (INVALID_OPTION = 'value')", + new ParserErrorInfo(64, "SQL46010", "INVALID_OPTION")); + + // Metric value without quotes + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = cosine)", + new ParserErrorInfo(73, "SQL46010", "cosine")); + + // Type value without quotes + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (TYPE = DiskANN)", + new ParserErrorInfo(71, "SQL46010", "DiskANN")); + + // MAXDOP with invalid value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (MAXDOP = 'invalid')", + new ParserErrorInfo(73, "SQL46010", "'invalid'")); + + // MAXDOP with negative value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (MAXDOP = -1)", + new ParserErrorInfo(73, "SQL46010", "-")); + + // Missing equals sign in option + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC 'cosine')", + new ParserErrorInfo(64, "SQL46010", "METRIC")); + + // Incomplete WITH clause + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH", + new ParserErrorInfo(58, "SQL46010", "WITH")); + } } } diff --git a/Test/SqlDom/TestScripts/VectorIndexTests170.sql b/Test/SqlDom/TestScripts/VectorIndexTests170.sql new file mode 100644 index 00000000..d3a1a79b --- /dev/null +++ b/Test/SqlDom/TestScripts/VectorIndexTests170.sql @@ -0,0 +1,46 @@ +-- Basic VECTOR index creation +CREATE VECTOR INDEX IX_Vector_Basic ON dbo.Documents (VectorData); + +-- VECTOR index with METRIC option +CREATE VECTOR INDEX IX_Vector_Cosine ON dbo.Documents (VectorData) +WITH (METRIC = 'cosine'); + +CREATE VECTOR INDEX IX_Vector_Dot ON dbo.Documents (VectorData) +WITH (METRIC = 'dot'); + +CREATE VECTOR INDEX IX_Vector_Euclidean ON dbo.Documents (VectorData) +WITH (METRIC = 'euclidean'); + +-- VECTOR index with TYPE option +CREATE VECTOR INDEX IX_Vector_DiskANN ON dbo.Documents (VectorData) +WITH (TYPE = 'DiskANN'); + +-- VECTOR index with both METRIC and TYPE options +CREATE VECTOR INDEX IX_Vector_Complete ON dbo.Documents (VectorData) +WITH (METRIC = 'cosine', TYPE = 'DiskANN'); + +-- VECTOR index with MAXDOP option +CREATE VECTOR INDEX IX_Vector_MaxDop ON dbo.Documents (VectorData) +WITH (MAXDOP = 4); + +-- VECTOR index with multiple options +CREATE VECTOR INDEX IX_Vector_AllOptions ON dbo.Documents (VectorData) +WITH (METRIC = 'dot', TYPE = 'DiskANN', MAXDOP = 8); + +-- VECTOR index on schema-qualified table +CREATE VECTOR INDEX IX_Vector_Schema ON MySchema.MyTable (VectorColumn) +WITH (METRIC = 'euclidean'); + +-- VECTOR index with quoted identifiers +CREATE VECTOR INDEX [IX Vector Index] ON [dbo].[Documents] ([Vector Data]) +WITH (METRIC = 'cosine'); + +-- VECTOR index with filegroup +CREATE VECTOR INDEX IX_Vector_Filegroup ON dbo.Documents (VectorData) +WITH (METRIC = 'cosine') +ON [PRIMARY]; + +-- VECTOR index with filegroup as string +CREATE VECTOR INDEX IX_Vector_DefaultFG ON dbo.Documents (VectorData) +WITH (METRIC = 'dot') +ON "default"; \ No newline at end of file From 63236ba30ef99397d910cd7e9876c59812f9a8b2 Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Thu, 7 Aug 2025 16:03:33 -0700 Subject: [PATCH 06/45] Sync Repos: Release 170.82.0 (#151) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Merged PR 1735207: Adding regex functions tests # Pull Request Template for ScriptDom ## Description This PR adds tests for regex intrinsic functions. Functional Spec - https://microsoft.sharepoint.com/:w:/t/Ad-Astra/EZAk15L-vkJHqsaCybly0QIB0eBUdv02BBaHUAl48aY_Pw?e=NPRj0w ## Code Change - [x] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [x] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [x] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [x] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information None Adding regex functions tests Related work items: #4005966 * Merged PR 1718694: [ai_generate_chunks] Add syntax to ScriptDom # Pull Request Template for ScriptDom ## Description # Add syntax and script generation support for AI_GENERATE_CHUNKS table-valued function ## Description This PR introduces parser and script generator support for the new built-in table-valued function (TVF) `AI_GENERATE_CHUNKS`. `AI_GENERATE_CHUNKS` enables chunking of input text based on a specified strategy. It accepts required and optional parameters and supports aliasing for cross apply scenarios. ### Syntax supported ```sql SELECT * FROM AI_GENERATE_CHUNKS ( source = 'some text', chunk_type = fixed, chunk_size = 5, overlap = 2, enable_chunk_set_id = 1 ); ``` ### Parameters | Parameter | Required | Type | Description | |------------------------|----------|-------------------|--------------------------------------------------------------------| | `source` | Yes | `ScalarExpression`| Input text to be chunked | | `chunk_type` | Yes | `Identifier` | Type of chunking strategy. Currently only `fixed` is supported | | `chunk_size` | Yes | `ScalarExpression`| Number of tokens per chunk | | `overlap` | No | `ScalarExpression`| Optional token overlap between adjacent chunks | | `enable_chunk_set_id` | No | `ScalarExpression`| Optional flag. If set, adds a `chunk_set_id` column to the result | ### Summary of Changes - Added support for the `ai_generate_chunks` table-valued function to the SQL parser. - Introduced new AST class `AiGenerateChunksTableReference` with members: - `Source` - `ChunkType` - `ChunkSize` - `Overlap` - `EnableChunkSetId` - Added grammar rule for parsing `ai_generate_chunks`. - Implemented corresponding visitor logic for script generation (`SqlScriptGeneratorVisitor`). - Added unit tests for: - Positive cases covering all combinations of optional parameters. - Negative cases for missing/invalid parameter order, unexpected tokens, or malformed expressions. ### Example Use Cases This function is designed to support downstream AI workflows where long documents need to be split into manageable token chunks for embedding generation or other ML tasks. ## Code Change - [X] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [X] Code changes are accompanied by appropriate unit tests - [X] Identified and included SMEs needed to review code changes - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [X] Follow the [steps](https://msdata.vi... * Update .NET SDK to latest patch version * Merged PR 1724944: [MSJSON] added support for json_objectagg and Returning JSON option for json_object, json_array # Pull Request Template for ScriptDom ## Description adds support to scriptdom for new functions and options in SQLServer. Specifically support for - Json_objectagg with options NULL ON NULL/ABSENT ON NULL and RETURNING JSON. - Support for RETURNING JSON option for json_object, json_array. Added relevant test for all options. ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [X] Code changes are accompanied by appropriate unit tests - [X] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature Added Test. * Merged PR 1724727: [ai_generate_embeddings] Add syntax to ScriptDom # Pull Request Template for ScriptDom ## Description This PR adds support for the new `AI_GENERATE_EMBEDDINGS` T-SQL built-in function syntax: ```sql AI_GENERATE_EMBEDDINGS('input text' USE MODEL model_name [PARAMETERS (...optional JSON...)]) ``` Input expression: required string or expression representing the text to embed. USE MODEL model_name: required keyword clause specifying the embedding model. PARAMETERS ( ... ): optional block allowing additional JSON parameters to customize embedding behavior. ### Examples ```sql -- Basic usage with required input and model SELECT AI_GENERATE_EMBEDDINGS('Hello world' USE MODEL MyEmbeddingModel); -- Usage with optional PARAMETERS block SELECT AI_GENERATE_EMBEDDINGS('Hello world' USE MODEL MyEmbeddingModel PARAMETERS (TRY_CONVERT(JSON, N'{"param":"value"}'))); ``` ### Features - Adds `AiGenerateEmbeddingsFunctionCall` AST node. - Grammar recognizes required `USE MODEL` clause and optional `PARAMETERS` block. - Script generator visitor outputs syntax matching expected SQL Server formatting, with or without optional PARAMETERS. - Comprehensive unit tests cover: - Missing required keywords or values (e.g., missing USE, missing MODEL). - Misplaced keywords (e.g., PARAMETERS before input). - Invalid syntax like missing parentheses or incomplete expressions. - Extra commas or unknown parameters. - Negative tests aligned with expected SQL46010 and SQL46029 parser errors. - Supports round-tripping: parsed AST can be pretty-printed back to valid SQL matching the original input. ### Compatibility - Valid only in SQL Server with compatibility level 170 or higher. ## Code Change - [X] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [X] Code changes are accompanied by appropriate unit tests - [X] Identified and included SMEs needed to review code changes - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ---- #### AI description (iteration 1) #### PR Classification New feature implementation to add syntax support for the AI_GENERATE_EMBEDDINGS function in ScriptDom. #### PR Summary This PR introduces a new SQL function, AI_GENERATE_EMBEDDINGS, which allows users to send input text to external AI models and retrieve an em... * Merged PR 1752033: [modle_management]ScriptDom changes for external model support # Pull Request Template for ScriptDom ## Description Introduces syntax support for Create, Alter and Drop operation for External Model DDL CREATE CREATE EXTERNAL MODEL AUTHORIZATION owner WITH ( LOCATION = 'URL or FILE PATH', API_FORMAT = ‘OpenAI, Azure OpenAI, etc’, MODEL_TYPE = , MODEL = ‘text-embedding-ada-002,etc’, CREDENTIAL = , PARAMETERS = ‘{ “valid”:”JSON”}’ } | **Column Name** | **Data Type** | **Notes** | |-----------------------|---------------------|-----------| | `model_name` | `SYSNAME` | Name of the external model object | | `owner_name` | `SYSNAME` | Database principal that owns the external model object. Defaults to connected user if not specified. | | `location` | `NVARCHAR(4000)` | Location of the endpoint. Can be a URL (`https://...`) or file path (`mountpoint:\\...`). | | `api_format` | `NVARCHAR(100)` | Format of the API the endpoint accepts/produces. P0: Azure OpenAI, OpenAI, Ollama; P1: Local, Nvidia Triton, Databricks; P2: TBD | | `model_type` | `SYSNAME` | Model type for the data plane. P0: EMBEDDINGS; Post GA: CHAT, MODERATE, TRANSLATE, SPEECH. Only supported types are accepted. | | `model` | `NVARCHAR(100)` | Name of the embedding model used by the endpoint. | | `local_runtime_path` | `NVARCHAR(4000)` | Path to local model runtime (e.g., ONNX runtime). Required for local models. | | `credential` | `SYSNAME` | Name of the database scoped credential. Not used for ONNX Runtime. | | `parameters` | `JSON` | Default JSON parameters to be appended to the embeddings payload. | ## Code Change - [X] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [X] Code changes are accompanied by appropriate unit tests - [X] Identified and included SMEs needed to review code changes - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [X] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers ScriptDom channges ---- #### AI description (iteration 1) #### PR Classific... * Merged PR 1758352: Add ScriptDom support for VECTOR_SEARCH function # Pull Request Template for ScriptDom ## Description Added parser and script generator support for VECTOR_SEARCH Before submitting your pull request, please ensure you have completed the following: ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [ ] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers Add ScriptDom support for VECTOR_SEARCH function ---- #### AI description (iteration 1) #### PR Classification This pull request introduces a new feature by adding native ScriptDom support for the VECTOR_SEARCH function. #### PR Summary The changes implement parsing, AST definition, and script generation for VECTOR_SEARCH, along with a comprehensive suite of tests to validate error handling and syntax compliance. - **`SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs`**: New file added to generate script output for the VECTOR_SEARCH function. - **`SqlScriptDom/Parser/TSql/TSql170.g` & `SqlDom/Parser/TSql/Ast.xml`**: Extended grammar rules and AST definitions to support VECTOR_SEARCH. - **`SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs`**: Added new constants (e.g., COSINE, DOT, EUCLIDEAN, METRIC, TOP_N, VECTOR_SEARCH) required for vector search processing. - **`Test/SqlDom/ParserErrorsTests.cs` and related vector test scripts**: Introduced extensive tests covering syntax errors and parameter validations for VECTOR_SEARCH. Related work items: #4440435 * Merged PR 1757817: Added EM Permission support ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [ ] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers Added EM Permission support ---- #### AI description (iteration 1) #### PR Classification This PR implements a new feature by adding support for External Model permissions in ScriptDOM, enabling the parsing and generation of new permission-related T-SQL statements. #### PR Summary The pull request enhances ScriptDOM to correctly handle External Model permissions—covering GRANT, DENY, REVOKE, and ALTER AUTHORIZATION operations—and integrates comprehensive tests and token generation support to improve IntelliSense and syntax-highlighting as outlined in the linked work items. - **`Test/SqlDom/ExternalModelPermissionUnitTests.cs`**: Adds unit tests for External Model permission statements, including backward compatibility checks. - **`Test/SqlDom/Baselines170/SecurityStatementExternalModelTests170.sql` & `Test/SqlDom/TestScripts/SecurityStatementExternalModelTests170.sql`**: Introduce baseline and test scripts with various External Model permission scenarios. - **`SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs` & `SqlScriptDom/Parser/TSql/SecurityObjectKind.cs`**: Update parsing logic and the security object enumeration to recognize and handle External Model keywords. - **`SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SecurityTargetObject.cs`**: Enhances token generation to support the External Model permission syntax. Related work items: #4088625, #4088633 * Update .NET SDK to latest patch version (8.0.413) * Merged PR 1764425: Adding release notes for 170.82.0 # Pull Request Template for ScriptDom ## Description Please provide a detailed description, include the link to the design specification or SQL feature document for the new TSQL syntaxes. Make sure to add links to the Github or DevDiv issue Before submitting your pull request, please ensure you have completed the following: ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [ ] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers Adding release notes for 170.82.0 * remove extras * fixing the build --------- Co-authored-by: C Shanmukha Reddy Co-authored-by: Sicong Liu Co-authored-by: MerlinBot Co-authored-by: Shiv Prashant Sood Co-authored-by: Urvashi Raj Co-authored-by: Zi Chen --- SqlScriptDom/Parser/TSql/Ast.xml | 53 +- .../Parser/TSql/CodeGenerationSupporter.cs | 26 +- .../Parser/TSql/ExternalModelTypeOption.cs | 26 + .../Parser/TSql/SecurityObjectKind.cs | 1 + SqlScriptDom/Parser/TSql/TSql170.g | 903 ++++++++++++++---- .../Parser/TSql/TSql170ParserBaseInternal.cs | 24 + ...ptGenerator.AlterExternalModelStatement.cs | 121 +++ ...iptGenerator.DropExternalModelStatement.cs | 23 + ...tor.AIGenerateFixedChunksTableReference.cs | 31 + ...rVisitor.AiGenerateChunksTableReference.cs | 51 + ...torVisitor.AiGenerateEmbeddingsFunction.cs | 48 + ...torVisitor.CreateExternalModelStatement.cs | 122 +++ .../SqlScriptGeneratorVisitor.FunctionCall.cs | 26 + ...ptGeneratorVisitor.SecurityTargetObject.cs | 8 +- ...ratorVisitor.VectorSearchTableReference.cs | 56 ++ .../Baselines170/AiGenerateChunksTests170.sql | 101 ++ .../AiGenerateEmbeddingsTests170.sql | 52 + .../AlterExternalModelStatementTests170.sql | 27 + .../CreateExternalModelStatementTests170.sql | 33 + .../DropExternalModelStatementTests170.sql | 1 + .../Baselines170/JsonFunctionTests170.sql | 101 ++ Test/SqlDom/Baselines170/RegexpTests170.sql | 22 + ...SecurityStatementExternalModelTests170.sql | 71 ++ .../Baselines170/VectorFunctionTests170.sql | 23 + Test/SqlDom/Only170SyntaxTests.cs | 12 +- Test/SqlDom/ParserErrorsTests.cs | 454 ++++++++- .../TestScripts/AiGenerateChunksTests170.sql | 101 ++ .../AiGenerateEmbeddingsTests170.sql | 52 + .../AlterExternalModelStatementTests170.sql | 27 + .../CreateExternalModelStatementTests170.sql | 33 + .../DropExternalModelStatementTests170.sql | 1 + .../TestScripts/JsonFunctionTests170.sql | 98 ++ Test/SqlDom/TestScripts/RegexpTests170.sql | 26 + ...SecurityStatementExternalModelTests170.sql | 47 + .../TestScripts/VectorFunctionTests170.sql | 25 + global.json | 2 +- release-notes/170/170.82.0.md | 27 + 37 files changed, 2652 insertions(+), 203 deletions(-) create mode 100644 SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.DropExternalModelStatement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AIGenerateFixedChunksTableReference.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateChunksTableReference.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs create mode 100644 Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql create mode 100644 Test/SqlDom/Baselines170/AiGenerateEmbeddingsTests170.sql create mode 100644 Test/SqlDom/Baselines170/AlterExternalModelStatementTests170.sql create mode 100644 Test/SqlDom/Baselines170/CreateExternalModelStatementTests170.sql create mode 100644 Test/SqlDom/Baselines170/DropExternalModelStatementTests170.sql create mode 100644 Test/SqlDom/Baselines170/JsonFunctionTests170.sql create mode 100644 Test/SqlDom/Baselines170/RegexpTests170.sql create mode 100644 Test/SqlDom/Baselines170/SecurityStatementExternalModelTests170.sql create mode 100644 Test/SqlDom/Baselines170/VectorFunctionTests170.sql create mode 100644 Test/SqlDom/TestScripts/AiGenerateChunksTests170.sql create mode 100644 Test/SqlDom/TestScripts/AiGenerateEmbeddingsTests170.sql create mode 100644 Test/SqlDom/TestScripts/AlterExternalModelStatementTests170.sql create mode 100644 Test/SqlDom/TestScripts/CreateExternalModelStatementTests170.sql create mode 100644 Test/SqlDom/TestScripts/DropExternalModelStatementTests170.sql create mode 100644 Test/SqlDom/TestScripts/JsonFunctionTests170.sql create mode 100644 Test/SqlDom/TestScripts/RegexpTests170.sql create mode 100644 Test/SqlDom/TestScripts/SecurityStatementExternalModelTests170.sql create mode 100644 Test/SqlDom/TestScripts/VectorFunctionTests170.sql create mode 100644 release-notes/170/170.82.0.md diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index c8ebb38e..842a7871 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -403,8 +403,8 @@ Summary="Actual JSON for clause options. First one is always present (JSON mode)."/> - - + + @@ -642,6 +642,7 @@ + @@ -1346,6 +1347,27 @@ + + + + + + + + + + + + + + + + + + + + + @@ -3558,7 +3580,7 @@ - + @@ -4713,4 +4735,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 4deaa86e..1106636a 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -99,6 +99,8 @@ internal static class CodeGenerationSupporter internal const string Affinity = "AFFINITY"; internal const string After = "AFTER"; internal const string Aggregate = "AGGREGATE"; + internal const string AiGenerateChunks = "AI_GENERATE_CHUNKS"; + internal const string AIGenerateEmbeddings = "AI_GENERATE_EMBEDDINGS"; internal const string Algorithm = "ALGORITHM"; internal const string AlterColumn = "ALTERCOLUMN"; internal const string All = "ALL"; @@ -118,6 +120,7 @@ internal static class CodeGenerationSupporter internal const string Always = "ALWAYS"; internal const string Anonymous = "ANONYMOUS"; internal const string AnsiNullDefault = "ANSI_NULL_DEFAULT"; + internal const string ApiFormat = "API_FORMAT"; internal const string Application = "APPLICATION"; internal const string ApplicationLog = "APPLICATION_LOG"; internal const string Apply = "APPLY"; @@ -198,6 +201,8 @@ internal static class CodeGenerationSupporter internal const string CheckPolicy = "CHECK_POLICY"; internal const string Checksum = "CHECKSUM"; internal const string ChecksumAgg = "CHECKSUM_AGG"; + internal const string ChunkSize = "CHUNK_SIZE"; + internal const string ChunkType = "CHUNK_TYPE"; internal const string ModularSum = "MODULAR_SUM"; internal const string Classifier = "CLASSIFIER"; internal const string Classification = "CLASSIFICATION"; @@ -225,7 +230,6 @@ internal static class CodeGenerationSupporter internal const string CompressionDelay = "COMPRESSION_DELAY"; internal const string CompressAllRowGroups = "COMPRESS_ALL_ROW_GROUPS"; internal const string Concat = "CONCAT"; - internal const string Cosine = "COSINE"; internal const string Configuration = "CONFIGURATION"; internal const string ConnectionOptions = "CONNECTION_OPTIONS"; internal const string Contained = "CONTAINED"; @@ -244,6 +248,7 @@ internal static class CodeGenerationSupporter internal const string CopyCommand = "COPY"; internal const string CopyOnly = "COPY_ONLY"; internal const string Correlated = "CORRELATED"; + internal const string Cosine = "COSINE"; internal const string Count = "COUNT"; internal const string CountBig = "COUNT_BIG"; internal const string Counter = "COUNTER"; @@ -301,7 +306,6 @@ internal static class CodeGenerationSupporter internal const string Description = "DESCRIPTION"; internal const string DesiredState = "DESIRED_STATE"; internal const string DiskANN = "DISKANN"; - internal const string Dot = "DOT"; internal const string Delay = "DELAY"; internal const string DelayedDurability = "DELAYED_DURABILITY"; internal const string DelimitedText = "DELIMITEDTEXT"; @@ -320,6 +324,7 @@ internal static class CodeGenerationSupporter internal const string Document = "DOCUMENT"; internal const string DollarSign = "$"; internal const string DollarPartition = "$PARTITION"; + internal const string Dot = "DOT"; internal const string Drop = "DROP"; internal const string DropExisting = "DROP_EXISTING"; internal const string DTSBuffers = "DTS_BUFFERS"; @@ -329,11 +334,13 @@ internal static class CodeGenerationSupporter internal const string Edition = "EDITION"; internal const string ElasticPool = "ELASTIC_POOL"; internal const string Elements = "ELEMENTS"; + internal const string Embeddings = "EMBEDDINGS"; internal const string Emergency = "EMERGENCY"; internal const string Empty = "EMPTY"; internal const string Enable = "ENABLE"; internal const string Enabled = "ENABLED"; internal const string EnableBroker = "ENABLE_BROKER"; + internal const string EnableChunkSetId = "ENABLE_CHUNK_SET_ID"; internal const string EnclaveComputations = "ENCLAVE_COMPUTATIONS"; internal const string Encoding = "ENCODING"; internal const string Encrypted = "ENCRYPTED"; @@ -350,13 +357,13 @@ internal static class CodeGenerationSupporter internal const string EnvironmentVariables = "ENVIRONMENT_VARIABLES"; internal const string Equal = "="; internal const string Error = "ERROR"; - internal const string Euclidean = "EUCLIDEAN"; internal const string ErrorBrokerConversations = "ERROR_BROKER_CONVERSATIONS"; internal const string ErrorDataSource = "ERRORFILE_DATA_SOURCE"; internal const string ErrorFile = "ERRORFILE"; internal const string ErrorFileCredential = "ERRORFILE_CREDENTIAL"; internal const string EscapeChar = "ESCAPECHAR"; internal const string EstimateOnly = "ESTIMATEONLY"; + internal const string Euclidean = "EUCLIDEAN"; internal const string Event = "EVENT"; internal const string EventRetentionMode = "EVENT_RETENTION_MODE"; internal const string Exclamation = "!"; @@ -415,6 +422,7 @@ internal static class CodeGenerationSupporter internal const string FieldQuote = "FIELDQUOTE"; internal const string FipsFlagger = "FIPS_FLAGGER"; internal const string First = "FIRST"; + internal const string Fixed = "FIXED"; internal const string FlushIntervalSeconds = "FLUSH_INTERVAL_SECONDS"; internal const string FlushIntervalSecondsAlt = "DATA_FLUSH_INTERVAL_SECONDS"; internal const string Fn = "FN"; @@ -514,6 +522,7 @@ internal static class CodeGenerationSupporter internal const string Json = "JSON"; internal const string JsonArray = "JSON_ARRAY"; internal const string JsonObject = "JSON_OBJECT"; + internal const string JsonObjectAgg = "JSON_OBJECTAGG"; internal const string Keep = "KEEP"; internal const string KeepDefaults = "KEEPDEFAULTS"; internal const string KeepFixed = "KEEPFIXED"; @@ -555,6 +564,7 @@ internal static class CodeGenerationSupporter internal const string LoadHistory = "LOADHISTORY"; internal const string LobCompaction = "LOB_COMPACTION"; internal const string Local = "LOCAL"; + internal const string LocalRuntimePath = "LOCAL_RUNTIME_PATH"; internal const string Location = "LOCATION"; internal const string LocationUserDB = "USER_DB"; internal const string LocalServiceName = "LOCAL_SERVICE_NAME"; @@ -615,8 +625,8 @@ internal static class CodeGenerationSupporter internal const string Message = "MESSAGE"; internal const string MessageForwarding = "MESSAGE_FORWARDING"; internal const string MessageForwardSize = "MESSAGE_FORWARD_SIZE"; - internal const string MigrationState = "MIGRATION_STATE"; internal const string Metric = "METRIC"; + internal const string MigrationState = "MIGRATION_STATE"; internal const string Min = "MIN"; internal const string MinGrantPercent = "MIN_GRANT_PERCENT"; internal const string MinCpuPercent = "MIN_CPU_PERCENT"; @@ -628,6 +638,8 @@ internal static class CodeGenerationSupporter internal const string Mirror = "MIRROR"; internal const string Mixed = "MIXED"; internal const string MixedPageAllocation = "MIXED_PAGE_ALLOCATION"; + internal const string ModelType = "MODEL_TYPE"; + internal const string ModelName = "MODEL"; internal const string Modify = "MODIFY"; internal const string Money = "MONEY"; internal const string Move = "MOVE"; @@ -761,6 +773,7 @@ internal static class CodeGenerationSupporter internal const string Model = "MODEL"; internal const string RunTime = "RUNTIME"; internal const string Onnx = "ONNX"; + internal const string Overlap = "OVERLAP"; internal const string Process = "PROCESS"; internal const string PropertySetGuid = "PROPERTY_SET_GUID"; @@ -842,6 +855,7 @@ internal static class CodeGenerationSupporter internal const string RetentionDays = "RETENTION_DAYS"; internal const string RetentionPeriod = "RETENTION_PERIOD"; internal const string Returns = "RETURNS"; + internal const string Returning = "RETURNING"; internal const string RequestMaxCpuTimeSec = "REQUEST_MAX_CPU_TIME_SEC"; internal const string RequestMaxMemoryGrantPercent = "REQUEST_MAX_MEMORY_GRANT_PERCENT"; internal const string RequestMemoryGrantTimeoutSec = "REQUEST_MEMORY_GRANT_TIMEOUT_SEC"; @@ -916,6 +930,7 @@ internal static class CodeGenerationSupporter internal const string ShrinkDb = "SHRINKDB"; internal const string Sid = "SID"; internal const string Signature = "SIGNATURE"; + internal const string SimilarTo = "SIMILAR_TO"; internal const string Simple = "SIMPLE"; internal const string SingleBlob = "SINGLE_BLOB"; internal const string SingleClob = "SINGLE_CLOB"; @@ -1025,6 +1040,7 @@ internal static class CodeGenerationSupporter internal const string Timer = "TIMER"; internal const string TimeStamp = "TIMESTAMP"; internal const string TinyInt = "TINYINT"; + internal const string TopN = "TOP_N"; internal const string TornPageDetection = "TORN_PAGE_DETECTION"; internal const string TrackCausality = "TRACK_CAUSALITY"; internal const string TrackColumnsUpdated = "TRACK_COLUMNS_UPDATED"; @@ -1059,6 +1075,7 @@ internal static class CodeGenerationSupporter internal const string Unpivot = "UNPIVOT"; internal const string UpdLock = "UPDLOCK"; internal const string Url = "URL"; + internal const string Use = "USE"; internal const string Used = "USED"; internal const string UseIdentity = "USE_IDENTITY"; internal const string UseTypeDefault = "USE_TYPE_DEFAULT"; @@ -1076,6 +1093,7 @@ internal static class CodeGenerationSupporter internal const string Varp = "VARP"; internal const string VDevNo = "VDEVNO"; internal const string Vector = "Vector"; + internal const string VectorSearch = "VECTOR_SEARCH"; internal const string Verbose = "VERBOSE"; internal const string VerboseLogging = "VerboseLogging"; internal const string VerifyOnly = "VERIFYONLY"; diff --git a/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs b/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs new file mode 100644 index 00000000..858784e5 --- /dev/null +++ b/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ +#pragma warning disable 1591 + + /// + /// The enumeration specifies the external model type + /// Currently, we support EMBEDDINGS only. + /// + public enum ExternalModelTypeOption + { + /// + /// MODEL_TYPE = EMBEDDINGS + /// + EMBEDDINGS = 0, + + } + +#pragma warning restore 1591 +} diff --git a/SqlScriptDom/Parser/TSql/SecurityObjectKind.cs b/SqlScriptDom/Parser/TSql/SecurityObjectKind.cs index 8d72de8b..4d1cf170 100644 --- a/SqlScriptDom/Parser/TSql/SecurityObjectKind.cs +++ b/SqlScriptDom/Parser/TSql/SecurityObjectKind.cs @@ -42,6 +42,7 @@ public enum SecurityObjectKind SearchPropertyList = 23, ServerRole = 24, AvailabilityGroup = 25, + ExternalModel = 26, } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 1ef43398..a8f9bf26 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -906,7 +906,7 @@ create2005Statements returns [TSqlStatement vResult = null] vResult=createEventStatement // NOTIFICATION or SESSION | {NextTokenMatches(CodeGenerationSupporter.External)}? - vResult=createExternalStatements // EXTERNAL DATA SOURCE, FILE FORMAT, STREAM, TABLE, RESOURCE POOL, LIBRARY, LANGUAGE + vResult=createExternalStatements // EXTERNAL DATA SOURCE, FILE FORMAT, STREAM, TABLE, RESOURCE POOL, LIBRARY, LANGUAGE, MODEL | {NextTokenMatches(CodeGenerationSupporter.Fulltext)}? vResult=createFulltextStatement // Index or CATALOG @@ -4299,8 +4299,8 @@ alterDatabaseEncryptionKey [IToken tAlter] returns [AlterDatabaseEncryptionKeySt addSensitivityClassificationStatement returns [AddSensitivityClassificationStatement vResult = this.FragmentFactory.CreateFragment()] { ColumnReferenceExpression vColumn; - SensitivityClassificationOption vOption; - long encounteredOptions = 0; + SensitivityClassificationOption vOption; + long encounteredOptions = 0; } : tSensitivity:Identifier tClassification:Identifier To { @@ -4309,24 +4309,24 @@ addSensitivityClassificationStatement returns [AddSensitivityClassificationState } (vColumn = column { - CheckTableNameExistsForColumn(vColumn, true); + CheckTableNameExistsForColumn(vColumn, true); AddAndUpdateTokenInfo(vResult, vResult.Columns, vColumn); } (Comma vColumn = column { - CheckTableNameExistsForColumn(vColumn, true); + CheckTableNameExistsForColumn(vColumn, true); AddAndUpdateTokenInfo(vResult, vResult.Columns, vColumn); } )* ) - With LeftParenthesis vOption = sensitivityClassificationOption + With LeftParenthesis vOption = sensitivityClassificationOption { - CheckOptionDuplication(ref encounteredOptions, (int)vOption.Type, vOption); + CheckOptionDuplication(ref encounteredOptions, (int)vOption.Type, vOption); AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); } (Comma vOption = sensitivityClassificationOption { - CheckOptionDuplication(ref encounteredOptions, (int)vOption.Type, vOption); + CheckOptionDuplication(ref encounteredOptions, (int)vOption.Type, vOption); AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); } )* @@ -4357,10 +4357,10 @@ sensitivityClassificationOption returns [SensitivityClassificationOption vResult break; } - vResult = FragmentFactory.CreateFragment(); + vResult = FragmentFactory.CreateFragment(); vResult.Value = vSensitivityValue; - vResult.Type = optionType; + vResult.Type = optionType; UpdateTokenInfo(vResult, tOption); } @@ -4409,17 +4409,17 @@ dropSensitivityClassificationStatement returns [DropSensitivityClassificationSta } (vColumn = column { - CheckTableNameExistsForColumn(vColumn, true); + CheckTableNameExistsForColumn(vColumn, true); AddAndUpdateTokenInfo(vResult, vResult.Columns, vColumn); } (Comma vColumn = column { - CheckTableNameExistsForColumn(vColumn, true); + CheckTableNameExistsForColumn(vColumn, true); AddAndUpdateTokenInfo(vResult, vResult.Columns, vColumn); } )* ) - ; + ; ////////////////////////////////////////////////////////////////////// // Create Database @@ -6266,7 +6266,7 @@ simpleBulkInsertOptionWithValue returns [LiteralBulkInsertOption vResult = Fragm | iValue = identifier { vResult.OptionKind = BulkInsertStringOptionsHelper.Instance.ParseOption(tOption, SqlVersionFlags.TSql150); - UpdateTokenInfo(vResult, tOption); + UpdateTokenInfo(vResult, tOption); if (vResult.OptionKind == BulkInsertOptionKind.HeaderRow) if(!TryMatch(iValue, CodeGenerationSupporter.True)) Match(iValue, CodeGenerationSupporter.False); @@ -8947,6 +8947,9 @@ createExternalStatements returns [TSqlStatement vResult = null] | {NextTokenMatches(CodeGenerationSupporter.Stream)}? vResult = createExternalStreamStatement + | + {NextTokenMatches(CodeGenerationSupporter.Model)}? + vResult = createExternalModelStatement ) ; @@ -8964,6 +8967,9 @@ alterExternalStatements returns [TSqlStatement vResult = null] | {NextTokenMatches(CodeGenerationSupporter.Language)}? vResult = alterExternalLanguageStatement + | + {NextTokenMatches(CodeGenerationSupporter.Model)}? + vResult = alterExternalModelStatement ) ; @@ -13945,7 +13951,7 @@ securityTargetObjectCommon[SecurityTargetObject vParent] ( vIdentifier2=securityStatementPermission { - vParent.ObjectKind = ParseSecurityObjectKind(vIdentifier1, vIdentifier2); + vParent.ObjectKind = ParseSecurityObjectKindTSql170(vIdentifier1, vIdentifier2); } | vIdentifier2=securityStatementPermission vIdentifier3=securityStatementPermission @@ -14768,9 +14774,9 @@ dropStatements returns [TSqlStatement vResult] | {NextTokenMatches(CodeGenerationSupporter.Column)}? vResult = dropColumnStatements | {NextTokenMatches(CodeGenerationSupporter.External)}? - vResult = dropExternalStatement // EXTERNAL DATA SOURCE, FILE FORMAT, TABLE or RESOURCE POOL - | {NextTokenMatches(CodeGenerationSupporter.Sensitivity)}? - vResult = dropSensitivityClassificationStatement + vResult = dropExternalStatement // EXTERNAL DATA SOURCE, FILE FORMAT, TABLE , MODEL or RESOURCE POOL + | {NextTokenMatches(CodeGenerationSupporter.Sensitivity)}? + vResult = dropSensitivityClassificationStatement | vResult = dropServerStatements | vResult = dropUserStatement ) @@ -15662,6 +15668,9 @@ dropExternalStatement returns [TSqlStatement vResult = null] | {NextTokenMatches(CodeGenerationSupporter.Resource)}? vResult = dropExternalResourcePoolStatement + | + {NextTokenMatches(CodeGenerationSupporter.Model)}? + vResult = dropExternalModelStatement ) ; @@ -16952,13 +16961,13 @@ createColumnStoreIndexStatement [IToken tUnique, bool? isClustered] returns [Cre ( identifierColumnList[vResult, vResult.OrderedColumns] { - foreach (var col in vResult.OrderedColumns) - { - if (PseudoColumnHelper.IsGraphPseudoColumn(col)) - { + foreach (var col in vResult.OrderedColumns) + { + if (PseudoColumnHelper.IsGraphPseudoColumn(col)) + { ThrowIncorrectSyntaxErrorException(col); } - } + } } ) )? @@ -17184,9 +17193,9 @@ filterExpressionPrimary returns [BooleanExpression vResult] vExpression = filterColumn ( Is - ( - vResult = filterNullPredicate[vExpression] - | + ( + vResult = filterNullPredicate[vExpression] + | ( Not { @@ -17199,7 +17208,7 @@ filterExpressionPrimary returns [BooleanExpression vResult] | vResult = filterDistinctPredicate[vExpression, vNotDefined] ) - ) + ) | vResult = filterComparisonPredicate[vExpression] | vResult = filterInPredicate[vExpression] ) @@ -17252,9 +17261,9 @@ filterDistinctPredicate[ScalarExpression vColumn, bool vNotDefined] returns [Dis ScalarExpression vExpression; } : - vExpression = expression + vExpression = expression { - vResult.FirstExpression = vColumn; + vResult.FirstExpression = vColumn; vResult.SecondExpression = vExpression; vResult.IsNot = vNotDefined; } @@ -17262,9 +17271,9 @@ filterDistinctPredicate[ScalarExpression vColumn, bool vNotDefined] returns [Dis filterNullPredicateFromDistinctPredicate[ScalarExpression vColumn, bool vNotDefined] returns [BooleanIsNullExpression vResult = this.FragmentFactory.CreateFragment()] : - tNull:Null + tNull:Null { - vResult.IsNot = vNotDefined; + vResult.IsNot = vNotDefined; vResult.Expression = vColumn; UpdateTokenInfo(vResult,tNull); } @@ -19122,6 +19131,8 @@ selectTableReferenceElementWithoutJoinParenthesis[SubDmlFlags subDmlFlags] retur : {NextTokenMatches(CodeGenerationSupporter.ChangeTable)}? vResult=changeTableTableReference + | {NextTokenMatches(CodeGenerationSupporter.AiGenerateChunks)}? + vResult = aiGenerateChunksTableReference | vResult=builtInFunctionTableReference | {NextIdentifierMatchesOneOf(new string[] {CodeGenerationSupporter.StringSplit, CodeGenerationSupporter.GenerateSeries, CodeGenerationSupporter.RegexpMatches, CodeGenerationSupporter.RegexpSplitToTable})}? vResult=globalFunctionTableReference @@ -19137,124 +19148,259 @@ selectTableReferenceElementWithoutJoinParenthesis[SubDmlFlags subDmlFlags] retur | vResult=subDmlTableReference[subDmlFlags] | {NextTokenMatches(CodeGenerationSupporter.Predict)}? vResult=predictTableReference[subDmlFlags] + | {NextTokenMatches(CodeGenerationSupporter.VectorSearch)}? + vResult=vectorSearchTableReference | vResult=schemaObjectOrFunctionTableReference ; +aiGenerateChunksTableReference returns [AIGenerateChunksTableReference vResult = null] +{ + ScalarExpression vSource; + Identifier vChunkType; +} + : + {NextTokenMatches(CodeGenerationSupporter.AiGenerateChunks)}? + tFunc:Identifier + { + Match(tFunc, CodeGenerationSupporter.AiGenerateChunks); + } + LeftParenthesis + tSourceToken:Identifier + { + Match(tSourceToken, CodeGenerationSupporter.Source); + } + EqualsSign + vSource = expression + Comma + tChunkTypeToken:Identifier + { + Match(tChunkTypeToken, CodeGenerationSupporter.ChunkType); + } + EqualsSign + vChunkType = identifier + Comma + vResult = aiGenerateFixedChunksTableReference[vSource, vChunkType] + tRParen:RightParenthesis + { + if (vResult != null) + { + UpdateTokenInfo(vResult, tFunc); + UpdateTokenInfo(vResult, tRParen); + } + } + simpleTableReferenceAliasOpt[vResult] + ; + +aiGenerateFixedChunksTableReference [ScalarExpression vSource, Identifier vChunkType] + returns [AIGenerateFixedChunksTableReference vResult = FragmentFactory.CreateFragment()] +{ + Identifier vChunkSizeParam; + Identifier vOverlapParam = null; + Identifier vEnableChunkSetIdParam = null; + + ScalarExpression vChunkSize = null; + ScalarExpression vOverlap = null; + ScalarExpression vEnableChunkSetId = null; +} + : + { + Match(vChunkType, CodeGenerationSupporter.Fixed); + vResult.Source = vSource; + vResult.ChunkType = vChunkType; + } + vChunkSizeParam = identifier + { + Match(vChunkSizeParam, CodeGenerationSupporter.ChunkSize); + } + EqualsSign + vChunkSize = expression + { + vResult.ChunkSize = vChunkSize; + } + + ( + Comma + vOverlapParam = identifier + { + Match(vOverlapParam, CodeGenerationSupporter.Overlap); + } + EqualsSign + vOverlap = expression + { + vResult.Overlap = vOverlap; + } + )? + + ( + Comma + vEnableChunkSetIdParam = identifier + { + Match(vEnableChunkSetIdParam, CodeGenerationSupporter.EnableChunkSetId); + } + EqualsSign + vEnableChunkSetId = expression + { + vResult.EnableChunkSetId = vEnableChunkSetId; + } + )? + ; + +vectorSearchTableReference returns [VectorSearchTableReference vResult = FragmentFactory.CreateFragment()] +{ + TableReferenceWithAlias vTable; + ColumnReferenceExpression vColumn; + ScalarExpression vSimilarTo; + StringLiteral vMetric; + IntegerLiteral vTopN; +} + : + tVectorSearch:Identifier LeftParenthesis + { + Match(tVectorSearch, CodeGenerationSupporter.VectorSearch); + UpdateTokenInfo(vResult, tVectorSearch); + } + Table EqualsSign vTable = mergeTarget[false] + { + vResult.Table = vTable; + } + Comma Column EqualsSign vColumn = fixedColumn + { + vResult.Column = vColumn; + } + Comma tSimilarTo:Identifier EqualsSign vSimilarTo = expression + { + Match(tSimilarTo, CodeGenerationSupporter.SimilarTo); + vResult.SimilarTo = vSimilarTo; + } + Comma tMetric:Identifier EqualsSign vMetric = stringLiteral + { + Match(tMetric, CodeGenerationSupporter.Metric); + MatchString(vMetric, CodeGenerationSupporter.Cosine, CodeGenerationSupporter.Dot, CodeGenerationSupporter.Euclidean); + vResult.Metric = vMetric; + } + Comma tTopN:Identifier EqualsSign vTopN = integer + { + Match(tTopN, CodeGenerationSupporter.TopN); + vResult.TopN = vTopN; + } + RightParenthesis simpleTableReferenceAliasOpt[vResult] + ; + predictTableReference[SubDmlFlags subDmlFlags] returns [PredictTableReference vResult] - : - {NextTokenMatches(CodeGenerationSupporter.Predict)}? - tPredict:Identifier LeftParenthesis vResult = predictParams[subDmlFlags, ExpressionFlags.None] tRParen:RightParenthesis predictWithClauseOpt[vResult] simpleTableReferenceAliasOpt[vResult] - { - Match(tPredict, CodeGenerationSupporter.Predict); - UpdateTokenInfo(vResult, tPredict); - UpdateTokenInfo(vResult, tRParen); - } - ; + : + {NextTokenMatches(CodeGenerationSupporter.Predict)}? + tPredict:Identifier LeftParenthesis vResult = predictParams[subDmlFlags, ExpressionFlags.None] tRParen:RightParenthesis predictWithClauseOpt[vResult] simpleTableReferenceAliasOpt[vResult] + { + Match(tPredict, CodeGenerationSupporter.Predict); + UpdateTokenInfo(vResult, tPredict); + UpdateTokenInfo(vResult, tRParen); + } + ; predictParams[SubDmlFlags subDmlFlags, ExpressionFlags expressionFlags] returns [PredictTableReference vResult = FragmentFactory.CreateFragment()] { - ScalarExpression vModelVariable; - ScalarSubquery vModelSubquery; - TableReferenceWithAlias vDataSource; - Identifier vRuntime; -} - : - ( - tModelVariable:Identifier EqualsSign vModelVariable = expression - { - Match(tModelVariable, CodeGenerationSupporter.Model); - vResult.ModelVariable = vModelVariable; - UpdateTokenInfo(vResult, tModelVariable); - } - | tModelSubquery:Identifier EqualsSign vModelSubquery = subquery[SubDmlFlags.SelectNotForInsert, expressionFlags] - { - vResult.ModelSubquery = vModelSubquery; - } - ) - Comma tData:Identifier EqualsSign vDataSource = mergeTarget[false] - { - vResult.DataSource = vDataSource; - } - ( - Comma tRunTime:Identifier EqualsSign vRuntime = identifier - { - vResult.RunTime = vRuntime; - } - )? - ; + ScalarExpression vModelVariable; + ScalarSubquery vModelSubquery; + TableReferenceWithAlias vDataSource; + Identifier vRuntime; +} + : + ( + tModelVariable:Identifier EqualsSign vModelVariable = expression + { + Match(tModelVariable, CodeGenerationSupporter.Model); + vResult.ModelVariable = vModelVariable; + UpdateTokenInfo(vResult, tModelVariable); + } + | tModelSubquery:Identifier EqualsSign vModelSubquery = subquery[SubDmlFlags.SelectNotForInsert, expressionFlags] + { + vResult.ModelSubquery = vModelSubquery; + } + ) + Comma tData:Identifier EqualsSign vDataSource = mergeTarget[false] + { + vResult.DataSource = vDataSource; + } + ( + Comma tRunTime:Identifier EqualsSign vRuntime = identifier + { + vResult.RunTime = vRuntime; + } + )? + ; predictWithClauseOpt [PredictTableReference vParent] - : (With) => - ( - (With LeftParenthesis predictSchemaItemList[vParent] tRParen:RightParenthesis - { - UpdateTokenInfo(vParent,tRParen); - } - ) - ) - ; + : (With) => + ( + (With LeftParenthesis predictSchemaItemList[vParent] tRParen:RightParenthesis + { + UpdateTokenInfo(vParent,tRParen); + } + ) + ) + ; predictSchemaItemList [PredictTableReference vParent] { - SchemaDeclarationItem vItem; + SchemaDeclarationItem vItem; } - : vItem = predictSchemaItem - { - AddAndUpdateTokenInfo(vParent, vParent.SchemaDeclarationItems, vItem); - } - (Comma vItem = predictSchemaItem - { - AddAndUpdateTokenInfo(vParent, vParent.SchemaDeclarationItems, vItem); - } - )* - ; + : vItem = predictSchemaItem + { + AddAndUpdateTokenInfo(vParent, vParent.SchemaDeclarationItems, vItem); + } + (Comma vItem = predictSchemaItem + { + AddAndUpdateTokenInfo(vParent, vParent.SchemaDeclarationItems, vItem); + } + )* + ; predictSchemaItem returns [SchemaDeclarationItem vResult = FragmentFactory.CreateFragment()] { - ValueExpression vMapping; - ColumnDefinitionBase vColumn; -} - : vColumn = columnDefinitionBasic - { - vResult.ColumnDefinition = vColumn; - } - (vMapping = stringLiteral - { - vResult.Mapping = vMapping; - } - )? - (As tPredict:Identifier - { - Match(tPredict, CodeGenerationSupporter.Predict); - } - )? - ; + ValueExpression vMapping; + ColumnDefinitionBase vColumn; +} + : vColumn = columnDefinitionBasic + { + vResult.ColumnDefinition = vColumn; + } + (vMapping = stringLiteral + { + vResult.Mapping = vMapping; + } + )? + (As tPredict:Identifier + { + Match(tPredict, CodeGenerationSupporter.Predict); + } + )? + ; mergeTarget[bool indexHintAllowed] returns [TableReferenceWithAlias vResult] { - Identifier vAlias; -} - : - vResult=dmlTarget[indexHintAllowed] - ( - ( - As vAlias = identifier - { - vResult.Alias = vAlias; - } - ) - | - {!NextTokenMatches(CodeGenerationSupporter.Using)}? - ( - vAlias = identifier - { - vResult.Alias = vAlias; - } - ) - | - /* empty */ - ) - ; + Identifier vAlias; +} + : + vResult=dmlTarget[indexHintAllowed] + ( + ( + As vAlias = identifier + { + vResult.Alias = vAlias; + } + ) + | + {!NextTokenMatches(CodeGenerationSupporter.Using)}? + ( + vAlias = identifier + { + vResult.Alias = vAlias; + } + ) + | + /* empty */ + ) + ; changeTableTableReference returns [TableReferenceWithAliasAndColumns vResult] { @@ -20158,20 +20304,20 @@ insertColumn returns [ColumnReferenceExpression vResult = FragmentFactory.Create openRowsetColumn returns [OpenRowsetColumnDefinition vResult = FragmentFactory.CreateFragment()] { ColumnDefinitionBase vColumn; - IntegerLiteral vColumnOrdinal; - StringLiteral vStringLiteral; + IntegerLiteral vColumnOrdinal; + StringLiteral vStringLiteral; } : vColumn = columnDefinitionBasic - { - vResult.ColumnIdentifier = vColumn.ColumnIdentifier; - vResult.DataType = vColumn.DataType; - vResult.Collation = vColumn.Collation; - } - (vColumnOrdinal=integer + { + vResult.ColumnIdentifier = vColumn.ColumnIdentifier; + vResult.DataType = vColumn.DataType; + vResult.Collation = vColumn.Collation; + } + (vColumnOrdinal=integer { vResult.ColumnOrdinal = vColumnOrdinal; } - | vStringLiteral=stringLiteral + | vStringLiteral=stringLiteral { vResult.JsonPath = vStringLiteral; })? @@ -20264,13 +20410,23 @@ schemaObjectTableDmlTarget [bool indexHintAllowed] returns [NamedTableReference )? ; -schemaObjectOrFunctionTableReference returns [TableReference vResult] +schemaObjectOrFunctionTableReference returns [TableReference vResult = null] { SchemaObjectName vSchemaObjectName; } : vSchemaObjectName=schemaObjectFourPartName ( + { + vSchemaObjectName.BaseIdentifier != null && + vSchemaObjectName.BaseIdentifier.Value.Equals(CodeGenerationSupporter.AiGenerateChunks, StringComparison.OrdinalIgnoreCase) && + vSchemaObjectName.BaseIdentifier.QuoteType == QuoteType.NotQuoted && + LT(2).getText().Equals(CodeGenerationSupporter.Source, StringComparison.OrdinalIgnoreCase) + }? + { + vResult = aiGenerateChunksTableReference(); + } + | {IsTableReference(false)}? vResult=schemaObjectTableReference[vSchemaObjectName] | vResult=schemaObjectFunctionTableReference[vSchemaObjectName] @@ -20806,7 +20962,7 @@ openRowsetCosmos returns [OpenRowsetCosmos vResult = FragmentFactory.CreateFragm { long encountered = 0; OpenRowsetCosmosOption vOption; - OpenRowsetColumnDefinition vColumn; + OpenRowsetColumnDefinition vColumn; } : vOption = openRowsetCosmosOptionHint @@ -20867,7 +21023,7 @@ openRowsetBulk returns [BulkOpenRowset vResult = FragmentFactory.CreateFragment< BulkInsertOption vOption; StringLiteral vDataFile; - OpenRowsetColumnDefinition vColumn; + OpenRowsetColumnDefinition vColumn; } : Bulk (( @@ -20902,10 +21058,10 @@ openRowsetBulk returns [BulkOpenRowset vResult = FragmentFactory.CreateFragment< tRParen:RightParenthesis { CheckForDataFileFormatProhibitedOptionsInOpenRowsetBulk(encountered, vDataFile); - CheckForParquetFormatProhibitedOptionsInOpenRowsetBulk(encountered, vResult); + CheckForParquetFormatProhibitedOptionsInOpenRowsetBulk(encountered, vResult); UpdateTokenInfo(vResult,tRParen); } - (tWith:With + (tWith:With { UpdateTokenInfo(vResult,tWith); } @@ -21541,23 +21697,23 @@ simpleGroupByItem [ref bool alreadyEncounteredDistributedAggHint] returns [Expre { vResult.Expression = vExpression; } - ( - // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces - options { greedy = true; } : - With LeftParenthesis tDistributedAgg:Identifier tRParen:RightParenthesis - { - Match(tDistributedAgg, CodeGenerationSupporter.DistributedAgg); + ( + // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options { greedy = true; } : + With LeftParenthesis tDistributedAgg:Identifier tRParen:RightParenthesis + { + Match(tDistributedAgg, CodeGenerationSupporter.DistributedAgg); - if (alreadyEncounteredDistributedAggHint) - ThrowParseErrorException("SQL46129", tDistributedAgg, TSqlParserResource.SQL46129Message); + if (alreadyEncounteredDistributedAggHint) + ThrowParseErrorException("SQL46129", tDistributedAgg, TSqlParserResource.SQL46129Message); - vResult.DistributedAggregation = true; - UpdateTokenInfo(vResult, tDistributedAgg); - UpdateTokenInfo(vResult, tRParen); + vResult.DistributedAggregation = true; + UpdateTokenInfo(vResult, tDistributedAgg); + UpdateTokenInfo(vResult, tRParen); - alreadyEncounteredDistributedAggHint = true; - } - )? + alreadyEncounteredDistributedAggHint = true; + } + )? ; // End of Group By clause @@ -23281,9 +23437,9 @@ createColumnMasterKeyStatement returns [CreateColumnMasterKeyStatement vResult = columnMasterkeyParameter returns [ColumnMasterKeyParameter vResult] : {NextTokenMatches(CodeGenerationSupporter.KeyStoreProviderName)}? vResult = columnMasterKeyStoreProviderNameParameter - | {NextTokenMatches(CodeGenerationSupporter.KeyPath)}? + | {NextTokenMatches(CodeGenerationSupporter.KeyPath)}? vResult = columnMasterKeyPathParameter - | {NextTokenMatches(CodeGenerationSupporter.EnclaveComputations)}? + | {NextTokenMatches(CodeGenerationSupporter.EnclaveComputations)}? vResult = columnMasterKeyEnclaveComputationsParameter ; @@ -23311,14 +23467,14 @@ columnMasterKeyPathParameter returns [ColumnMasterKeyPathParameter vResult = Fra } ; - columnMasterKeyEnclaveComputationsParameter returns [ColumnMasterKeyEnclaveComputationsParameter vResult = FragmentFactory.CreateFragment()] + columnMasterKeyEnclaveComputationsParameter returns [ColumnMasterKeyEnclaveComputationsParameter vResult = FragmentFactory.CreateFragment()] { BinaryLiteral vSignature; } : tEnclaveComputations:Identifier tLeftParens:LeftParenthesis tSignature:Identifier tEquals3:EqualsSign vSignature=binary tRightParens:RightParenthesis { Match(tEnclaveComputations, CodeGenerationSupporter.EnclaveComputations); - Match(tSignature, CodeGenerationSupporter.Signature); + Match(tSignature, CodeGenerationSupporter.Signature); vResult.ParameterKind = ColumnMasterKeyParameterKind.Signature; vResult.Signature = vSignature; } @@ -23763,6 +23919,247 @@ dropSecurityPolicyStatement returns [DropSecurityPolicyStatement vResult = Fragm } ; +createExternalModelStatement returns [CreateExternalModelStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vName; + long encounteredOptions = 0; +} + : tModel:Identifier vName = identifier + { + Match(tModel, CodeGenerationSupporter.Model); + vResult.Name = vName; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + tWith:With LeftParenthesis + ( + {NextTokenMatches(CodeGenerationSupporter.Location)}? + externalModelLocation[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ApiFormat)}? + externalModelApiFormat[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelType)}? + externalModelModelType[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelName)}? + externalModelModelName[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Credential)}? + externalModelCredential[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.LocalRuntimePath)}? + externalModelLocalRuntimePath[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Parameters)}? + externalModelParameters[vResult] + ) + + ( + tComma:Comma + ( + {NextTokenMatches(CodeGenerationSupporter.Location)}? + externalModelLocation[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ApiFormat)}? + externalModelApiFormat[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelType)}? + externalModelModelType[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelName)}? + externalModelModelName[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Credential)}? + externalModelCredential[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.LocalRuntimePath)}? + externalModelLocalRuntimePath[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Parameters)}? + externalModelParameters[vResult] + ) + )* + + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult,tRParen); + } + ; + +externalModelLocation[ExternalModelStatement vParent] +{ + StringLiteral vLocation; +} + : + tLocation:Identifier EqualsSign vLocation = stringLiteral + { + Match(tLocation, CodeGenerationSupporter.Location); + vParent.Location = vLocation; + } + ; + +externalModelApiFormat[ExternalModelStatement vParent] +{ +StringLiteral vApiFormat; +} +: + tApiFormat:Identifier EqualsSign vApiFormat = stringLiteral + { + Match(tApiFormat, CodeGenerationSupporter.ApiFormat); + vParent.ApiFormat = vApiFormat; + } +; + +externalModelModelType[ExternalModelStatement vParent] + : + tModelType:Identifier + { + Match(tModelType, CodeGenerationSupporter.ModelType); + UpdateTokenInfo(vParent, tModelType); + } + EqualsSign + ( + tEmbeddings:Identifier + { + if (TryMatch(tEmbeddings, CodeGenerationSupporter.Embeddings)) + { + vParent.ModelType = ExternalModelTypeOption.EMBEDDINGS; + UpdateTokenInfo(vParent, tEmbeddings); + } + else + { + ThrowIncorrectSyntaxErrorException(tEmbeddings); + } + } + ) + ; + +externalModelModelName[ExternalModelStatement vParent] +{ + StringLiteral vModelName; +} + : + tModelName:Identifier EqualsSign vModelName = stringLiteral + { + Match(tModelName, CodeGenerationSupporter.ModelName); + vParent.ModelName = vModelName; + } + ; + +externalModelCredential[ExternalModelStatement vParent] +{ +Identifier vCredential; +} +: + tCredential:Identifier EqualsSign vCredential = identifier + { + Match(tCredential, CodeGenerationSupporter.Credential); + vParent.Credential = vCredential; + } +; +externalModelLocalRuntimePath[ExternalModelStatement vParent] +{ +StringLiteral vLocalRuntimePath; +} + : + tLocalRuntimePath:Identifier EqualsSign vLocalRuntimePath = stringLiteral + { + Match(tLocalRuntimePath, CodeGenerationSupporter.LocalRuntimePath); + vParent.LocalRuntimePath = vLocalRuntimePath; + } + ; +externalModelParameters[ExternalModelStatement vParent] +{ + StringLiteral vParameters; +} + : + tParameters:Identifier EqualsSign vParameters = stringLiteral + { + Match(tParameters, CodeGenerationSupporter.Parameters); + vParent.Parameters = vParameters; + } + ; + +alterExternalModelStatement returns [AlterExternalModelStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vName; + long encounteredOptions = 0; +} + : tModel:Identifier vName = identifier + { + Match(tModel, CodeGenerationSupporter.Model); + vResult.Name = vName; + ThrowPartialAstIfPhaseOne(vResult); + } + tSet:Set LeftParenthesis + ( + {NextTokenMatches(CodeGenerationSupporter.Location)}? + externalModelLocation[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ApiFormat)}? + externalModelApiFormat[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelType)}? + externalModelModelType[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelName)}? + externalModelModelName[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Credential)}? + externalModelCredential[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.LocalRuntimePath)}? + externalModelLocalRuntimePath[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Parameters)}? + externalModelParameters[vResult] + ) + + ( + tComma:Comma + ( + {NextTokenMatches(CodeGenerationSupporter.Location)}? + externalModelLocation[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ApiFormat)}? + externalModelApiFormat[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelType)}? + externalModelModelType[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.ModelName)}? + externalModelModelName[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Credential)}? + externalModelCredential[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.LocalRuntimePath)}? + externalModelLocalRuntimePath[vResult] + | + {NextTokenMatches(CodeGenerationSupporter.Parameters)}? + externalModelParameters[vResult] + ) + )* + + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult,tRParen); + } + ; + +dropExternalModelStatement returns [DropExternalModelStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vName; +} + : tModel:Identifier vName = identifier + { + Match(tModel, CodeGenerationSupporter.Model); + vResult.Name = vName; + ThrowPartialAstIfPhaseOne(vResult); + } + ; + createExternalDataSourceStatement returns [CreateExternalDataSourceStatement vResult = FragmentFactory.CreateFragment()] { Identifier vName; @@ -23852,11 +24249,11 @@ externalDataSourceType[CreateExternalDataSourceStatement vParent] UpdateTokenInfo(vParent, tExternalDataSourceType); vParent.DataSourceType = ExternalDataSourceType.BLOB_STORAGE; } - else - { - UpdateTokenInfo(vParent, tExternalDataSourceType); + else + { + UpdateTokenInfo(vParent, tExternalDataSourceType); vParent.DataSourceType = ExternalDataSourceType.EXTERNAL_GENERICS; - } + } } ) ; @@ -24026,7 +24423,7 @@ createExternalStreamStatement returns [CreateExternalStreamStatement vResult = F {NextTokenMatches(CodeGenerationSupporter.Location)}? externalStreamLocation[vResult] | - {NextTokenMatches(CodeGenerationSupporter.InputOptions)}? + {NextTokenMatches(CodeGenerationSupporter.InputOptions)}? externalStreamInputOptions[vResult] | {NextTokenMatches(CodeGenerationSupporter.OutputOptions)}? @@ -29393,11 +29790,11 @@ generatedAlwaysClause [ColumnDefinition vResult] } else if (TryMatch(tGeneratedType, CodeGenerationSupporter.TransactionId)) { - vResult.GeneratedAlways = GeneratedAlwaysType.TransactionIdStart; + vResult.GeneratedAlways = GeneratedAlwaysType.TransactionIdStart; } else if (TryMatch(tGeneratedType, CodeGenerationSupporter.SequenceNumber)) - { - vResult.GeneratedAlways = GeneratedAlwaysType.SequenceNumberStart; + { + vResult.GeneratedAlways = GeneratedAlwaysType.SequenceNumberStart; } else { @@ -29861,7 +30258,7 @@ uniqueTableConstraint [IndexAffectingStatement statementType] returns [UniqueCon ( uniqueConstraintEnforcement[vResult] | - uniqueConstraintTailOpt[statementType, vResult] + uniqueConstraintTailOpt[statementType, vResult] ) ; @@ -31629,6 +32026,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.IIf) && (LA(2) == LeftParenthesis)}? vResult=iIfCall + | + {NextTokenMatches(CodeGenerationSupporter.AIGenerateEmbeddings) && LA(2) == LeftParenthesis}? + vResult = aiGenerateEmbeddingsFunctionCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -31663,6 +32063,58 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v collationOpt[vResult] ; +aiGenerateEmbeddingsFunctionCall + returns [AIGenerateEmbeddingsFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vInput; + SchemaObjectName vModelName; + ScalarExpression vParams = null; +} + : + tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AIGenerateEmbeddings); + UpdateTokenInfo(vResult, tFunc); + } + vInput=expression + { + vResult.Input = vInput; + } + + tUse:Use // your reserved keyword + { + UpdateTokenInfo(vResult, tUse); + } + + tModel:Identifier + { + Match(tModel, CodeGenerationSupporter.Model); + } + + vModelName=schemaObjectThreePartName + { + vResult.ModelName = vModelName; + } + + ( + tParams:Identifier + { + Match(tParams, CodeGenerationSupporter.Parameters); + } + LeftParenthesis + vParams=expression + RightParenthesis + { + vResult.OptionalParameters = vParams; + } + )? + + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } + ; + parenthesisDisambiguatorForExpressions [ExpressionFlags expressionFlags] returns [PrimaryExpression vResult] : @@ -31962,6 +32414,36 @@ expressionList [TSqlFragment vParent, IList expressions] | /* empty */ ) + ( + jsonReturningClause[vParent] + | + /* empty */ + ) + ; + + jsonObjectAggExpressionList [FunctionCall vParent] + { + JsonKeyValue vExpression; + } + : + ( + vExpression=jsonKeyValueExpression + { + AddAndUpdateTokenInfo(vParent, vParent.JsonParameters, vExpression); + } + | + /* empty */ + ) + ( + jsonNullClauseFunction[vParent] + | + /* empty */ + ) + ( + jsonReturningClause[vParent] + | + /* empty */ + ) ; jsonNullClauseFunction [FunctionCall vParent] @@ -31970,7 +32452,7 @@ expressionList [TSqlFragment vParent, IList expressions] Identifier vAbsent; } : - ( + ( Null On Null { vNull = FragmentFactory.CreateFragment(); @@ -31988,24 +32470,40 @@ expressionList [TSqlFragment vParent, IList expressions] } ) ; - + +jsonReturningClause [FunctionCall vParent] +{ + Identifier vJson; +} +: + tReturning:Identifier tJson:Identifier + { + Match(tReturning, CodeGenerationSupporter.Returning); + Match(tJson, CodeGenerationSupporter.Json); + UpdateTokenInfo(vParent,tJson); + vJson = FragmentFactory.CreateFragment(); + AddAndUpdateTokenInfo(vParent, vParent.ReturnType, vJson); + vJson.SetUnquotedIdentifier(tJson.getText()); + } +; + jsonKeyValueExpression returns [JsonKeyValue vResult = FragmentFactory.CreateFragment()] { ScalarExpression vKey; ScalarExpression vValue; } - : + : ( vKey=expression - { - vResult.JsonKeyName=vKey; - } + { + vResult.JsonKeyName=vKey; + } Colon vValue=expression - { - vResult.JsonValue=vValue; + { + vResult.JsonValue=vValue; } - ) - ; + ) + ; windowClause returns [WindowClause vResult = FragmentFactory.CreateFragment()] { @@ -32284,6 +32782,9 @@ builtInFunctionCall returns [FunctionCall vResult = FragmentFactory.CreateFragme | {(vResult.FunctionName != null && vResult.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonObject)}? jsonObjectBuiltInFunctionCall[vResult] + | + {(vResult.FunctionName != null && vResult.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonObjectAgg)}? + jsonObjectAggBuiltInFunctionCall[vResult] | {(vResult.FunctionName != null && vResult.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.Trim) && (NextTokenMatches(CodeGenerationSupporter.Leading) | NextTokenMatches(CodeGenerationSupporter.Trailing) | NextTokenMatches(CodeGenerationSupporter.Both))}? @@ -32317,6 +32818,11 @@ jsonArrayBuiltInFunctionCall [FunctionCall vParent] | /* empty */ ) + ( + jsonReturningClause[vParent] + | + /* empty */ + ) tRParen:RightParenthesis { UpdateTokenInfo(vParent, tRParen); @@ -32339,6 +32845,20 @@ jsonObjectBuiltInFunctionCall [FunctionCall vParent] } ; +jsonObjectAggBuiltInFunctionCall [FunctionCall vParent] +{ +} + : ( + jsonObjectAggExpressionList[vParent] + | + /* empty */ + ) + tRParen:RightParenthesis + { + UpdateTokenInfo(vParent, tRParen); + } + ; + regularBuiltInFunctionCall [FunctionCall vParent] { ColumnReferenceExpression vColumn; @@ -32402,19 +32922,19 @@ ignoreRespectNulls [FunctionCall vParent] Identifier vNulls; } : - tIgnoreOrRespect:Identifier + tIgnoreOrRespect:Identifier { - Match(tIgnoreOrRespect, CodeGenerationSupporter.Ignore, CodeGenerationSupporter.Respect); + Match(tIgnoreOrRespect, CodeGenerationSupporter.Ignore, CodeGenerationSupporter.Respect); vIgnoreOrRespect = FragmentFactory.CreateFragment(); - AddAndUpdateTokenInfo(vParent, vParent.IgnoreRespectNulls, vIgnoreOrRespect); - vIgnoreOrRespect.SetUnquotedIdentifier(tIgnoreOrRespect.getText()); + AddAndUpdateTokenInfo(vParent, vParent.IgnoreRespectNulls, vIgnoreOrRespect); + vIgnoreOrRespect.SetUnquotedIdentifier(tIgnoreOrRespect.getText()); } tNulls:Identifier { - Match(tNulls, CodeGenerationSupporter.Nulls); + Match(tNulls, CodeGenerationSupporter.Nulls); vNulls = FragmentFactory.CreateFragment(); - AddAndUpdateTokenInfo(vParent, vParent.IgnoreRespectNulls, vNulls); - vNulls.SetUnquotedIdentifier(tNulls.getText()); + AddAndUpdateTokenInfo(vParent, vParent.IgnoreRespectNulls, vNulls); + vNulls.SetUnquotedIdentifier(tNulls.getText()); } ; @@ -33480,9 +34000,9 @@ nonEmptyString returns [StringLiteral vResult] } ; - defaultValueLiteral returns [ScalarExpression vResult] - : vResult = literal - | vResult = signedIntegerOrReal; + defaultValueLiteral returns [ScalarExpression vResult] + : vResult = literal + | vResult = signedIntegerOrReal; stringLiteral returns [StringLiteral vResult = this.FragmentFactory.CreateFragment()] : tAsciiStringLiteral:AsciiStringLiteral @@ -33744,6 +34264,7 @@ securityStatementPermission returns [Identifier vResult = this.FragmentFactory.C } : tId:Identifier + | AiGenerateEmbeddings | Add | All | Alter diff --git a/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs index 5c332e56..2ca8412a 100644 --- a/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs @@ -46,5 +46,29 @@ public TSql170ParserBaseInternal(bool initialQuotedIdentifiersOn) } #endregion + + /// + /// Parses security object kind with support for External Model (TSql170+) + /// + /// The first identifier. + /// The second identifier. + /// The security object kind. + protected SecurityObjectKind ParseSecurityObjectKindTSql170(Identifier identifier1, Identifier identifier2) + { + if (identifier1 == null) + { + throw new ArgumentNullException(nameof(identifier1)); + } + + switch (identifier1.Value.ToUpperInvariant()) + { + case CodeGenerationSupporter.External: + Match(identifier2, CodeGenerationSupporter.Model); + return SecurityObjectKind.ExternalModel; + default: + // Fall back to the base class implementation for all other cases + return TSql160ParserBaseInternal.ParseSecurityObjectKind(identifier1, identifier2); + } + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs new file mode 100644 index 00000000..31298995 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs @@ -0,0 +1,121 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System.Globalization; +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(AlterExternalModelStatement node) + { + GenerateKeyword(TSqlTokenType.Alter); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.External); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Model); + GenerateAlterExternalModelStatementBody(node); + } + + protected void GenerateAlterExternalModelStatementBody(AlterExternalModelStatement node) + { + // external model name + GenerateSpaceAndFragmentIfNotNull(node.Name); + + NewLine(); + GenerateKeywordAndSpace(TSqlTokenType.Set); + GenerateKeyword(TSqlTokenType.LeftParenthesis); + bool ifFirst = true; + // external model location + if (node.Location != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.Location, node.Location); + } + + // external model API Format options + if (node.ApiFormat != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.ApiFormat, node.ApiFormat); + } + + // external model Model Type options + if (node.ModelType == ExternalModelTypeOption.EMBEDDINGS) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + ExternalModelTypeOption typeOption = ExternalModelTypeOption.EMBEDDINGS; + string externalModelTypeOption = GetValueForEnumKey(_externalModelTypeOption, typeOption); + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.ModelType, externalModelTypeOption); + } + + // external model name options + if (node.ModelName != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.ModelName, node.ModelName); + } + + // external model credential options + if (node.Credential != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.Credential, node.Credential); + } + + // external model parameters options + if (node.Parameters != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.Parameters, node.Parameters); + } + + // external model local runtime path options + if (node.LocalRuntimePath != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.LocalRuntimePath, node.LocalRuntimePath); + } + + NewLine(); + GenerateKeyword(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.DropExternalModelStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.DropExternalModelStatement.cs new file mode 100644 index 00000000..707fe8f9 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.DropExternalModelStatement.cs @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + // Generates the statement + // DROP EXTERNAL MODEL [{node.Name}] + // + public override void ExplicitVisit(DropExternalModelStatement node) + { + GenerateKeyword(TSqlTokenType.Drop); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.External); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Model); + + GenerateSpaceAndFragmentIfNotNull(node.Name); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AIGenerateFixedChunksTableReference.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AIGenerateFixedChunksTableReference.cs new file mode 100644 index 00000000..318cee05 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AIGenerateFixedChunksTableReference.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(AIGenerateFixedChunksTableReference node) + { + List<(string, TSqlFragment)> specificParameters = new List<(string, TSqlFragment)>(); + specificParameters.Add((CodeGenerationSupporter.ChunkSize, node.ChunkSize)); + + if (node.Overlap != null) + { + specificParameters.Add((CodeGenerationSupporter.Overlap, node.Overlap)); + } + + if (node.EnableChunkSetId != null) + { + specificParameters.Add((CodeGenerationSupporter.EnableChunkSetId, node.EnableChunkSetId)); + } + + GenerateAIChunkTableReference(node, specificParameters); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateChunksTableReference.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateChunksTableReference.cs new file mode 100644 index 00000000..eefa100e --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateChunksTableReference.cs @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public void GenerateNameValuePairs(IList<(string Name, TSqlFragment Value)> pairs) + { + for (int index = 0; index < pairs.Count; index++) + { + (string name, TSqlFragment value) = pairs[index]; + + if (index > 0) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + } + + GenerateIdentifierWithoutCasing(name); + GenerateSpace(); + GenerateSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + GenerateFragmentIfNotNull(value); + } + } + + public void GenerateAIChunkTableReference(AIGenerateChunksTableReference node, IList<(string, TSqlFragment)> additionalParameters) + { + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.AiGenerateChunks); + GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); + + // Include common parameters: source, chunk_type + List<(string, TSqlFragment)> parameters = new List<(string, TSqlFragment)>(); + parameters.Add((CodeGenerationSupporter.Source, node.Source)); + parameters.Add((CodeGenerationSupporter.ChunkType, node.ChunkType)); + parameters.AddRange(additionalParameters); + + GenerateNameValuePairs(parameters); + + GenerateSymbol(TSqlTokenType.RightParenthesis); + + GenerateSpaceAndAlias(node.Alias); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs new file mode 100644 index 00000000..0efdc605 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs @@ -0,0 +1,48 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(AIGenerateEmbeddingsFunctionCall node) + { + if (node.Input == null || node.ModelName == null) + { + return; + } + + // Emit function name without extra space before '(' + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.AIGenerateEmbeddings); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + // Emit input expression + GenerateFragmentIfNotNull(node.Input); + + // Emit " USE MODEL" with explicit spaces + GenerateSpace(); + GenerateKeyword(TSqlTokenType.Use); + GenerateSpace(); + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.Model); + GenerateSpaceAndFragmentIfNotNull(node.ModelName); + + // Emit optional PARAMETERS block + if (node.OptionalParameters != null) + { + GenerateSpace(); + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.Parameters); + GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.OptionalParameters); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + + // Emit closing parenthesis + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs new file mode 100644 index 00000000..8e01b6ba --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs @@ -0,0 +1,122 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using System.Globalization; +using Microsoft.SqlServer.TransactSql.ScriptDom; +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(CreateExternalModelStatement node) + { + GenerateKeyword(TSqlTokenType.Create); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.External); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Model); + GenerateCreateExternalModelStatementBody(node); + } + protected static Dictionary _externalModelTypeOption = new Dictionary() + { + {ExternalModelTypeOption.EMBEDDINGS, CodeGenerationSupporter.Embeddings} + }; + + protected void GenerateCreateExternalModelStatementBody(CreateExternalModelStatement node) + { + // external model name + GenerateSpaceAndFragmentIfNotNull(node.Name); + GenerateOwnerIfNotNull(node.Owner); + + NewLine(); + GenerateKeywordAndSpace(TSqlTokenType.With); + GenerateKeyword(TSqlTokenType.LeftParenthesis); + bool ifFirst = true; + + // external model location + if (node.Location != null) + { + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.Location, node.Location); + ifFirst = false; + } + + // external model API Format options + if (node.ApiFormat != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.ApiFormat, node.ApiFormat); + } + + // external model Model Type options + if (node.ModelType == ExternalModelTypeOption.EMBEDDINGS) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + ExternalModelTypeOption typeOption = ExternalModelTypeOption.EMBEDDINGS; + string externalModelTypeOption = GetValueForEnumKey(_externalModelTypeOption, typeOption); + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.ModelType, externalModelTypeOption); + } + + // external model name options + if (node.ModelName != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.ModelName, node.ModelName); + } + + // external model credential options + if (node.Credential != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.Credential, node.Credential); + } + + // external model parameters options + if (node.Parameters != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.Parameters, node.Parameters); + } + + // external model local runtime path options + if (node.LocalRuntimePath != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + GenerateNameEqualsValue(CodeGenerationSupporter.LocalRuntimePath, node.LocalRuntimePath); + } + + NewLine(); + GenerateKeyword(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs index daf325db..f4e50f9f 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs @@ -55,6 +55,20 @@ public override void ExplicitVisit(FunctionCall node) if (node.JsonParameters?.Count > 0 && node.AbsentOrNullOnNull?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them GenerateSpace(); GenerateNullOnNullOrAbsentOnNull(node?.AbsentOrNullOnNull); + if (node.JsonParameters?.Count > 0 && node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them + GenerateSpace(); + GenerateReturnType(node?.ReturnType); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonObjectAgg) + { + GenerateCommaSeparatedList(node.JsonParameters); + if (node.JsonParameters?.Count > 0 && node.AbsentOrNullOnNull?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them + GenerateSpace(); + GenerateNullOnNullOrAbsentOnNull(node?.AbsentOrNullOnNull); + if (node.JsonParameters?.Count > 0 && node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them + GenerateSpace(); + GenerateReturnType(node?.ReturnType); GenerateSymbol(TSqlTokenType.RightParenthesis); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonArray) @@ -63,6 +77,9 @@ public override void ExplicitVisit(FunctionCall node) if (node.Parameters?.Count > 0 && node?.AbsentOrNullOnNull?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them GenerateSpace(); GenerateNullOnNullOrAbsentOnNull(node?.AbsentOrNullOnNull); + if (node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them + GenerateSpace(); + GenerateReturnType(node?.ReturnType); GenerateSymbol(TSqlTokenType.RightParenthesis); } else @@ -117,5 +134,14 @@ private void GenerateNullOnNullOrAbsentOnNull(IList list) GenerateKeyword(TSqlTokenType.Null); } } + private void GenerateReturnType(IList list) + { + if (list?.Count > 0 && list[0].Value?.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.Json) + { + GenerateIdentifier("RETURNING"); + GenerateSpace(); + GenerateSpaceSeparatedList(list); + } + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SecurityTargetObject.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SecurityTargetObject.cs index ebceaa02..571e65db 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SecurityTargetObject.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SecurityTargetObject.cs @@ -13,7 +13,7 @@ partial class SqlScriptGeneratorVisitor protected static Dictionary> _securityObjectKindGenerators = new Dictionary>() { - { SecurityObjectKind.AvailabilityGroup, new List() { + { SecurityObjectKind.AvailabilityGroup, new List() { new IdentifierGenerator(CodeGenerationSupporter.Availability, true), new IdentifierGenerator(CodeGenerationSupporter.Group) }}, @@ -96,11 +96,15 @@ partial class SqlScriptGeneratorVisitor { SecurityObjectKind.FullTextStopList, new List() { new IdentifierGenerator(CodeGenerationSupporter.Fulltext, true), new KeywordGenerator(TSqlTokenType.StopList)}}, - + { SecurityObjectKind.SearchPropertyList, new List() { new IdentifierGenerator(CodeGenerationSupporter.Search, true), new IdentifierGenerator(CodeGenerationSupporter.Property, true), new IdentifierGenerator(CodeGenerationSupporter.List)}}, + + { SecurityObjectKind.ExternalModel, new List() { + new IdentifierGenerator(CodeGenerationSupporter.External, true), + new IdentifierGenerator(CodeGenerationSupporter.Model) }}, }; diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs new file mode 100644 index 00000000..55e4730a --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs @@ -0,0 +1,56 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Script generator visitor for VECTOR_SEARCH function: https://learn.microsoft.com/sql/t-sql/functions/vector-search-transact-sql + /// Syntax: + /// VECTOR_SEARCH( + /// TABLE = object[AS source_table_alias], + /// COLUMN = vector_column, + /// SIMILAR_TO = query_vector, + /// METRIC = { 'cosine' | 'dot' | 'euclidean' }, + /// TOP_N = k + /// ) [AS result_table_alias] + /// + public override void ExplicitVisit(VectorSearchTableReference node) + { + AlignmentPoint start = new AlignmentPoint(); + MarkAndPushAlignmentPoint(start); + + GenerateIdentifier(CodeGenerationSupporter.VectorSearch); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + NewLineAndIndent(); + GenerateNameEqualsValue(TSqlTokenType.Table, node.Table); + GenerateSymbol(TSqlTokenType.Comma); + + NewLineAndIndent(); + GenerateNameEqualsValue(TSqlTokenType.Column, node.Column); + GenerateSymbol(TSqlTokenType.Comma); + + NewLineAndIndent(); + GenerateNameEqualsValue(CodeGenerationSupporter.SimilarTo, node.SimilarTo); + GenerateSymbol(TSqlTokenType.Comma); + + NewLineAndIndent(); + GenerateNameEqualsValue(CodeGenerationSupporter.Metric, node.Metric); + GenerateSymbol(TSqlTokenType.Comma); + + NewLineAndIndent(); + GenerateNameEqualsValue(CodeGenerationSupporter.TopN, node.TopN); + + NewLine(); + GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateSpaceAndAlias(node.Alias); + + PopAlignmentPoint(); + } + } +} diff --git a/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql b/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql new file mode 100644 index 00000000..8374acc9 --- /dev/null +++ b/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql @@ -0,0 +1,101 @@ +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = 50); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = NULL, ENABLE_CHUNK_SET_ID = 50); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = 10, ENABLE_CHUNK_SET_ID = 1); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = @SOURCE, CHUNK_TYPE = fixed, CHUNK_SIZE = @CHUNK_SIZE); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = @SOURCE, CHUNK_TYPE = fixed, CHUNK_SIZE = @CHUNK_SIZE, OVERLAP = @OVERLAP, ENABLE_CHUNK_SET_ID = @ENABLE_CHUNK_SET_ID); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = NULL, CHUNK_TYPE = fixed, CHUNK_SIZE = 5); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t1.c1, CHUNK_TYPE = fixed, CHUNK_SIZE = 10); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = t1.c1); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = t1.c1); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = 5, ENABLE_CHUNK_SET_ID = t1.c1); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = NULL); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = NULL); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = 5, ENABLE_CHUNK_SET_ID = NULL); + +CREATE TABLE t2 ( + Id INT IDENTITY PRIMARY KEY, + Text NVARCHAR (MAX) +); +GO + +INSERT INTO t2 (Text) +VALUES (N'This is the first text.'), +(N'Second sample text.'), +(N'Third example text.'); +GO + +CREATE VIEW v_GeneratedChunksFromTable +AS +SELECT t2.Id, + chunks.* +FROM t2 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t2.Text, CHUNK_TYPE = fixed, CHUNK_SIZE = 5) AS chunks; +GO + +CREATE PROCEDURE usp_GenerateChunks +AS +BEGIN + SELECT * + FROM AI_GENERATE_CHUNKS (SOURCE = N'This is some sample text that will be chunked.', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = 2); +END +GO + +CREATE FUNCTION dbo.AI_GENERATE_CHUNKS +(@input NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN CONCAT('Chunked: ', @input); +END +GO + +CREATE TABLE dbo.AI_GENERATE_CHUNKS ( + id INT PRIMARY KEY, + data NVARCHAR (MAX) +); + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS(target); + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS](SOURCE); + + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS([SOURCE]); + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS]([SOURCE]); + +SELECT * +FROM dbo.AI_GENERATE_CHUNKS(3); \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/AiGenerateEmbeddingsTests170.sql b/Test/SqlDom/Baselines170/AiGenerateEmbeddingsTests170.sql new file mode 100644 index 00000000..72493c7f --- /dev/null +++ b/Test/SqlDom/Baselines170/AiGenerateEmbeddingsTests170.sql @@ -0,0 +1,52 @@ +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyDefaultModel); +SELECT AI_GENERATE_EMBEDDINGS(N'My Default Input Text' USE MODEL MyDefaultModel); +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyDefaultModel PARAMETERS (TRY_CONVERT (JSON, N'{}'))); +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL dbo.MyDefaultModel); +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyDatabase.dbo.MyDefaultModel); +GO + +CREATE FUNCTION dbo.AI_GENERATE_EMBEDDINGS +(@input NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN CONCAT('Embed: ', @input); +END +GO + +CREATE TABLE dbo.AI_GENERATE_EMBEDDINGS ( + id INT PRIMARY KEY, + data NVARCHAR (MAX) +); +GO + +CREATE VIEW dbo.ai_generate_embeddings +AS +SELECT 'View result' AS result; +GO + +CREATE FUNCTION dbo.MyEmbeddingFunction +( ) +RETURNS TABLE +AS +RETURN + SELECT AI_GENERATE_EMBEDDINGS('Function Input' USE MODEL MyDefaultModel) AS EmbeddingResult +GO + +CREATE VIEW dbo.MyEmbeddingView +AS +SELECT AI_GENERATE_EMBEDDINGS(N'View Input' USE MODEL dbo.MyDefaultModel) AS EmbeddingResult; +GO + +CREATE TABLE dbo.SimpleEmbeddingTable ( + InputText NVARCHAR (MAX), + Embedding AS CONVERT (NVARCHAR (MAX), AI_GENERATE_EMBEDDINGS(InputText USE MODEL MyDefaultModel)) +); +GO + +CREATE PROCEDURE dbo.GetEmbedding +@InputText NVARCHAR (MAX) +AS +BEGIN + SELECT CONVERT (NVARCHAR (MAX), AI_GENERATE_EMBEDDINGS(@InputText USE MODEL MyDefaultModel)) AS Embedding; +END diff --git a/Test/SqlDom/Baselines170/AlterExternalModelStatementTests170.sql b/Test/SqlDom/Baselines170/AlterExternalModelStatementTests170.sql new file mode 100644 index 00000000..e9b590c8 --- /dev/null +++ b/Test/SqlDom/Baselines170/AlterExternalModelStatementTests170.sql @@ -0,0 +1,27 @@ +ALTER EXTERNAL MODEL abc +SET ( +LOCATION = 'new_location', +API_FORMAT = 'Ollama', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'new_model', +PARAMETERS = '{"key":"new_value"}' +); +ALTER EXTERNAL MODEL abc +SET ( +MODEL = 'new_model' +); +ALTER EXTERNAL MODEL params_model +SET ( +PARAMETERS = '{"temperature":0.7, "max_tokens":2048}' +); +ALTER EXTERNAL MODEL ml_model +SET ( +API_FORMAT = 'OpenAI', +MODEL = 'gpt-3.5-turbo-16k', +PARAMETERS = '{"stream":true}' +); +ALTER EXTERNAL MODEL location_change +SET ( +LOCATION = '/new/model/path', +MODEL_TYPE = EMBEDDINGS +); \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/CreateExternalModelStatementTests170.sql b/Test/SqlDom/Baselines170/CreateExternalModelStatementTests170.sql new file mode 100644 index 00000000..88914762 --- /dev/null +++ b/Test/SqlDom/Baselines170/CreateExternalModelStatementTests170.sql @@ -0,0 +1,33 @@ +CREATE EXTERNAL MODEL abc + AUTHORIZATION dbo +WITH ( +LOCATION = 'sdfasfd', +API_FORMAT = 'Ollama', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'shghfh', +PARAMETERS = '{"key":"valuoipe"}' +); +CREATE EXTERNAL MODEL simple_model +WITH ( +LOCATION = '/models/simple', +API_FORMAT = 'OpenAI', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'gpt-3.5-turbo' +); +CREATE EXTERNAL MODEL advanced_model +WITH ( +LOCATION = 'https://models.example.com/advanced', +API_FORMAT = 'Azure OpenAI', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'bert-base-uncased', +PARAMETERS = '{"batch_size":32,"device":"cuda"}' +); +CREATE EXTERNAL MODEL [model_name] +WITH ( +LOCATION = 'FILE PATH', +API_FORMAT = 'onnx runtime', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'text-embedding-ada-002,etc', +PARAMETERS = '{ "valid":"JSON"}', +LOCAL_RUNTIME_PATH = 'Path on local server to onnx runtime' +); \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/DropExternalModelStatementTests170.sql b/Test/SqlDom/Baselines170/DropExternalModelStatementTests170.sql new file mode 100644 index 00000000..127b413d --- /dev/null +++ b/Test/SqlDom/Baselines170/DropExternalModelStatementTests170.sql @@ -0,0 +1 @@ +DROP EXTERNAL MODEL my_model1; \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/JsonFunctionTests170.sql b/Test/SqlDom/Baselines170/JsonFunctionTests170.sql new file mode 100644 index 00000000..29adc383 --- /dev/null +++ b/Test/SqlDom/Baselines170/JsonFunctionTests170.sql @@ -0,0 +1,101 @@ +SELECT id, + json_col +FROM tab1 +WHERE ISJSON(json_col) = 1; + +SELECT id, + json_col +FROM tab1 +WHERE ISJSON(json_col, SCALAR) = 1; + +SELECT ISJSON('true', VALUE); + +DECLARE @jsonInfo AS NVARCHAR (MAX); + +SET @jsonInfo = N'{"info":{"address":[{"town":"Paris"},{"town":"London"}]}}'; + +SELECT JSON_PATH_EXISTS(@jsonInfo, '$.info.address'); + +SELECT JSON_OBJECT('name':'value'); + +SELECT JSON_OBJECT('name':'value', 'type':1 NULL ON NULL); + +SELECT JSON_OBJECT(NULL ON NULL); + +SELECT JSON_OBJECT('name':'value', 'type':NULL ABSENT ON NULL); + +SELECT JSON_OBJECT('name':'value', 'type':JSON_OBJECT('type_id':1, 'name':'a')); + +SELECT JSON_OBJECT(); + +SELECT JSON_OBJECT('name':'value', 'type':1); + +SELECT JSON_OBJECT('name':'value', 'type':JSON_ARRAY(1, 2)); + +DECLARE @id_key AS NVARCHAR (10) = N'id', @id_value AS NVARCHAR (64) = NEWID(); + +SELECT JSON_OBJECT('user_name':USER_NAME(), @id_key:@id_value, 'sid':(SELECT @@SPID)); + +SELECT s.session_id, + JSON_OBJECT('security_id':s.security_id, 'login':s.login_name, 'status':s.status) AS info +FROM sys.dm_exec_sessions AS s +WHERE s.is_user_process = 1; + +SELECT JSON_OBJECT('name':'b' RETURNING JSON); + +SELECT JSON_OBJECT('name':'b' NULL ON NULL RETURNING JSON); + +SELECT JSON_OBJECT('name':'b' ABSENT ON NULL RETURNING JSON); + +SELECT JSON_ARRAY('a', JSON_OBJECT('name':'value', 'type':1 NULL ON NULL) NULL ON NULL); + +SELECT JSON_ARRAY(); + +SELECT JSON_ARRAY('name'); + +SELECT JSON_ARRAY('a', 1, 'b', 2); + +SELECT JSON_ARRAY('a', 1, NULL, 2 NULL ON NULL); + +SELECT JSON_ARRAY('a', 1, NULL, 2 ABSENT ON NULL); + +SELECT JSON_ARRAY(NULL ON NULL); + +SELECT JSON_ARRAY(ABSENT ON NULL); + +DECLARE @id_value AS NVARCHAR (64) = NEWID(); + +SELECT JSON_ARRAY(1, @id_value, (SELECT @@SPID)); + +SELECT s.session_id, + JSON_ARRAY(s.host_name, s.program_name, s.client_interface_name) +FROM sys.dm_exec_sessions AS s +WHERE s.is_user_process = 1; + +SELECT JSON_ARRAY('a', 1, NULL, 2 RETURNING JSON); + +SELECT JSON_ARRAY('a', 1, NULL, 2 NULL ON NULL RETURNING JSON); + +SELECT JSON_ARRAY('a', 1, NULL, 2 ABSENT ON NULL RETURNING JSON); + +SELECT JSON_OBJECTAGG('name':'value'); + +SELECT JSON_OBJECTAGG('name':'value' NULL ON NULL); + +SELECT JSON_OBJECTAGG(NULL ON NULL); + +SELECT JSON_OBJECTAGG('name':NULL ABSENT ON NULL); + +SELECT JSON_OBJECTAGG('name':JSON_OBJECT('type_id':1, 'name':'a')); + +SELECT JSON_OBJECTAGG(); + +SELECT JSON_OBJECTAGG('name':1); + +SELECT JSON_OBJECTAGG('name':JSON_ARRAY(1, 2)); +SELECT JSON_OBJECTAGG('name':'b' NULL ON NULL RETURNING JSON); + +SELECT JSON_OBJECTAGG('name':'b' ABSENT ON NULL RETURNING JSON); + +SELECT JSON_OBJECTAGG('name':'b' RETURNING JSON); + diff --git a/Test/SqlDom/Baselines170/RegexpTests170.sql b/Test/SqlDom/Baselines170/RegexpTests170.sql new file mode 100644 index 00000000..e13c3dab --- /dev/null +++ b/Test/SqlDom/Baselines170/RegexpTests170.sql @@ -0,0 +1,22 @@ +SELECT REGEXP_COUNT('hello', 'he(l+)o'); +SELECT REGEXP_COUNT('hello', 'he(l+)o', 1); +SELECT REGEXP_COUNT('hello', 'he(l+)o', 1, 'i'); + +SELECT REGEXP_INSTR('hello', 'he(l+)o'); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1, 0); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1, 0, 'i'); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1, 0, 'c', 1); + +SELECT REGEXP_REPLACE('hello', 'he(l+)o'); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o'); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o', 1); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o', 1, 1); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o', 1, 1, 'm'); + +SELECT REGEXP_SUBSTR('hello', 'he(l+)o'); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1, 1); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1, 1, 's'); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1, 1, 'c', 1); \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/SecurityStatementExternalModelTests170.sql b/Test/SqlDom/Baselines170/SecurityStatementExternalModelTests170.sql new file mode 100644 index 00000000..a64b7b77 --- /dev/null +++ b/Test/SqlDom/Baselines170/SecurityStatementExternalModelTests170.sql @@ -0,0 +1,71 @@ +GRANT ALTER ANY EXTERNAL MODEL TO datascientist; + +GRANT ALTER ANY EXTERNAL MODEL TO PUBLIC + WITH GRANT OPTION; + +GRANT ALTER ANY EXTERNAL MODEL TO mlrole, adminrole + AS dbo; + +GRANT EXECUTE + ON EXTERNAL MODEL::MyPredictionModel TO analyst; + +GRANT EXECUTE + ON EXTERNAL MODEL::schema1.ModelName TO user1, user2 + WITH GRANT OPTION; + +GRANT CONTROL + ON EXTERNAL MODEL::dbo.SalesModel TO mladmin + AS dbo; + +GRANT VIEW DEFINITION + ON EXTERNAL MODEL::MySchema.MyModel TO PUBLIC; + +DENY ALTER ANY EXTERNAL MODEL TO restricteduser; + +DENY EXECUTE + ON EXTERNAL MODEL::TestModel TO guest CASCADE; + +DENY CONTROL + ON EXTERNAL MODEL::test.model1 TO user1, user2 CASCADE + AS admin; + +REVOKE ALTER ANY EXTERNAL MODEL TO olduser; + +REVOKE GRANT OPTION FOR EXECUTE + ON EXTERNAL MODEL::MyModel TO tempuser CASCADE; + +REVOKE CONTROL + ON EXTERNAL MODEL::prod.RecommendationModel TO contractor + AS manager; + +REVOKE EXECUTE + ON EXTERNAL MODEL::dbo.CustomerModel TO PUBLIC CASCADE; + +ALTER AUTHORIZATION + ON EXTERNAL MODEL::MyModel + TO newowner; + +ALTER AUTHORIZATION + ON EXTERNAL MODEL::schema1.ModelName + TO SCHEMA OWNER; + +ALTER AUTHORIZATION + ON EXTERNAL MODEL::test.experimentalmodel + TO datateam; + +GRANT EXECUTE, VIEW DEFINITION + ON EXTERNAL MODEL::MultiPermModel TO analyst; + +DENY EXECUTE, CONTROL + ON EXTERNAL MODEL::RestrictedModel TO guest; + +REVOKE EXECUTE, VIEW DEFINITION + ON EXTERNAL MODEL::OldModel TO formeranalyst; + +GRANT EXECUTE + ON EXTERNAL MODEL::MyDatabase.MySchema.ModelWithSpaces TO testuser; + +DENY ALTER ANY EXTERNAL MODEL TO userwithspaces; + +REVOKE CONTROL + ON EXTERNAL MODEL::QuotedModel TO QuotedUser; \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/VectorFunctionTests170.sql b/Test/SqlDom/Baselines170/VectorFunctionTests170.sql new file mode 100644 index 00000000..dc893ed8 --- /dev/null +++ b/Test/SqlDom/Baselines170/VectorFunctionTests170.sql @@ -0,0 +1,23 @@ +DECLARE @qv AS VECTOR (1536) = AI_GENERATE_EMBEDDINGS(N'Pink Floyd music style' USE MODEL Ada2Embeddings); + +SELECT t.id, + s.distance, + t.title +FROM VECTOR_SEARCH( + TABLE = [dbo].[wikipedia_articles_embeddings] AS t, + COLUMN = [content_vector], + SIMILAR_TO = @qv, + METRIC = 'cosine', + TOP_N = 10 + ) AS s +ORDER BY s.distance; + +SELECT * +FROM VECTOR_SEARCH( + TABLE = wikipedia_articles_embeddings, + COLUMN = dbo.wikipedia_articles_embeddings.content_vector, + SIMILAR_TO = @qv, + METRIC = 'dot', + TOP_N = 10 + ) +ORDER BY distance; \ No newline at end of file diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 05ade644..a339cf78 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -13,7 +13,17 @@ public partial class SqlDomTests new ParserTest170("JsonIndexTests170.sql", nErrors80: 2, nErrors90: 8, nErrors100: 8, nErrors110: 8, nErrors120: 8, nErrors130: 8, nErrors140: 8, nErrors150: 8, nErrors160: 8), new ParserTest170("VectorIndexTests170.sql", nErrors80: 2, nErrors90: 12, nErrors100: 12, nErrors110: 12, nErrors120: 12, nErrors130: 12, nErrors140: 12, nErrors150: 12, nErrors160: 12), new ParserTest170("AlterDatabaseManualCutoverTests170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), - new ParserTest170("CreateColumnStoreIndexTests170.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0) + new ParserTest170("CreateColumnStoreIndexTests170.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), + new ParserTest170("RegexpTests170.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), + new ParserTest170("AiGenerateChunksTests170.sql", nErrors80: 21, nErrors90: 18, nErrors100: 17, nErrors110: 17, nErrors120: 17, nErrors130: 17, nErrors140: 17, nErrors150: 17, nErrors160: 17), + new ParserTest170("JsonFunctionTests170.sql", nErrors80: 9, nErrors90: 8, nErrors100: 30, nErrors110: 30, nErrors120: 30, nErrors130: 30, nErrors140: 30, nErrors150: 30, nErrors160: 30), + new ParserTest170("AiGenerateEmbeddingsTests170.sql", nErrors80: 12, nErrors90: 9, nErrors100: 9, nErrors110: 9, nErrors120: 9, nErrors130: 9, nErrors140: 9, nErrors150: 9, nErrors160: 9), + new ParserTest170("CreateExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), + new ParserTest170("AlterExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5), + new ParserTest170("DropExternalModelStatementTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1, nErrors160: 1), + new ParserTest170("VectorFunctionTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), + new ParserTest170("SecurityStatementExternalModelTests170.sql", nErrors80: 2, nErrors90: 17, nErrors100: 17, nErrors110: 17, nErrors120: 17, nErrors130: 17, nErrors140: 17, nErrors150: 17, nErrors160: 17), + }; private static readonly ParserTest[] SqlAzure170_TestInfos = diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 23d2be16..6a463172 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -503,6 +503,51 @@ public void JsonArraySyntaxNegativeTest() new ParserErrorInfo(48, "SQL46010", "ON")); } + /// + /// Negative tests for JSON_OBJECTAGG syntax in functions + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void JsonObjectAGGSyntaxNegativeTest() + { + // Incorrect key value parameter number + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':'value', 'type':1)", + new ParserErrorInfo(36, "SQL46010", ",")); + + // No closing quotation mark + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':'value)", + new ParserErrorInfo(29, "SQL46030", "'value)")); + + // Incorrect placing of colon + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':'value''type':1)", + new ParserErrorInfo(42, "SQL46010", ":")); + + // cannot use expression without colon + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name')", + new ParserErrorInfo(22, "SQL46010", "'name'")); + + // cannot use expression without colon + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name' ABSENT ON NULL)", + new ParserErrorInfo(29, "SQL46010", "ABSENT")); + + // Cannot use empty value + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':)", + new ParserErrorInfo(29, "SQL46010", ")")); + + // Cannot use incomplete absent on null clause cases + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':NULL ABSENT ON)", + new ParserErrorInfo(43, "SQL46010", ")")); + + // Cannot use Incomplete RETURNING clause + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':NULL RETURNING ON)", + new ParserErrorInfo(46, "SQL46010", ")")); + + // Cannot use anything other than JSON in RETURNING clause + ParserTestUtils.ErrorTest170("SELECT JSON_OBJECTAGG('name':NULL RETURNING INT)", + new ParserErrorInfo(44, "SQL46005", "JSON", "INT")); + } + /// /// Negative tests for Data Masking Alter Column syntax. /// @@ -6864,7 +6909,7 @@ FROM OPENROWSET ('a', 'b', [ab cd]) WITH a;"; ParserTestUtils.ErrorTest160(invalidWithClause3Syntax, new ParserErrorInfo(invalidWithClause3Syntax.IndexOf(@"a;"), "SQL46010", "a")); } - + /// /// Negative tests for Scalar Functions in Fabric DW. /// @@ -7031,5 +7076,412 @@ public void VectorIndexNegativeTests() ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH", new ParserErrorInfo(58, "SQL46010", "WITH")); } + + /// + /// Negative tests for AI_GENERATE_CHUNKS syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void GenerateChunksNegativeTest170() + { + // Missing required parameters + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text')", + new ParserErrorInfo(48, "SQL46010", ")")); + + // Missing CHUNK_SIZE + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed)", + new ParserErrorInfo(68, "SQL46010", ")")); + + // Invalid order: CHUNK_SIZE before CHUNK_TYPE + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_SIZE = 5, CHUNK_TYPE = fixed)", + new ParserErrorInfo(50, "SQL46005", "CHUNK_TYPE", "CHUNK_SIZE")); + + // Invalid order: enable_chunk_set_id before overlap + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, enable_chunk_set_id = 1, overlap = 10)", + new ParserErrorInfo(86, "SQL46010", "enable_chunk_set_id")); + + // Invalid order: enable_chunk_set_id before CHUNK_SIZE + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed, enable_chunk_set_id = 1, CHUNK_SIZE = 5, overlap = 10)", + new ParserErrorInfo(70, "SQL46010", "enable_chunk_set_id")); + + // Invalid value: CHUNK_TYPE = 'fixed' (should be keyword, not string) + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = 'fixed', CHUNK_SIZE = 5)", + new ParserErrorInfo(63, "SQL46010", "'fixed'")); + + // Invalid expression: CHUNK_TYPE = @CHUNK_TYPE (should not be variable) + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = @CHUNK_TYPE, CHUNK_SIZE = 5)", + new ParserErrorInfo(63, "SQL46010", "@CHUNK_TYPE")); + + // Invalid parameter: CHUNK_TYPE = t1.c1 (should not be column reference) + ParserTestUtils.ErrorTest170( + "SELECT * FROM t1 CROSS APPLY AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = t1.c1, CHUNK_SIZE = 5)", + new ParserErrorInfo(80, "SQL46010", ".")); + + // Missing value after equals + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = , CHUNK_TYPE = fixed, CHUNK_SIZE = 5)", + new ParserErrorInfo(42, "SQL46010", ",")); + + // Missing value for CHUNK_SIZE + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed, CHUNK_SIZE = )", + new ParserErrorInfo(83, "SQL46010", ")")); + + // Unknown parameter + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, invalid_param = 123)", + new ParserErrorInfo(86, "SQL46010", "invalid_param")); + + // Extra comma at end + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5,)", + new ParserErrorInfo(85, "SQL46010", ")")); + + // Too many parameters + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS(source = 'text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, overlap = 1, enable_chunk_set_id = 2, extra = 3)", + new ParserErrorInfo(122, "SQL46010", ",")); + + // Function call with constant input, not keyword params + ParserTestUtils.ErrorTest170( + "SELECT * FROM ai_generate_chunks(3)", + new ParserErrorInfo(33, "SQL46010", "3")); + + // Missing paramter "source" + ParserTestUtils.ErrorTest170( + "SELECT source, target FROM userTable cross apply ai_generate_chunks(target)", + new ParserErrorInfo(68, "SQL46005", "SOURCE", "target")); + + // Misuse of parameter "source" + ParserTestUtils.ErrorTest170( + "SELECT source, target FROM userTable cross apply ai_generate_chunks(source)", + new ParserErrorInfo(74, "SQL46010", ")")); + + // Misuse of bracketed function name + ParserTestUtils.ErrorTest170( + "SELECT * FROM [ai_generate_chunks](source = 'something to chunk', chunk_type = fixed, chunk_size = 5)", + new ParserErrorInfo(42, "SQL46010", "=")); + + // Misuse of 2-part identifier + ParserTestUtils.ErrorTest170( + "SELECT * FROM dbo.ai_generate_chunks(source = 'something to chunk', chunk_type = fixed, chunk_size = 5)", + new ParserErrorInfo(36, "SQL46010", "(")); + + // 2-part identifier misuse in CROSS APPLY + ParserTestUtils.ErrorTest170( + "SELECT * FROM source CROSS APPLY dbo.ai_generate_chunks(source.c1)", + new ParserErrorInfo(55, "SQL46010", "(")); + + // 2-part identifier misuse in CROSS APPLY + ParserTestUtils.ErrorTest170( + "SELECT source, target FROM userTable cross apply dbo.ai_generate_chunks(source)", + new ParserErrorInfo(71, "SQL46010", "(")); + + // Invalid CHUNK_TYPE + ParserTestUtils.ErrorTest170( + "SELECT * FROM AI_GENERATE_CHUNKS (source = 'some text', chunk_type = other, chunk_size = 5)", + new ParserErrorInfo(69, "SQL46010", "other")); + } + + /// + /// Negative tests for AI_GENERATE_EMBEDDINGS syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void GenerateEmbeddingsNegativeTest170() + { + // Missing required USE MODEL clause + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text')", + new ParserErrorInfo(53, "SQL46010", ")")); + + // Missing model name after USE MODEL + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL)", + new ParserErrorInfo(63, "SQL46010", ")")); + + // Missing USE keyword before MODEL + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' MODEL MyModel)", + new ParserErrorInfo(54, "SQL46010", "MODEL")); + + // USE keyword misplaced before input expression + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS(USE MODEL MyModel 'My Default Input Text')", + new ParserErrorInfo(30, "SQL46010", "USE")); + + // PARAMETERS specified without USE MODEL + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' PARAMETERS (TRY_CONVERT(JSON, N'{}')))", + new ParserErrorInfo(54, "SQL46010", "PARAMETERS")); + + // PARAMETERS missing parentheses + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyModel PARAMETERS TRY_CONVERT(JSON, N'{}'))", + new ParserErrorInfo(83, "SQL46010", "TRY_CONVERT")); + + // Invalid expression inside PARAMETERS (missing closing parenthesis) + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyModel PARAMETERS (TRY_CONVERT(JSON, N'{}')", + new ParserErrorInfo(108, "SQL46029", "EOF")); + + // Extra comma at end inside PARAMETERS + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyModel PARAMETERS (TRY_CONVERT(JSON, N'{}'),))", + new ParserErrorInfo(108, "SQL46010", ",")); + + // PARAMETERS misplaced before input + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS(PARAMETERS (TRY_CONVERT(JSON, N'{}') 'My Default Input Text'))", + new ParserErrorInfo(67, "SQL46010", "'My Default Input Text'")); + + // Missing MODEL keyword after USE + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MyModel)", + new ParserErrorInfo(58, "SQL46005", "MODEL", "MyModel")); + + // NULL model name after USE MODEL + ParserTestUtils.ErrorTest170( + "SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL NULL)", + new ParserErrorInfo(64, "SQL46010", "NULL")); + } + + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CreateExternalModelNegativeTest() + { + // Keyword typos + // + ParserTestUtils.ErrorTest170( + "CREATE EXTERNAL MODLE abc WITH (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDIGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(16, "SQL46010", "MODLE")); + + // Invalid Model type + // + ParserTestUtils.ErrorTest170( + "CREATE EXTERNAL MODEL abc WITH (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDIGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(106, "SQL46010", "EMBEDDIGS")); + + // Model type not identifier + // + ParserTestUtils.ErrorTest170( + "CREATE EXTERNAL MODEL abc WITH (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = 'EMBEDDINGS',MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(106, "SQL46010", "'EMBEDDINGS'")); + + // Missing With Clause + // + ParserTestUtils.ErrorTest170( + "CREATE EXTERNAL MODEL abc (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDINGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(26, "SQL46010", "(")); + + // Missing Model Name + // + ParserTestUtils.ErrorTest170( + "CREATE EXTERNAL MODEL WITH (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDINGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(16, "SQL46010", "MODEL")); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AlterExternalModelNegativeTest() + { + // Keyword typos + // + ParserTestUtils.ErrorTest170( + "ALTER EXTERNAL MODLE abc SET (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDINGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(15, "SQL46010", "MODLE")); + + // Invalid Model type + // + ParserTestUtils.ErrorTest170( + "ALTER EXTERNAL MODEL abc SET (MODEL_TYPE = EMBEDDINS);", + new ParserErrorInfo(43, "SQL46010", "EMBEDDINS")); + + // Model type not identifier + // + ParserTestUtils.ErrorTest170( + "ALTER EXTERNAL MODEL abc SET (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = 'EMBEDDINGS',MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(104, "SQL46010", "'EMBEDDINGS'")); + + // Missing SET Clause + // + ParserTestUtils.ErrorTest170( + "ALTER EXTERNAL MODEL abc (MODEL = 'shghfh');", + new ParserErrorInfo(25, "SQL46010", "(")); + + // WITH instead of SET clause + // + ParserTestUtils.ErrorTest170( + "ALTER EXTERNAL MODEL abc WITH (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDINGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(25, "SQL46010", "WITH")); + + // Missing Model Name + // + ParserTestUtils.ErrorTest170( + "ALTER EXTERNAL MODEL SET (LOCATION = 'www.somemodellocation.235',API_FORMAT = 'Ollama',MODEL_TYPE = EMBEDDINGS,MODEL = 'shghfh',PARAMETERS = '{\"key\":\"value\"}');", + new ParserErrorInfo(15, "SQL46010", "MODEL")); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void DropExternalModelNegativeTest() + { + // Keyword typos + // + ParserTestUtils.ErrorTest170( + "DROP EXTERNAL MODLE abc;", + new ParserErrorInfo(14, "SQL46010", "MODLE")); + + // Missing Model Name + // + ParserTestUtils.ErrorTest170( + "DROP EXTERNAL MODEL;", + new ParserErrorInfo(14, "SQL46010", "MODEL")); + + // Extra keyword + // + ParserTestUtils.ErrorTest170( + "DROP EXTERNAL MODEL abc WITH (LOCATION = 'www.somemodellocation.235');", + new ParserErrorInfo(29, "SQL46010", "(")); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void VectorSearchErrorTest170() + { + // Missing required parameters: TABLE + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH()", + new ParserErrorInfo(28, "SQL46010", ")")); + + // Missing required parameters: COLUMN + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1)", + new ParserErrorInfo(40, "SQL46010", ")")); + + // Missing required parameters: SIMILAR_TO + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1)", + new ParserErrorInfo(55, "SQL46010", ")")); + + // Missing required parameters: METRIC + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector)", + new ParserErrorInfo(82, "SQL46010", ")")); + + // Missing required parameters: TOP_N + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot')", + new ParserErrorInfo(98, "SQL46010", ")")); + + // Invalid order: COLUMN before TABLE + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(COLUMN = col1, TABLE = tbl1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(28, "SQL46010", "COLUMN")); + + // Invalid order: SIMILAR_TO before COLUMN + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, SIMILAR_TO = query_vector, COLUMN = col1, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(42, "SQL46010", "SIMILAR_TO")); + + // Invalid order: METRIC before SIMILAR_TO + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, METRIC = 'dot', SIMILAR_TO = query_vector, TOP_N = 5)", + new ParserErrorInfo(57, "SQL46005", "SIMILAR_TO", "METRIC")); + + // Invalid value: TABLE = 'tbl1' (should be identifier, not string) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = 'tbl1', COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(36, "SQL46010", "'tbl1'")); + + // Invalid value: TABLE = 123 (should be identifier, not integer) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = 123, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(36, "SQL46010", "123")); + + // Invalid value: COLUMN = 'col1' (should be identifier, not string) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = 'col1', SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(51, "SQL46010", "'col1'")); + + // Invalid value: COLUMN = 123 (should be identifier, not integer) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = 123, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(51, "SQL46010", "123")); + + // Invalid value: METRIC = dot (should be string literal) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = dot, TOP_N = 5)", + new ParserErrorInfo(93, "SQL46010", "dot")); + + // Invalid value: METRIC = 'invalid_value' (should be either 'cosine', 'dot', or 'euclidean') + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'invalid_value', TOP_N = 5)", + new ParserErrorInfo(93, "SQL46010", "'invalid_value'")); + + // Invalid value: TOP_N = '5' (should be integer, not string) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = '5')", + new ParserErrorInfo(108, "SQL46010", "'5'")); + + // Invalid value: TOP_N = -5 (should be positive integer) + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = -5)", + new ParserErrorInfo(108, "SQL46010", "-")); + + // Missing value after equals for TABLE + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = , COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(36, "SQL46010", ",")); + + // Missing value after equals for COLUMN + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = , SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(51, "SQL46010", ",")); + + // Missing value after equals for SIMILAR_TO + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = , METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(70, "SQL46010", ",")); + + // Missing value after equals for METRIC + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = , TOP_N = 5)", + new ParserErrorInfo(93, "SQL46010", ",")); + + // Missing value after equals for TOP_N + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = )", + new ParserErrorInfo(108, "SQL46010", ")")); + + // Extra parameter + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5, EXTRA_PARAM = 'value')", + new ParserErrorInfo(109, "SQL46010", ",")); + + // Extra comma at end + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5,)", + new ParserErrorInfo(109, "SQL46010", ",")); + + // Function call with constant input, not keyword params + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH('tbl1', 'col1', 'query_vector', 'dot', 5)", + new ParserErrorInfo(28, "SQL46010", "'tbl1'")); + } } } diff --git a/Test/SqlDom/TestScripts/AiGenerateChunksTests170.sql b/Test/SqlDom/TestScripts/AiGenerateChunksTests170.sql new file mode 100644 index 00000000..8374acc9 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiGenerateChunksTests170.sql @@ -0,0 +1,101 @@ +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = 50); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = NULL, ENABLE_CHUNK_SET_ID = 50); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = 10, ENABLE_CHUNK_SET_ID = 1); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = @SOURCE, CHUNK_TYPE = fixed, CHUNK_SIZE = @CHUNK_SIZE); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = @SOURCE, CHUNK_TYPE = fixed, CHUNK_SIZE = @CHUNK_SIZE, OVERLAP = @OVERLAP, ENABLE_CHUNK_SET_ID = @ENABLE_CHUNK_SET_ID); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = NULL, CHUNK_TYPE = fixed, CHUNK_SIZE = 5); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t1.c1, CHUNK_TYPE = fixed, CHUNK_SIZE = 10); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = t1.c1); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = t1.c1); + +SELECT * +FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = 5, ENABLE_CHUNK_SET_ID = t1.c1); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = NULL); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = NULL); + +SELECT * +FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = 5, ENABLE_CHUNK_SET_ID = NULL); + +CREATE TABLE t2 ( + Id INT IDENTITY PRIMARY KEY, + Text NVARCHAR (MAX) +); +GO + +INSERT INTO t2 (Text) +VALUES (N'This is the first text.'), +(N'Second sample text.'), +(N'Third example text.'); +GO + +CREATE VIEW v_GeneratedChunksFromTable +AS +SELECT t2.Id, + chunks.* +FROM t2 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t2.Text, CHUNK_TYPE = fixed, CHUNK_SIZE = 5) AS chunks; +GO + +CREATE PROCEDURE usp_GenerateChunks +AS +BEGIN + SELECT * + FROM AI_GENERATE_CHUNKS (SOURCE = N'This is some sample text that will be chunked.', CHUNK_TYPE = fixed, CHUNK_SIZE = 5, OVERLAP = 2); +END +GO + +CREATE FUNCTION dbo.AI_GENERATE_CHUNKS +(@input NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN CONCAT('Chunked: ', @input); +END +GO + +CREATE TABLE dbo.AI_GENERATE_CHUNKS ( + id INT PRIMARY KEY, + data NVARCHAR (MAX) +); + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS(target); + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS](SOURCE); + + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS([SOURCE]); + +SELECT SOURCE +FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS]([SOURCE]); + +SELECT * +FROM dbo.AI_GENERATE_CHUNKS(3); \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/AiGenerateEmbeddingsTests170.sql b/Test/SqlDom/TestScripts/AiGenerateEmbeddingsTests170.sql new file mode 100644 index 00000000..72493c7f --- /dev/null +++ b/Test/SqlDom/TestScripts/AiGenerateEmbeddingsTests170.sql @@ -0,0 +1,52 @@ +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyDefaultModel); +SELECT AI_GENERATE_EMBEDDINGS(N'My Default Input Text' USE MODEL MyDefaultModel); +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyDefaultModel PARAMETERS (TRY_CONVERT (JSON, N'{}'))); +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL dbo.MyDefaultModel); +SELECT AI_GENERATE_EMBEDDINGS('My Default Input Text' USE MODEL MyDatabase.dbo.MyDefaultModel); +GO + +CREATE FUNCTION dbo.AI_GENERATE_EMBEDDINGS +(@input NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN CONCAT('Embed: ', @input); +END +GO + +CREATE TABLE dbo.AI_GENERATE_EMBEDDINGS ( + id INT PRIMARY KEY, + data NVARCHAR (MAX) +); +GO + +CREATE VIEW dbo.ai_generate_embeddings +AS +SELECT 'View result' AS result; +GO + +CREATE FUNCTION dbo.MyEmbeddingFunction +( ) +RETURNS TABLE +AS +RETURN + SELECT AI_GENERATE_EMBEDDINGS('Function Input' USE MODEL MyDefaultModel) AS EmbeddingResult +GO + +CREATE VIEW dbo.MyEmbeddingView +AS +SELECT AI_GENERATE_EMBEDDINGS(N'View Input' USE MODEL dbo.MyDefaultModel) AS EmbeddingResult; +GO + +CREATE TABLE dbo.SimpleEmbeddingTable ( + InputText NVARCHAR (MAX), + Embedding AS CONVERT (NVARCHAR (MAX), AI_GENERATE_EMBEDDINGS(InputText USE MODEL MyDefaultModel)) +); +GO + +CREATE PROCEDURE dbo.GetEmbedding +@InputText NVARCHAR (MAX) +AS +BEGIN + SELECT CONVERT (NVARCHAR (MAX), AI_GENERATE_EMBEDDINGS(@InputText USE MODEL MyDefaultModel)) AS Embedding; +END diff --git a/Test/SqlDom/TestScripts/AlterExternalModelStatementTests170.sql b/Test/SqlDom/TestScripts/AlterExternalModelStatementTests170.sql new file mode 100644 index 00000000..e9b590c8 --- /dev/null +++ b/Test/SqlDom/TestScripts/AlterExternalModelStatementTests170.sql @@ -0,0 +1,27 @@ +ALTER EXTERNAL MODEL abc +SET ( +LOCATION = 'new_location', +API_FORMAT = 'Ollama', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'new_model', +PARAMETERS = '{"key":"new_value"}' +); +ALTER EXTERNAL MODEL abc +SET ( +MODEL = 'new_model' +); +ALTER EXTERNAL MODEL params_model +SET ( +PARAMETERS = '{"temperature":0.7, "max_tokens":2048}' +); +ALTER EXTERNAL MODEL ml_model +SET ( +API_FORMAT = 'OpenAI', +MODEL = 'gpt-3.5-turbo-16k', +PARAMETERS = '{"stream":true}' +); +ALTER EXTERNAL MODEL location_change +SET ( +LOCATION = '/new/model/path', +MODEL_TYPE = EMBEDDINGS +); \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/CreateExternalModelStatementTests170.sql b/Test/SqlDom/TestScripts/CreateExternalModelStatementTests170.sql new file mode 100644 index 00000000..88914762 --- /dev/null +++ b/Test/SqlDom/TestScripts/CreateExternalModelStatementTests170.sql @@ -0,0 +1,33 @@ +CREATE EXTERNAL MODEL abc + AUTHORIZATION dbo +WITH ( +LOCATION = 'sdfasfd', +API_FORMAT = 'Ollama', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'shghfh', +PARAMETERS = '{"key":"valuoipe"}' +); +CREATE EXTERNAL MODEL simple_model +WITH ( +LOCATION = '/models/simple', +API_FORMAT = 'OpenAI', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'gpt-3.5-turbo' +); +CREATE EXTERNAL MODEL advanced_model +WITH ( +LOCATION = 'https://models.example.com/advanced', +API_FORMAT = 'Azure OpenAI', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'bert-base-uncased', +PARAMETERS = '{"batch_size":32,"device":"cuda"}' +); +CREATE EXTERNAL MODEL [model_name] +WITH ( +LOCATION = 'FILE PATH', +API_FORMAT = 'onnx runtime', +MODEL_TYPE = EMBEDDINGS, +MODEL = 'text-embedding-ada-002,etc', +PARAMETERS = '{ "valid":"JSON"}', +LOCAL_RUNTIME_PATH = 'Path on local server to onnx runtime' +); \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/DropExternalModelStatementTests170.sql b/Test/SqlDom/TestScripts/DropExternalModelStatementTests170.sql new file mode 100644 index 00000000..127b413d --- /dev/null +++ b/Test/SqlDom/TestScripts/DropExternalModelStatementTests170.sql @@ -0,0 +1 @@ +DROP EXTERNAL MODEL my_model1; \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/JsonFunctionTests170.sql b/Test/SqlDom/TestScripts/JsonFunctionTests170.sql new file mode 100644 index 00000000..d15a477f --- /dev/null +++ b/Test/SqlDom/TestScripts/JsonFunctionTests170.sql @@ -0,0 +1,98 @@ +-- ISJSON +SELECT id, json_col +FROM tab1 +WHERE ISJSON(json_col) = 1 + +SELECT id, json_col +FROM tab1 +WHERE ISJSON(json_col, SCALAR) = 1 + +SELECT ISJSON('true', VALUE) + +-- JSON_PATH_EXISTS +DECLARE @jsonInfo NVARCHAR(MAX); +SET @jsonInfo=N'{"info":{"address":[{"town":"Paris"},{"town":"London"}]}}'; +SELECT JSON_PATH_EXISTS(@jsonInfo,'$.info.address'); + +SELECT JSON_OBJECT('name':'value'); + +SELECT JSON_OBJECT('name':'value', 'type':1 NULL ON NULL); + +SELECT JSON_OBJECT(NULL ON NULL); + +SELECT JSON_OBJECT('name':'value', 'type':NULL ABSENT ON NULL); + +SELECT JSON_OBJECT('name':'value', 'type':JSON_OBJECT('type_id':1, 'name':'a')); + +SELECT JSON_OBJECT(); + +SELECT JSON_OBJECT('name':'value', 'type':1); + +SELECT JSON_OBJECT('name':'value', 'type':JSON_ARRAY(1, 2)); + +DECLARE @id_key AS NVARCHAR (10) = N'id', @id_value AS NVARCHAR (64) = NEWID(); + +SELECT JSON_OBJECT('user_name':USER_NAME(), @id_key:@id_value, 'sid':(SELECT @@SPID)); + +SELECT s.session_id, + JSON_OBJECT('security_id':s.security_id, 'login':s.login_name, 'status':s.status) AS info +FROM sys.dm_exec_sessions AS s +WHERE s.is_user_process = 1; + +SELECT JSON_OBJECT('name':'b' RETURNING JSON); + +SELECT JSON_OBJECT('name':'b' NULL ON NULL RETURNING JSON); + +SELECT JSON_OBJECT('name':'b' ABSENT ON NULL RETURNING JSON); + +SELECT JSON_ARRAY('a', JSON_OBJECT('name':'value', 'type':1 NULL ON NULL) NULL ON NULL); + +SELECT JSON_ARRAY(); + +SELECT JSON_ARRAY('name'); + +SELECT JSON_ARRAY('a', 1, 'b', 2); + +SELECT JSON_ARRAY('a', 1, NULL, 2 NULL ON NULL); + +SELECT JSON_ARRAY('a', 1, NULL, 2 ABSENT ON NULL); + +SELECT JSON_ARRAY(NULL ON NULL); + +SELECT JSON_ARRAY(ABSENT ON NULL); + +DECLARE @id_value AS NVARCHAR (64) = NEWID(); + +SELECT JSON_ARRAY(1, @id_value, (SELECT @@SPID)); + +SELECT s.session_id, + JSON_ARRAY(s.host_name, s.program_name, s.client_interface_name) +FROM sys.dm_exec_sessions AS s +WHERE s.is_user_process = 1; + +SELECT JSON_ARRAY('a', 1, NULL, 2 RETURNING JSON); + +SELECT JSON_ARRAY('a', 1, NULL, 2 NULL ON NULL RETURNING JSON); + +SELECT JSON_ARRAY('a', 1, NULL, 2 ABSENT ON NULL RETURNING JSON); + +SELECT JSON_OBJECTAGG('name':'value'); + +SELECT JSON_OBJECTAGG('name':'value' NULL ON NULL); + +SELECT JSON_OBJECTAGG(NULL ON NULL); + +SELECT JSON_OBJECTAGG('name':NULL ABSENT ON NULL); + +SELECT JSON_OBJECTAGG('name':JSON_OBJECT('type_id':1, 'name':'a')); + +SELECT JSON_OBJECTAGG(); + +SELECT JSON_OBJECTAGG('name':1); + +SELECT JSON_OBJECTAGG('name':JSON_ARRAY(1, 2)); +SELECT JSON_OBJECTAGG('name':'b' NULL ON NULL RETURNING JSON); + +SELECT JSON_OBJECTAGG('name':'b' ABSENT ON NULL RETURNING JSON); + +SELECT JSON_OBJECTAGG('name':'b' RETURNING JSON); diff --git a/Test/SqlDom/TestScripts/RegexpTests170.sql b/Test/SqlDom/TestScripts/RegexpTests170.sql new file mode 100644 index 00000000..160857a5 --- /dev/null +++ b/Test/SqlDom/TestScripts/RegexpTests170.sql @@ -0,0 +1,26 @@ +-- REGEXP_COUNT(text, pattern [, start [, flags ]]) +SELECT REGEXP_COUNT('hello', 'he(l+)o'); +SELECT REGEXP_COUNT('hello', 'he(l+)o', 1); +SELECT REGEXP_COUNT('hello', 'he(l+)o', 1, 'i'); + +-- REGEXP_INSTR(text, pattern [, start [, occurrence [, return_option [, flags [, group ]]]]]) +SELECT REGEXP_INSTR('hello', 'he(l+)o'); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1, 0); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1, 0, 'i'); +SELECT REGEXP_INSTR('hello', 'he(l+)o', 1, 1, 0, 'c', 1); + +-- REGEXP_REPLACE(text, pattern [, replacement [, start [, occurrence [, flags ]]]]) +SELECT REGEXP_REPLACE('hello', 'he(l+)o'); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o'); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o', 1); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o', 1, 1); +SELECT REGEXP_REPLACE('hello', 'he(l+)o', 'hi\1o', 1, 1, 'm'); + +-- REGEXP_SUBSTR(text, pattern [, start [, occurrence [, flags [, group ]]]]) +SELECT REGEXP_SUBSTR('hello', 'he(l+)o'); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1, 1); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1, 1, 's'); +SELECT REGEXP_SUBSTR('hello', 'he(l+)o', 1, 1, 'c', 1); \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/SecurityStatementExternalModelTests170.sql b/Test/SqlDom/TestScripts/SecurityStatementExternalModelTests170.sql new file mode 100644 index 00000000..04442d64 --- /dev/null +++ b/Test/SqlDom/TestScripts/SecurityStatementExternalModelTests170.sql @@ -0,0 +1,47 @@ +GRANT ALTER ANY EXTERNAL MODEL TO datascientist; +GRANT ALTER ANY EXTERNAL MODEL TO PUBLIC + WITH GRANT OPTION; +GRANT ALTER ANY EXTERNAL MODEL TO mlrole, adminrole + AS dbo; +GRANT EXECUTE + ON EXTERNAL MODEL::MyPredictionModel TO analyst; +GRANT EXECUTE + ON EXTERNAL MODEL::schema1.ModelName TO user1, user2 + WITH GRANT OPTION; +GRANT CONTROL + ON EXTERNAL MODEL::dbo.SalesModel TO mladmin + AS dbo; +GRANT VIEW DEFINITION + ON EXTERNAL MODEL::MySchema.MyModel TO PUBLIC; +DENY ALTER ANY EXTERNAL MODEL TO restricteduser; +DENY EXECUTE + ON EXTERNAL MODEL::TestModel TO guest + CASCADE; +DENY CONTROL + ON EXTERNAL MODEL::test.model1 TO user1, user2 + CASCADE + AS admin; +REVOKE ALTER ANY EXTERNAL MODEL FROM olduser; +REVOKE GRANT OPTION FOR EXECUTE + ON EXTERNAL MODEL::MyModel FROM tempuser + CASCADE; +REVOKE CONTROL + ON EXTERNAL MODEL::prod.RecommendationModel FROM contractor + AS manager; +REVOKE EXECUTE + ON EXTERNAL MODEL::dbo.CustomerModel FROM PUBLIC + CASCADE; +ALTER AUTHORIZATION ON EXTERNAL MODEL::MyModel TO newowner; +ALTER AUTHORIZATION ON EXTERNAL MODEL::schema1.ModelName TO SCHEMA OWNER; +ALTER AUTHORIZATION ON EXTERNAL MODEL::test.experimentalmodel TO datateam; +GRANT EXECUTE, VIEW DEFINITION + ON EXTERNAL MODEL::MultiPermModel TO analyst; +DENY EXECUTE, CONTROL + ON EXTERNAL MODEL::RestrictedModel TO guest; +REVOKE EXECUTE, VIEW DEFINITION + ON EXTERNAL MODEL::OldModel FROM formeranalyst; +GRANT EXECUTE + ON EXTERNAL MODEL::MyDatabase.MySchema.ModelWithSpaces TO testuser; +DENY ALTER ANY EXTERNAL MODEL TO userwithspaces; +REVOKE CONTROL + ON EXTERNAL MODEL::QuotedModel FROM QuotedUser; \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/VectorFunctionTests170.sql b/Test/SqlDom/TestScripts/VectorFunctionTests170.sql new file mode 100644 index 00000000..1d1c6799 --- /dev/null +++ b/Test/SqlDom/TestScripts/VectorFunctionTests170.sql @@ -0,0 +1,25 @@ +DECLARE @qv VECTOR(1536) = AI_GENERATE_EMBEDDINGS(N'Pink Floyd music style' USE MODEL Ada2Embeddings); + +SELECT + t.id, s.distance, t.title +FROM + VECTOR_SEARCH( + TABLE = [dbo].[wikipedia_articles_embeddings] as t, + COLUMN = [content_vector], + SIMILAR_TO = @qv, + METRIC = 'cosine', + TOP_N = 10 + ) AS s +ORDER BY s.distance + +SELECT + * +FROM + VECTOR_SEARCH( + TABLE = wikipedia_articles_embeddings, + COLUMN = dbo.wikipedia_articles_embeddings.content_vector, + SIMILAR_TO = @qv, + METRIC = 'dot', + TOP_N = 10 + ) +ORDER BY distance \ No newline at end of file diff --git a/global.json b/global.json index 457d429d..b812260e 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.117", + "version": "8.0.413", "rollForward": "latestMajor" }, "msbuild-sdks": { diff --git a/release-notes/170/170.82.0.md b/release-notes/170/170.82.0.md new file mode 100644 index 00000000..59e01121 --- /dev/null +++ b/release-notes/170/170.82.0.md @@ -0,0 +1,27 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 170.82.0 +This update brings the below changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates.NET SDK to latest patch version 8.0.413 + +#### .NET Framework +#### .NET Core + +### New Features +* Adds support for `AI_GENERATE_CHUNKS`, `JSON_OBJECTAGG`, `AI_GENERATE_EMBEDDINGS` and `VECTOR_SEARCH` Functions. +* Adds supports for `EXTERNAL MODEL` object type. + +### Fixed + +### Changes +* Updated Fabric DW syntax to better match the definition for identity columns. + +### Known Issues From 4ba3382f783a10f43d173e517c7353020ebeab32 Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Wed, 3 Sep 2025 13:17:02 -0700 Subject: [PATCH 07/45] Sync Repos: Release 170.82.0 (#154) * Merged PR 1756293: [MSJSON] json_arrayagg support for scriptdom ## Description This pull request introduces full support for the JSON_ARRAYAGG function in ScriptDom by extending the T-SQL grammar and code generation, along with updated test cases to validate the new functionality. Json_ArrayAgg with options NULL ON NULL/ABSENT ON NULL and RETURNING JSON are supported. * Merged PR 1777076: Adding missing event CREATE_JSON_INDEX # Pull Request Template for ScriptDom ## Description Adding missing JSON index event to the event type enum. Adding missing event CREATE_JSON_INDEX * Merged PR 1781082: Adding regexp_like syntax Regexp_like function works as a boolean expression similar to LIKE, MATCH starting from compat level 170. Adding regexp_like syntax Related work items: #4005966 * Merged PR 1762947: Nested CTE Implementation - Fabric DW In this PR we modify the Fabric DW Grammar to support Nested Common Table Expressions with the following syntax: ``` WITH [ (column_name , ...) ] AS (WITH [ (column_name , ...) ] AS ( ... WITH [ ( column_name , ...) ] AS ( WITH [ ( column_name , ...) ] AS ( Standard_CTE_query_definition ) -- Data source must include NESTED_CTE_NAME_LEVELn-1 ... ) )` - `ai_classify(, , [, , ...])` - `ai_extract(, [, , ...])` - `ai_fix_grammar()` - `ai_generate_response([, ])` - `ai_summarize()` - `ai_translate(, )` Detailed design document is here: https://microsoft.sharepoint.com/:w:/r/teams/AzurePolaris/_layouts/15/doc2.aspx?sourcedoc=%7B75BAC667-A870-4482-8A37-F80E6EC8FCE0%7D&file=AI%20and%20Extensibiliy.docx Before submitting your pull request, please ensure you have completed the following: - [x] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [x] Code changes are accompanied by appropriate unit tests - [x] Identified and included SMEs needed to review code changes - [X] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code - [x] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ---- New feature: Adding support for Fabric DW–specific AI built-in functions. This pull request extends the SQL parser for Fabric DW by introducing new AI functions and their corresponding AST representations, script generators, and tests. Key changes include: - **`TSqlFabricDW.g`**: Added grammar rules for AI functions (e.g., AI_ANALYZE_SENTIMENT, AI_CLASSIFY, AI_EXTRACT, AI_GENERATE_RESPONSE, AI_SUMMARIZE, AI_TRANSLATE). - **`Ast.xml`**: Introduced new AST classes to represent the AI function calls. - **Script Generator Files**: Created new files in `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/` to define visitors for the AI functions. - **`CodeGenerationSupporter.cs`**: Added new constants to support the AI function tokens. - **Test Files**: Included multiple test scripts and negative tests under `/Test/SqlDom/` to validate the syntax and error handling for the newly added functions. Related work items: #4924682 * Merged PR 1921976: Fixing IIF parsing when it occurs inside a parenthesis. # Pull Request Template for ScriptDom ## Description Fixes: https://github.com/microsoft/SqlScriptDOM/issues/28 The TSql160Parser.ParseExpression() was failing to parse valid T-SQL expressions where IIF with boolean operators was wrapped in parentheses: ```sql SELECT 1 WHERE (IIF(1 > 0 AND 2 > 1, 1, 0)) = 1 ``` Customers reported this issue when using IIF expressions with multiple boolean operators (AND, OR, >, <, etc.) wrapped in parentheses. The original code used a simple counter (insideIIf) to track when inside an IIF call. The counter was decremented on the first boolean operator inside the IIF (e.g., >). When a second operator like AND was encountered, insideIIf was already 0, causing it to be misidentified as a top-level boolean operator - which incorrectly signaled that the outer parentheses contained a boolean expression instead of a scalar expression. Replaced the simple counter with stack-based parenthesis depth tracking. This properly tracks when we're inside an IIF by remembering the parenthesis depth where each IIF started, rather than incorrectly decrementing on boolean operators. This also correctly handles: Nested IIF expressions: `(IIF(IIF(a > 1, b, c) > 2, 1, 0))` Deeply nested parentheses: `((((IIF(1 > 0 AND 2 > 1, 1, 0)))) = 1` Multiple IIF expressions: `(IIF(...)) = 1 AND (IIF(...)) = 1` ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [ ] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers ---- #### AI description (iteration 1) #### PR Classification Bug fix to correct the parsing of IIF expressions when they occur inside parentheses. #### PR Summary This pull request fixes the incorrect handling of nested IIF expressions by replacing a simple counter with a stack-based approach and a pending flag, ensuring accurate tracking of IIF parentheses. The update enhances the SQL parser and adds regression tests to validate various scenarios. - `SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs`: Refactor... * Merged PR 1932484: Adding release notes for 170.157.0 # Pull Request Template for ScriptDom ## Description Adding release notes for 170.157.0 Before submitting your pull request, please ensure you have completed the following: ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [ ] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers Adding release notes for 170.157.0 ---- #### AI description (iteration 1) #### PR Classification Documentation update providing the release notes for version 170.157.0. #### PR Summary This pull request adds a new release notes file for Microsoft.SqlServer.TransactSql.ScriptDom 170.157.0, detailing supported platforms, dependency updates, new AI function support, and fixes for specific issues. - `release-notes/170/170.157.0.md`: New file containing the release information including target platform support, updated .NET SDK dependency (8.0.415), addition of Fabric DW-specific AI functions, and fixes for issues #161 and #28. --------- Co-authored-by: Maksim Vlasov Co-authored-by: Aasim Khan --- .../bug_fixing.guidelines.instructions.md | 21 ++ .../grammer.guidelines.instructions.md | 33 +- .../parser.guidelines.instructions.md | 16 +- .../testing.guidelines.instructions.md | 107 ++++++ SqlScriptDom/Parser/TSql/Ast.xml | 32 ++ .../Parser/TSql/CodeGenerationSupporter.cs | 7 + SqlScriptDom/Parser/TSql/TSql170.g | 14 +- .../Parser/TSql/TSql170ParserBaseInternal.cs | 39 +++ .../Parser/TSql/TSql80ParserBaseInternal.cs | 39 ++- SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 197 +++++++++++ ...ratorVisitor.AiAnalyzeSentimentFunction.cs | 25 ++ ...riptGeneratorVisitor.AiClassifyFunction.cs | 41 +++ ...criptGeneratorVisitor.AiExtractFunction.cs | 42 +++ ...ptGeneratorVisitor.AiFixGrammarFunction.cs | 25 ++ ...ratorVisitor.AiGenerateResponseFunction.cs | 36 ++ ...iptGeneratorVisitor.AiSummarizeFunction.cs | 26 ++ ...iptGeneratorVisitor.AiTranslateFunction.cs | 31 ++ .../Baselines160/IifParenthesesTests160.sql | 97 ++++++ .../Baselines170/ComplexQueryTests170.sql | 69 ++++ .../AiAnalyzeSentimentTestsFabricDW.sql | 27 ++ .../AiClassifyTestsFabricDW.sql | 26 ++ .../AiExtractTestsFabricDW.sql | 26 ++ .../AiFixGrammarTestsFabricDW.sql | 27 ++ .../AiGenerateResponseTestsFabricDW.sql | 25 ++ .../AiSummarizeTestsFabricDW.sql | 27 ++ .../AiTranslateTestsFabricDW.sql | 33 ++ Test/SqlDom/Only160SyntaxTests.cs | 1 + Test/SqlDom/Only170SyntaxTests.cs | 4 +- Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 7 + Test/SqlDom/ParserErrorsTests.cs | 311 +++++++++++++----- .../AiAnalyzeSentimentTestsFabricDW.sql | 27 ++ .../TestScripts/AiClassifyTestsFabricDW.sql | 23 ++ .../TestScripts/AiExtractTestsFabricDW.sql | 23 ++ .../TestScripts/AiFixGrammarTestsFabricDW.sql | 27 ++ .../AiGenerateResponseTestsFabricDW.sql | 19 ++ .../TestScripts/AiSummarizeTestsFabricDW.sql | 27 ++ .../TestScripts/AiTranslateTestsFabricDW.sql | 26 ++ .../TestScripts/ComplexQueryTests170.sql | 72 ++++ .../TestScripts/IifParenthesesTests160.sql | 75 +++++ release-notes/170/170.157.0.md | 26 ++ 40 files changed, 1651 insertions(+), 105 deletions(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs create mode 100644 Test/SqlDom/Baselines160/IifParenthesesTests160.sql create mode 100644 Test/SqlDom/Baselines170/ComplexQueryTests170.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/ComplexQueryTests170.sql create mode 100644 Test/SqlDom/TestScripts/IifParenthesesTests160.sql create mode 100644 release-notes/170/170.157.0.md diff --git a/.github/instructions/bug_fixing.guidelines.instructions.md b/.github/instructions/bug_fixing.guidelines.instructions.md index 79715fab..b1a67931 100644 --- a/.github/instructions/bug_fixing.guidelines.instructions.md +++ b/.github/instructions/bug_fixing.guidelines.instructions.md @@ -90,6 +90,27 @@ The process of fixing a bug, especially one that involves adding new syntax, fol By following these steps, you can ensure that new syntax is correctly parsed, represented in the AST, generated back into a script, and fully validated by the testing framework without breaking existing functionality. +## Testing Best Practices + +### ✅ DO: Use Existing Test Framework +- Add test methods to existing test classes like `Only170SyntaxTests.cs` +- Use the established `TSqlParser.Parse()` pattern for verification +- Example: + ```csharp + [TestMethod] + public void VerifyNewSyntax() + { + var parser = new TSql170Parser(true); + var result = parser.Parse(new StringReader("YOUR SQL HERE"), out var errors); + Assert.AreEqual(0, errors.Count, "Should parse without errors"); + } + ``` + +### ❌ DON'T: Create New Test Projects +- **Never** create standalone `.csproj` files for testing parser functionality +- **Never** create new console applications or test runners +- This causes build issues and doesn't integrate with the existing test infrastructure + ## Special Case: Extending Grammar Rules from Literals to Expressions A common type of bug involves extending existing grammar rules that only accept literal values (like integers or strings) to accept full expressions (parameters, variables, outer references, etc.). This pattern was used to fix the VECTOR_SEARCH TOP_N parameter issue. diff --git a/.github/instructions/grammer.guidelines.instructions.md b/.github/instructions/grammer.guidelines.instructions.md index 900026f8..53311f7d 100644 --- a/.github/instructions/grammer.guidelines.instructions.md +++ b/.github/instructions/grammer.guidelines.instructions.md @@ -64,17 +64,32 @@ yourContextParameterRule returns [ScalarExpression vResult] Most script generators using `GenerateNameEqualsValue()` or similar methods work automatically with `ScalarExpression`. No changes typically needed. #### Step 4: Add Test Coverage -```sql --- Test parameter -FUNCTION_NAME(PARAM = @parameter) - --- Test outer reference -FUNCTION_NAME(PARAM = outerref.column) - --- Test computed expression -FUNCTION_NAME(PARAM = value + 1) +Add tests within the existing test framework: +```csharp +[TestMethod] +public void VerifyGrammarExtension() +{ + var parser = new TSql170Parser(true); + + // Test parameter + var sql1 = "SELECT FUNCTION_NAME(PARAM = @parameter)"; + var result1 = parser.Parse(new StringReader(sql1), out var errors1); + Assert.AreEqual(0, errors1.Count, "Parameter syntax should work"); + + // Test outer reference + var sql2 = "SELECT FUNCTION_NAME(PARAM = outerref.column)"; + var result2 = parser.Parse(new StringReader(sql2), out var errors2); + Assert.AreEqual(0, errors2.Count, "Outer reference syntax should work"); + + // Test computed expression + var sql3 = "SELECT FUNCTION_NAME(PARAM = value + 1)"; + var result3 = parser.Parse(new StringReader(sql3), out var errors3); + Assert.AreEqual(0, errors3.Count, "Computed expression syntax should work"); +} ``` +**⚠️ CRITICAL**: Add this test method to an existing test class (e.g., `Only170SyntaxTests.cs`). **Never create standalone test projects.** + ### Real-World Example: VECTOR_SEARCH TOP_N **Problem**: `VECTOR_SEARCH` TOP_N parameter only accepted integer literals. diff --git a/.github/instructions/parser.guidelines.instructions.md b/.github/instructions/parser.guidelines.instructions.md index acd96d6f..20da2e63 100644 --- a/.github/instructions/parser.guidelines.instructions.md +++ b/.github/instructions/parser.guidelines.instructions.md @@ -59,11 +59,21 @@ case TSql80ParserInternal.Identifier: ## Step-by-Step Fix Process ### 1. Reproduce the Issue -Create a test case to confirm the bug: -```sql -SELECT 1 WHERE (REGEXP_LIKE('a', 'pattern')); -- Should fail without fix +Create a test case within the existing test framework to confirm the bug: +```csharp +[TestMethod] +public void ReproduceParenthesesIssue() +{ + var parser = new TSql170Parser(true); + var sql = "SELECT 1 WHERE (REGEXP_LIKE('a', 'pattern'));"; + var result = parser.Parse(new StringReader(sql), out var errors); + // Should fail before fix, pass after fix + Assert.AreEqual(0, errors.Count, "Should parse without errors after fix"); +} ``` +**⚠️ IMPORTANT**: Add this test to an existing test class like `Only170SyntaxTests.cs`, **do not** create a new test project. + ### 2. Identify the Predicate Constant Find the predicate identifier in `CodeGenerationSupporter`: ```csharp diff --git a/.github/instructions/testing.guidelines.instructions.md b/.github/instructions/testing.guidelines.instructions.md index 1cd17054..ec628119 100644 --- a/.github/instructions/testing.guidelines.instructions.md +++ b/.github/instructions/testing.guidelines.instructions.md @@ -13,6 +13,43 @@ The SqlScriptDOM testing framework validates parser functionality through: 4. **Version-Specific Testing** - Tests syntax across multiple SQL Server versions (SQL 2000-2025) 5. **Exact T-SQL Verification** - When testing specific T-SQL syntax from prompts or user requests, the **exact T-SQL statement must be included and verified** in the test to ensure the specific syntax works as expected +## Quick Verification Tests + +For rapid verification and debugging, add simple test methods directly to existing test classes: + +```csharp +[TestMethod] +[Priority(0)] +[SqlStudioTestCategory(Category.UnitTest)] +public void VerifyMyNewSyntax() +{ + var parser = new TSql170Parser(true); + + // Test basic syntax + var query1 = "SELECT YOUR_NEW_FUNCTION('param1', 'param2');"; + var result1 = parser.Parse(new StringReader(query1), out var errors1); + Assert.AreEqual(0, errors1.Count, "Basic syntax should parse"); + + // Test complex variations + var query2 = "SELECT YOUR_NEW_FUNCTION(@variable);"; + var result2 = parser.Parse(new StringReader(query2), out var errors2); + Assert.AreEqual(0, errors2.Count, "Variable syntax should parse"); + + Console.WriteLine("✅ All tests passed!"); +} +``` + +**Where to Add Quick Tests:** +- **SQL Server 2025 (170) features**: Add to `Test/SqlDom/Only170SyntaxTests.cs` +- **SQL Server 2022 (160) features**: Add to `Test/SqlDom/Only160SyntaxTests.cs` +- **Earlier versions**: Add to corresponding `OnlySyntaxTests.cs` + +**When to Use:** +- Quick verification during development +- Debugging parser issues +- Initial syntax validation before full test suite +- Rapid prototyping of test cases + ## Test Framework Architecture ### Core Components @@ -29,6 +66,30 @@ The SqlScriptDOM testing framework validates parser functionality through: 3. **Validate Phase**: Generated output is compared against baseline file 4. **Error Validation**: Parse error count is compared against expected error count for each SQL version +## ❌ Anti-Patterns: What NOT to Do + +### Do NOT Create New Test Projects + +- ❌ **Don't create new `.csproj` files for testing** +- ❌ **Don't create console applications** like `TestVectorParser.csproj` or `debug_complex.csproj` +- ❌ **Don't create standalone test runners** +- ❌ **Don't add new projects to the solution for testing** + +### Why This Causes Problems + +1. **Build Issues**: New projects often fail to build due to missing dependencies +2. **Integration Problems**: Standalone projects don't integrate with existing test infrastructure +3. **Maintenance Overhead**: Additional projects require separate maintenance and documentation +4. **CI/CD Conflicts**: Build pipelines aren't configured for ad-hoc test projects +5. **Resource Waste**: Creates duplicate testing infrastructure instead of using established patterns + +### The Correct Approach + +✅ **Always add test methods to existing test classes**: +- Add to `Test/SqlDom/Only170SyntaxTests.cs` for SQL Server 2025 features +- Add to `Test/SqlDom/Only160SyntaxTests.cs` for SQL Server 2022 features +- Use the established test framework patterns documented in this guide + ## Adding New Tests ### 1. Create Test Script @@ -639,6 +700,52 @@ new ParserTest170("ErrorConditionTests170.sql", nErrors160: 3, nErrors170: 3), ``` +## Real-World Example: VECTOR Parsing Verification + +This example shows the correct approach used to verify VECTOR data type parsing functionality: + +```csharp +[TestMethod] +[Priority(0)] +[SqlStudioTestCategory(Category.UnitTest)] +public void VerifyComplexQueryFix() +{ + // Test VECTOR parsing in various contexts - this is the real bug we found and fixed + var parser = new TSql170Parser(true); + + // Test 1: Basic VECTOR with base type + var query1 = "SELECT CAST('[1,2,3]' AS VECTOR(3, Float32));"; + var result1 = parser.Parse(new StringReader(query1), out var errors1); + Assert.AreEqual(0, errors1.Count, "Basic VECTOR with base type should parse"); + + // Test 2: VECTOR in complex CAST (from original failing query) + var query2 = "SELECT CAST('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3, Float32));"; + var result2 = parser.Parse(new StringReader(query2), out var errors2); + Assert.AreEqual(0, errors2.Count, "VECTOR with scientific notation should parse"); + + // Test 3: VECTOR in CONVERT (from original failing query) + var query3 = "SELECT CONVERT(VECTOR(77), '[-7.230808E+08,4.075427E+08]');"; + var result3 = parser.Parse(new StringReader(query3), out var errors3); + Assert.AreEqual(0, errors3.Count, "VECTOR in CONVERT should parse"); + + // Test 4: VECTOR in JOIN context (simplified version of original complex query) + var query4 = @"SELECT t1.id + FROM table1 t1 + INNER JOIN table2 t2 ON t1.vector_col = CAST('[1,2,3]' AS VECTOR(3, Float32));"; + var result4 = parser.Parse(new StringReader(query4), out var errors4); + Assert.AreEqual(0, errors4.Count, "VECTOR in JOIN condition should parse"); + + Console.WriteLine("✅ All VECTOR parsing tests passed - the original VECTOR bug is fixed!"); +} +``` + +**Key Points from This Example:** +1. Test was added directly to `Only170SyntaxTests.cs` - no new project created +2. Tests multiple contexts where the syntax appears (CAST, CONVERT, JOIN) +3. Uses inline assertions with descriptive messages +4. References the original bug being fixed +5. Provides immediate feedback via Console.WriteLine + ## Advanced Testing Patterns ### Multi-File Tests diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index 4e0e1823..d17d34eb 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -4769,6 +4769,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 6d285f50..4f7e5be1 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -101,6 +101,13 @@ internal static class CodeGenerationSupporter internal const string Aggregate = "AGGREGATE"; internal const string AiGenerateChunks = "AI_GENERATE_CHUNKS"; internal const string AIGenerateEmbeddings = "AI_GENERATE_EMBEDDINGS"; + internal const string AIAnalyzeSentiment = "AI_ANALYZE_SENTIMENT"; + internal const string AIClassify = "AI_CLASSIFY"; + internal const string AIExtract = "AI_EXTRACT"; + internal const string AIFixGrammar = "AI_FIX_GRAMMAR"; + internal const string AIGenerateResponse = "AI_GENERATE_RESPONSE"; + internal const string AISummarize = "AI_SUMMARIZE"; + internal const string AITranslate = "AI_TRANSLATE"; internal const string Algorithm = "ALGORITHM"; internal const string AlterColumn = "ALTERCOLUMN"; internal const string All = "ALL"; diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 27f3f613..b793bf56 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -19142,9 +19142,21 @@ joinElement[SubDmlFlags subDmlFlags, ref TableReference vResult] ; selectTableReferenceElement [SubDmlFlags subDmlFlags] returns [TableReference vResult = null] +{ + IToken tAfterJoinParenthesis = null; +} : + // Apply SaveGuessing optimization ONLY when VECTOR keyword is detected in lookahead + // This fixes VECTOR parsing in deeply nested JOINs without breaking other valid SQL patterns + {ContainsVectorInLookahead()}? + ({ if (!SkipGuessing(tAfterJoinParenthesis)) }: + (joinParenthesis[subDmlFlags])=> ({ SaveGuessing(out tAfterJoinParenthesis); }:))=> + ({ if (!SkipGuessing(tAfterJoinParenthesis)) }: + vResult=joinParenthesis[subDmlFlags]) + | + // Standard syntactic predicate for all other cases (joinParenthesis[subDmlFlags])=> - vResult=joinParenthesis[subDmlFlags] + vResult=joinParenthesis[subDmlFlags] | vResult=selectTableReferenceElementWithoutJoinParenthesis[subDmlFlags] ; diff --git a/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs index 2ca8412a..9b5146b3 100644 --- a/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs @@ -70,5 +70,44 @@ protected SecurityObjectKind ParseSecurityObjectKindTSql170(Identifier identifie return TSql160ParserBaseInternal.ParseSecurityObjectKind(identifier1, identifier2); } } + + /// + /// Checks if VECTOR keyword appears in the upcoming tokens within a reasonable lookahead window. + /// Used to determine if SaveGuessing optimization is needed for VECTOR data type parsing. + /// + /// true if VECTOR keyword found in lookahead; false otherwise + protected bool ContainsVectorInLookahead() + { + // Scan ahead looking for VECTOR keyword (case-insensitive identifier match) + + const int LookaheadLimit = 100; // Define a named constant for the lookahead limit + // We scan up to LookaheadLimit tokens to handle deeply nested JOIN structures with VECTOR types + for (int i = 1; i <= LookaheadLimit; i++) + { + IToken token; + try + { + token = LT(i); + } + catch (Exception ex) + { + Debug.WriteLine($"Error accessing token at lookahead index {i}: {ex.Message}"); + break; + } + if (token == null || token.Type == Token.EOF_TYPE) + { + break; + } + + // Check if this is an identifier token with text "VECTOR" + if (token.Type == TSql170ParserInternal.Identifier && + string.Equals(token.getText(), CodeGenerationSupporter.Vector, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } } } diff --git a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs index 87201d05..a17fe591 100644 --- a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs @@ -796,22 +796,35 @@ protected bool IsNextRuleBooleanParenthesis() int caseDepth = 0; // 0 means there was no select int topmostSelect = 0; - int insideIIf = 0; + // Stack to track paren levels where IIF calls started + // This allows proper handling of multiple boolean operators inside IIF + Stack iifParenLevels = new Stack(); + bool pendingIIf = false; for (bool loop = true; loop == true; consume()) { + // Check if the previous token was IIF and this token is its opening parenthesis + // This must be done before resetting pendingIIf, as we need to consume the flag + bool isIIfOpeningParen = pendingIIf && LA(1) == TSql80ParserInternal.LeftParenthesis; + + // Reset pendingIIf at start of each iteration - it will only be set to true + // if this token is the IIF identifier. This ensures IIF must be immediately + // followed by ( to be recognized as a function call. + pendingIIf = false; + switch (LA(1)) { case TSql80ParserInternal.Identifier: // if identifier is IIF if(NextTokenMatches(CodeGenerationSupporter.IIf)) { - ++insideIIf; + // Mark that we're expecting IIF's opening parenthesis next + pendingIIf = true; } // if identifier is REGEXP_LIKE else if(NextTokenMatches(CodeGenerationSupporter.RegexpLike)) { - if (caseDepth == 0 && topmostSelect == 0 && insideIIf == 0) + if (caseDepth == 0 && topmostSelect == 0 && iifParenLevels.Count == 0) { matches = true; loop = false; @@ -820,6 +833,11 @@ protected bool IsNextRuleBooleanParenthesis() break; case TSql80ParserInternal.LeftParenthesis: ++openParens; + if (isIIfOpeningParen) + { + // Record the paren level where IIF started + iifParenLevels.Push(openParens); + } break; case TSql80ParserInternal.RightParenthesis: if (openParens == topmostSelect) @@ -827,6 +845,12 @@ protected bool IsNextRuleBooleanParenthesis() topmostSelect = 0; } + // Check if we're closing an IIF's parenthesis + if (iifParenLevels.Count > 0 && iifParenLevels.Peek() == openParens) + { + iifParenLevels.Pop(); + } + --openParens; if (openParens == 0) { @@ -856,18 +880,13 @@ protected bool IsNextRuleBooleanParenthesis() case TSql80ParserInternal.Exists: case TSql80ParserInternal.TSEqual: case TSql80ParserInternal.Update: - if (caseDepth == 0 && topmostSelect == 0 && insideIIf == 0) + if (caseDepth == 0 && topmostSelect == 0 && iifParenLevels.Count == 0) { // The number of open paranthesis are not important. - // Unless inside an iff + // Unless inside an IIF (tracked by paren level stack) matches = true; loop = false; } - else if (insideIIf > 0) - { - // Found the operator inside IIF - --insideIIf; - } break; case TSql80ParserInternal.Case: ++caseDepth; diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index 8eb4d054..77019ed7 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -31629,6 +31629,27 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.JsonArray) && (LA(2) == LeftParenthesis)}? vResult=jsonArrayCall + | + {NextTokenMatches(CodeGenerationSupporter.AIAnalyzeSentiment) && (LA(2) == LeftParenthesis)}? + vResult=aiAnalyzeSentimentFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.AIClassify) && (LA(2) == LeftParenthesis)}? + vResult=aiClassifyFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.AIExtract) && (LA(2) == LeftParenthesis)}? + vResult=aiExtractFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.AIFixGrammar) && (LA(2) == LeftParenthesis)}? + vResult=aiFixGrammarFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.AIGenerateResponse) && (LA(2) == LeftParenthesis)}? + vResult=aiGenerateResponseFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.AISummarize) && (LA(2) == LeftParenthesis)}? + vResult=aiSummarizeFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.AITranslate) && (LA(2) == LeftParenthesis)}? + vResult=aiTranslateFunctionCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -32267,6 +32288,182 @@ withinGroupClause returns [WithinGroupClause vResult = FragmentFactory.CreateFra } ; +// AI_ANALYZE_SENTIMENT() +aiAnalyzeSentimentFunctionCall returns [AIAnalyzeSentimentFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vInput; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AIAnalyzeSentiment); + UpdateTokenInfo(vResult, tFunc); + } + vInput = expression + { + vResult.Input = vInput; + } + RightParenthesis + ; + +// AI_CLASSIFY(, [, ... up to 21]) +// Input and labels accept any expression; type constraints are deferred to semantic/type phase. +aiClassifyFunctionCall returns [AIClassifyFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vExpr; + int labelsCount = 0; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AIClassify); + UpdateTokenInfo(vResult, tFunc); + } + // input: any expression + vExpr = expression + { + vResult.Input = vExpr; + } + // first label (required) + Comma vExpr = expression + { + AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); + labelsCount = 1; + } + // additional labels up to 21 total + ( + Comma vExpr = expression + { + ++labelsCount; + if (labelsCount > 21) + {ThrowParseErrorException("SQL46010", vExpr, TSqlParserResource.SQL46010Message, CodeGenerationSupporter.AIClassify); + } + AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } + ; + +// AI_EXTRACT(, [, ... up to 21]) +// Input and labels accept any expression; type constraints are deferred to semantic/type phase. +aiExtractFunctionCall returns [AIExtractFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vExpr; + int labelsCount = 0; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AIExtract); + UpdateTokenInfo(vResult, tFunc); + } + // input: any expression + vExpr = expression + { + vResult.Input = vExpr; + } + // first label (required) + Comma vExpr = expression + { + AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); + labelsCount = 1; + } + // additional labels up to 21 total + ( + Comma vExpr = expression + { + ++labelsCount; + if (labelsCount > 21) + {ThrowParseErrorException("SQL46010", vExpr, TSqlParserResource.SQL46010Message, CodeGenerationSupporter.AIExtract); + } + AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } + ; + +// AI_FIX_GRAMMAR() +aiFixGrammarFunctionCall returns [AIFixGrammarFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vInput; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AIFixGrammar); + UpdateTokenInfo(vResult, tFunc); + } + vInput = expression + { + vResult.Input = vInput; + } + RightParenthesis + ; + +// AI_GENERATE_RESPONSE([, ]) +aiGenerateResponseFunctionCall returns [AIGenerateResponseFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vPart1; + ScalarExpression vPart2; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AIGenerateResponse); + UpdateTokenInfo(vResult, tFunc); + } + vPart1 = expression + { + vResult.PromptPart1 = vPart1; + } + ( + Comma vPart2 = expression + { + vResult.PromptPart2 = vPart2; + } + )? + RightParenthesis + ; + +// AI_SUMMARIZE() +aiSummarizeFunctionCall returns [AISummarizeFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vInput; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AISummarize); + UpdateTokenInfo(vResult, tFunc); + } + vInput = expression + { + vResult.Input = vInput; + } + RightParenthesis + ; + +// AI_TRANSLATE(, ) +aiTranslateFunctionCall returns [AITranslateFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + ScalarExpression vInput; + ScalarExpression vLang; +} + : tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.AITranslate); + UpdateTokenInfo(vResult, tFunc); + } + vInput = expression + { + vResult.Input = vInput; + } + Comma vLang = expression + { + vResult.Language = vLang; + } + RightParenthesis + ; // TODO, olegr: Add more checks for allowed functions here - there are quite some in SQL Server parser builtInFunctionCall returns [FunctionCall vResult = FragmentFactory.CreateFragment()] diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs new file mode 100644 index 00000000..181c775f --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs @@ -0,0 +1,25 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_ANALYZE_SENTIMENT function call like + /// AI_ANALYZE_SENTIMENT(input), where input is an expression or identifier. + /// + /// Expression node to generate + public override void ExplicitVisit(AIAnalyzeSentimentFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AIAnalyzeSentiment); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.Input); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs new file mode 100644 index 00000000..9baf443b --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_CLASSIFY function call like + /// AI_CLASSIFY(input, label1, label2 [, ...]), + /// where input is an expression or identifier, + /// and labels are expressions or identifiers representing classification labels. + /// + /// Expression node to generate + public override void ExplicitVisit(AIClassifyFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AIClassify); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + // input + GenerateFragmentIfNotNull(node.Input); + + // labels (require at least two via grammar) + if (node.Labels != null) + { + for (int i = 0; i < node.Labels.Count; i++) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + GenerateFragmentIfNotNull(node.Labels[i]); + } + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs new file mode 100644 index 00000000..0eb0fbb0 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_EXTRACT function call like + /// AI_EXTRACT(input, label1 [, ...]), + /// where input is an expression or identifier, + /// and labels are expressions or identifiers + /// representing extractible entities. + /// + /// Expression node to generate + public override void ExplicitVisit(AIExtractFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AIExtract); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + // input + GenerateFragmentIfNotNull(node.Input); + + // labels + if (node.Labels != null) + { + for (int i = 0; i < node.Labels.Count; i++) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + GenerateFragmentIfNotNull(node.Labels[i]); + } + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs new file mode 100644 index 00000000..a5de5c1d --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs @@ -0,0 +1,25 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_ANALYZE_SENTIMENT function call like + /// AI_ANALYZE_SENTIMENT(input), where input is an expression or identifier. + /// + /// Expression node to generate + public override void ExplicitVisit(AIFixGrammarFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AIFixGrammar); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.Input); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs new file mode 100644 index 00000000..393a9af3 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_GENERATE_RESPONSE function call like + /// AI_GENERATE_RESPONSE(promptPart1, promptPart2), + /// where promptPart1 and promptPart2 are expressions or identifiers + /// representing the parts of the prompt. + /// + /// Expression node to generate + public override void ExplicitVisit(AIGenerateResponseFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AIGenerateResponse); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + GenerateFragmentIfNotNull(node.PromptPart1); + + if (node.PromptPart2 != null) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + GenerateFragmentIfNotNull(node.PromptPart2); + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs new file mode 100644 index 00000000..fe1adafc --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_SUMMARIZE function call like + /// AI_SUMMARIZE(input), + /// where input is an expression or identifier. + /// + /// Expression node to generate + public override void ExplicitVisit(AISummarizeFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AISummarize); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.Input); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs new file mode 100644 index 00000000..922751c6 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an AI_TRANSLATE function call like + /// AI_TRANSLATE(input, language), + /// where input is an expression or identifier, + /// and language is an expression or identifier + /// representing the target language. + /// + /// Expression node to generate + public override void ExplicitVisit(AITranslateFunctionCall node) + { + GenerateIdentifier(CodeGenerationSupporter.AITranslate); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateFragmentIfNotNull(node.Input); + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + GenerateFragmentIfNotNull(node.Language); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/Test/SqlDom/Baselines160/IifParenthesesTests160.sql b/Test/SqlDom/Baselines160/IifParenthesesTests160.sql new file mode 100644 index 00000000..39e6f21d --- /dev/null +++ b/Test/SqlDom/Baselines160/IifParenthesesTests160.sql @@ -0,0 +1,97 @@ +SELECT (SELECT 1 + WHERE (IIF (1 > 0 + AND 2 > 1, 1, 0)) = 1); + + +GO +SELECT 1 +WHERE (IIF (1 > 0, 1, 0)) = 1; + + +GO +SELECT 1 +WHERE (IIF (1 > 0 + AND 2 > 1 + OR 3 < 4, 1, 0)) = 1; + + +GO +SELECT 1 +WHERE (IIF (1 >= 0 + AND 2 <= 1 + AND 3 <> 4, 1, 0)) = 1; + + +GO +SELECT 1 +WHERE (IIF (IIF (1 > 0, 1, 0) > 0, 'yes', 'no')) = 'yes'; + + +GO +SELECT (IIF (1 > 0, 1, 0)) + 1 AS result; + + +GO +SELECT 1 +WHERE (IIF (1 > 0, 1, 0)) = 1 + AND (IIF (2 > 1, 1, 0)) = 1; + + +GO +SELECT 1 +WHERE IIF (1 > 0 + AND 2 > 1, 1, 0) = 1; + + +GO +SELECT 1 +WHERE ((((IIF (1 > 0 + AND 2 > 1, 1, 0))))) = 1; + + +GO +SELECT 1 +WHERE (((((IIF (1 > 0 + AND 2 > 1 + OR 3 < 4, 1, 0)))))) = 1; + + +GO +SELECT 1 +WHERE (((IIF (1 > 0, 1, 0)) = 1) + AND ((IIF (2 > 1, 1, 0)) = 1)); + + +GO +SELECT ((((IIF (1 > 0 + AND 2 > 1, 10, 20))))) + 5 AS result; + + +GO +SELECT 1 +WHERE ((IIF ((IIF (1 > 0, 1, 0)) > 0, 'yes', 'no'))) = 'yes'; + + +GO +SELECT 1 +WHERE (IIF (((IIF (1 > 0 + AND 2 > 1, 1, 0))) > 0, 'a', 'b')) = 'a'; + + +GO +SELECT 1 +WHERE ((IIF ((IIF ((IIF (1 > 0, 1, 0)) > 0, 2, 3)) > 1, 'x', 'y'))) = 'x'; + + +GO +SELECT 1 +WHERE (((IIF (((IIF (1 > 0 + AND 2 > 1, 1, 0))) = 1 + AND 3 < 5, 'pass', 'fail')))) = 'pass'; + + +GO +SELECT 1 AS IIF +FROM T1; + + diff --git a/Test/SqlDom/Baselines170/ComplexQueryTests170.sql b/Test/SqlDom/Baselines170/ComplexQueryTests170.sql new file mode 100644 index 00000000..3e2cb7bc --- /dev/null +++ b/Test/SqlDom/Baselines170/ComplexQueryTests170.sql @@ -0,0 +1,69 @@ +SELECT 139 AS [p_1_0] +FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN (([dbo].[table_6] AS [alias_1_4] + RIGHT OUTER JOIN + [dbo].[table_3] AS [alias_1_5] + ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3))))); + +SELECT CAST ('test' AS VECTOR(3, Float32)); + +SELECT CAST ('test' AS VECTOR(3, Float32)); + +SELECT 1 +WHERE col = CAST ('test' AS VECTOR(3, Float32)); + +SELECT 1 +WHERE col IN (SELECT CAST ('test' AS VECTOR(3, Float32))); + +SELECT CAST ($492050157978986.2129 AS MONEY) AS [p_0_0] +FROM ([dbo].[table_6] AS [alias_0_0] CROSS JOIN [dbo].[table_4] AS [alias_0_1]) +WHERE (NOT (SYSDATETIME() IN (SELECT 139 AS [p_1_0] + FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN ([dbo].[table_6] AS [alias_1_1] + LEFT OUTER JOIN + ([dbo].[table_6] AS [alias_1_2] + INNER JOIN + ([dbo].[table_5] AS [alias_1_3] CROSS APPLY ([dbo].[table_6] AS [alias_1_4] + RIGHT OUTER JOIN + [dbo].[table_3] AS [alias_1_5] + ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3, Float32)))) + ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) + ON [alias_1_1].[c_1] = CONVERT (VECTOR(77), '[-7.230808E+08,4.075427E+08]')))) + OR (CONVERT (BIGINT, CONVERT (INT, 8)) >= 157) + OR (140 <= 19))); + +SELECT CAST ($492050157978986.2129 AS MONEY) AS [p_0_0] +FROM ([dbo].[table_6] AS [alias_0_0] CROSS JOIN [dbo].[table_4] AS [alias_0_1]) +WHERE (NOT (SYSDATETIME() IN (SELECT 139 AS [p_1_0] + FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN ([dbo].[table_6] AS [alias_1_1] + LEFT OUTER JOIN + ([dbo].[table_6] AS [alias_1_2] + INNER JOIN + ([dbo].[table_5] AS [alias_1_3] CROSS APPLY ([dbo].[table_6] AS [alias_1_4] + RIGHT OUTER JOIN + [dbo].[table_3] AS [alias_1_5] + ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3)))) + ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) + ON [alias_1_1].[c_1] = CONVERT (VECTOR(77), '[-7.230808E+08,4.075427E+08]')))) + OR (CONVERT (BIGINT, CONVERT (INT, 8)) >= 157) + OR (140 <= 19))); + +SELECT TOP 100 t1.order_id, + t1.customer_id, + t2.product_name, + t3.category_name +FROM ([dbo].[orders] AS t1 CROSS JOIN ([dbo].[order_items] AS t2 + LEFT OUTER JOIN + ([dbo].[products] AS t3 + INNER JOIN + ([dbo].[categories] AS t4 CROSS APPLY ([dbo].[suppliers] AS t5 + RIGHT OUTER JOIN + [dbo].[regions] AS t6 + ON t5.region_id = t6.id + AND t5.active = 1)) + ON t3.category_id = t4.id) + ON t2.product_id = t3.id)) +WHERE (t1.order_date >= '2025-01-01' + AND t2.quantity > 0 + AND EXISTS (SELECT 1 + FROM [dbo].[inventory] AS inv + WHERE inv.product_id = t2.product_id + AND inv.stock_level > 10)); \ No newline at end of file diff --git a/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql new file mode 100644 index 00000000..7c2656f9 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT AI_ANALYZE_SENTIMENT('text'); + +SELECT AI_ANALYZE_SENTIMENT(t.text_col) +FROM dbo.Texts AS t; + +SELECT AI_ANALYZE_SENTIMENT(text_col) +FROM Texts; + +DECLARE @s0 AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_ANALYZE_SENTIMENT(@s0 + 'a'); + +SELECT AI_ANALYZE_SENTIMENT('b' + 'a'); + +SELECT * +FROM AI_ANALYZE_SENTIMENT((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_ANALYZE_SENTIMENT(@s)); +END diff --git a/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql new file mode 100644 index 00000000..4703721d --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql @@ -0,0 +1,26 @@ +SELECT AI_CLASSIFY('text', 'spam', 'ham'); + +SELECT AI_CLASSIFY(t.text_col, 'spam', 'ham') +FROM dbo.Texts AS t; + +DECLARE @s AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_CLASSIFY(@s, 'topic', 'sentiment', 'intent'); + +SELECT AI_CLASSIFY('b' + 'a', 'topic', 'sentiment', 'intent'); + +SELECT AI_CLASSIFY(@s + 'a', 'topic', 'sentiment', 'intent'); + +SELECT * +FROM AI_CLASSIFY((SELECT t.text_col + FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_CLASSIFY(@s, 'labelA', 'labelB')); +END diff --git a/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql new file mode 100644 index 00000000..4af178b7 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql @@ -0,0 +1,26 @@ +SELECT AI_EXTRACT('text', 'spam', 'ham'); + +SELECT AI_EXTRACT(t.text_col, 'spam', 'ham') +FROM dbo.Texts AS t; + +DECLARE @s AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_EXTRACT(@s, 'topic', 'sentiment', 'intent'); + +SELECT AI_EXTRACT('b' + 'a', 'topic', 'sentiment', 'intent'); + +SELECT AI_EXTRACT(@s + 'a', 'topic', 'sentiment', 'intent'); + +SELECT * +FROM AI_EXTRACT((SELECT t.text_col + FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_EXTRACT(@s, 'labelA', 'labelB')); +END diff --git a/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql new file mode 100644 index 00000000..7e6225a6 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT AI_FIX_GRAMMAR('text'); + +SELECT AI_FIX_GRAMMAR(t.text_col) +FROM dbo.Texts AS t; + +SELECT AI_FIX_GRAMMAR(text_col) +FROM Texts; + +DECLARE @s0 AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_FIX_GRAMMAR(@s0 + 'a'); + +SELECT AI_FIX_GRAMMAR('b' + 'a'); + +SELECT * +FROM AI_FIX_GRAMMAR((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_FIX_GRAMMAR(@s)); +END diff --git a/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql new file mode 100644 index 00000000..5a0a6b55 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql @@ -0,0 +1,25 @@ +SELECT AI_GENERATE_RESPONSE('Hello'); + +SELECT AI_GENERATE_RESPONSE('Question:', ' What is the time?'); + +DECLARE @p1 AS NVARCHAR (MAX) = N'Prompt '; + +DECLARE @p2 AS NVARCHAR (MAX) = N'Continuation'; + +SELECT AI_GENERATE_RESPONSE(@p1 + 'part1', @p2); + +SELECT AI_GENERATE_RESPONSE('b' + 'a'); + +SELECT * +FROM AI_GENERATE_RESPONSE((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@p NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_GENERATE_RESPONSE(@p)); +END diff --git a/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql new file mode 100644 index 00000000..fbb972d0 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT AI_SUMMARIZE('text'); + +SELECT AI_SUMMARIZE(t.text_col) +FROM dbo.Texts AS t; + +SELECT AI_SUMMARIZE(text_col) +FROM Texts; + +DECLARE @s0 AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_SUMMARIZE(@s0 + 'a'); + +SELECT AI_SUMMARIZE('b' + 'a'); + +SELECT * +FROM AI_SUMMARIZE((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_SUMMARIZE(@s)); +END diff --git a/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql new file mode 100644 index 00000000..10b497d3 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql @@ -0,0 +1,33 @@ +SELECT AI_TRANSLATE(t.text_col, 'es') +FROM dbo.Texts AS t; + +SELECT AI_TRANSLATE('text', 'es'); + +SELECT AI_TRANSLATE('text' + 'text', 'e' + 's'); + +DECLARE @s AS NVARCHAR (MAX) = N'Hello world'; + +DECLARE @lang AS NVARCHAR (5) = N'en'; + +SELECT AI_TRANSLATE(@s, @lang); + +SELECT AI_TRANSLATE(@s + 'a', @lang + 'a'); + +SELECT * +FROM AI_TRANSLATE((SELECT t.text_col + FROM dbo.Texts AS t), 'e' + 's'); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_TRANSLATE(@s, 'fr')); +END + + +GO +SELECT AI_TRANSLATE(@s, t.lang) +FROM dbo.Texts AS t; diff --git a/Test/SqlDom/Only160SyntaxTests.cs b/Test/SqlDom/Only160SyntaxTests.cs index 43cba90c..552152b3 100644 --- a/Test/SqlDom/Only160SyntaxTests.cs +++ b/Test/SqlDom/Only160SyntaxTests.cs @@ -54,6 +54,7 @@ public partial class SqlDomTests new ParserTest160("NotEnforcedConstraintTests160.sql", nErrors80: 3, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1), new ParserTest160("VectorFunctionTests160.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0), + new ParserTest160("IifParenthesesTests160.sql", nErrors80: 16, nErrors90: 16, nErrors100: 16, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), }; private static readonly ParserTest[] SqlAzure160_TestInfos = diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 3132f3c7..50394937 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -31,7 +31,9 @@ public partial class SqlDomTests new ParserTest170("VectorTypeSecondParameterTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), new ParserTest170("RegexpLikeTests170.sql", nErrors80: 15, nErrors90: 15, nErrors100: 15, nErrors110: 18, nErrors120: 18, nErrors130: 18, nErrors140: 18, nErrors150: 18, nErrors160: 18), new ParserTest170("OptimizedLockingTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), - new ParserTest170("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0) + new ParserTest170("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), + // Complex query with VECTOR types - parses syntactically in all versions (optimization fix), but VECTOR type only valid in TSql170 + new ParserTest170("ComplexQueryTests170.sql") }; private static readonly ParserTest[] SqlAzure170_TestInfos = diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index 87c490a8..5bee5e26 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -17,6 +17,13 @@ public partial class SqlDomTests new ParserTestFabricDW("NestedCTETestsFabricDW.sql", nErrors80: 1, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2), new ParserTestFabricDW("ScalarFunctionTestsFabricDW.sql", nErrors80: 3, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), new ParserTestFabricDW("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiAnalyzeSentimentTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiClassifyTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiExtractTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiFixGrammarTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), }; [TestMethod] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 1fb39657..2204c307 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.VisualStudio.TestTools.UnitTesting; using SqlStudio.Tests.AssemblyTools.TestCategory; @@ -7103,87 +7104,6 @@ public void IdentityColumnNegativeTestsFabricDW() ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax2, new ParserErrorInfo(49, "SQL46010", "(")); } - /// - /// Negative tests for VECTOR INDEX syntax - /// - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void VectorIndexNegativeTests() - { - // Missing INDEX keyword - ParserTestUtils.ErrorTest170("CREATE VECTOR IX_Test ON dbo.Documents (VectorData)", - new ParserErrorInfo(7, "SQL46010", "VECTOR")); - - // Missing table name - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON (VectorData)", - new ParserErrorInfo(31, "SQL46010", "(")); - - // Missing column specification - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents", - new ParserErrorInfo(44, "SQL46029", "")); - - // Empty column list - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents ()", - new ParserErrorInfo(46, "SQL46010", ")")); - - // Multiple columns (not supported for vector indexes) - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData, OtherColumn)", - new ParserErrorInfo(56, "SQL46010", ",")); - - // Invalid metric value - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = 'invalid')", - new ParserErrorInfo(73, "SQL46010", "'invalid'")); - - // Invalid type value - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (TYPE = 'invalid')", - new ParserErrorInfo(71, "SQL46010", "'invalid'")); - - // Missing option value - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = )", - new ParserErrorInfo(73, "SQL46010", ")")); - - // Empty option value - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = '')", - new ParserErrorInfo(73, "SQL46010", "''")); - - // Missing WITH keyword when options are present - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) (METRIC = 'cosine')", - new ParserErrorInfo(59, "SQL46010", "METRIC")); - - // Missing parentheses around options - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH METRIC = 'cosine'", - new ParserErrorInfo(63, "SQL46010", "METRIC")); - - // Invalid option name - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (INVALID_OPTION = 'value')", - new ParserErrorInfo(64, "SQL46010", "INVALID_OPTION")); - - // Metric value without quotes - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = cosine)", - new ParserErrorInfo(73, "SQL46010", "cosine")); - - // Type value without quotes - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (TYPE = DiskANN)", - new ParserErrorInfo(71, "SQL46010", "DiskANN")); - - // MAXDOP with invalid value - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (MAXDOP = 'invalid')", - new ParserErrorInfo(73, "SQL46010", "'invalid'")); - - // MAXDOP with negative value - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (MAXDOP = -1)", - new ParserErrorInfo(73, "SQL46010", "-")); - - // Missing equals sign in option - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC 'cosine')", - new ParserErrorInfo(64, "SQL46010", "METRIC")); - - // Incomplete WITH clause - ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH", - new ParserErrorInfo(58, "SQL46010", "WITH")); - } - /// /// Negative tests for AI_GENERATE_CHUNKS syntax /// @@ -7625,5 +7545,234 @@ public void VectorSearchErrorTest170() "SELECT * FROM VECTOR_SEARCH('tbl1', 'col1', 'query_vector', 'dot', 5)", new ParserErrorInfo(28, "SQL46010", "'tbl1'")); } + + /// + /// Negative tests for VECTOR INDEX syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void VectorIndexNegativeTests() + { + // Missing INDEX keyword + ParserTestUtils.ErrorTest170("CREATE VECTOR IX_Test ON dbo.Documents (VectorData)", + new ParserErrorInfo(7, "SQL46010", "VECTOR")); + + // Missing table name + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON (VectorData)", + new ParserErrorInfo(31, "SQL46010", "(")); + + // Missing column specification + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents", + new ParserErrorInfo(44, "SQL46029", "")); + + // Empty column list + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents ()", + new ParserErrorInfo(46, "SQL46010", ")")); + + // Multiple columns (not supported for vector indexes) + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData, OtherColumn)", + new ParserErrorInfo(56, "SQL46010", ",")); + + // Invalid metric value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = 'invalid')", + new ParserErrorInfo(73, "SQL46010", "'invalid'")); + + // Invalid type value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (TYPE = 'invalid')", + new ParserErrorInfo(71, "SQL46010", "'invalid'")); + + // Missing option value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = )", + new ParserErrorInfo(73, "SQL46010", ")")); + + // Empty option value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = '')", + new ParserErrorInfo(73, "SQL46010", "''")); + + // Missing WITH keyword when options are present + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) (METRIC = 'cosine')", + new ParserErrorInfo(59, "SQL46010", "METRIC")); + + // Missing parentheses around options + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH METRIC = 'cosine'", + new ParserErrorInfo(63, "SQL46010", "METRIC")); + + // Invalid option name + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (INVALID_OPTION = 'value')", + new ParserErrorInfo(64, "SQL46010", "INVALID_OPTION")); + + // Metric value without quotes + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC = cosine)", + new ParserErrorInfo(73, "SQL46010", "cosine")); + + // Type value without quotes + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (TYPE = DiskANN)", + new ParserErrorInfo(71, "SQL46010", "DiskANN")); + + // MAXDOP with invalid value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (MAXDOP = 'invalid')", + new ParserErrorInfo(73, "SQL46010", "'invalid'")); + + // MAXDOP with negative value + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (MAXDOP = -1)", + new ParserErrorInfo(73, "SQL46010", "-")); + + // Missing equals sign in option + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH (METRIC 'cosine')", + new ParserErrorInfo(64, "SQL46010", "METRIC")); + + // Incomplete WITH clause + ParserTestUtils.ErrorTest170("CREATE VECTOR INDEX IX_Test ON dbo.Documents (VectorData) WITH", + new ParserErrorInfo(58, "SQL46010", "WITH")); + } + + /// + /// Negative tests for AI_ANALYZE_SENTIMET syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiAnalyzeSentimentNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_ANALYZE_SENTIMENT()", + new ParserErrorInfo(28, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_ANALYZE_SENTIMENT('1', '2')", + new ParserErrorInfo(31, "SQL46010", ",")); + } + + /// + /// Negative tests for AI_CLASSIFY syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiClassifyNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_CLASSIFY()", + new ParserErrorInfo(19, "SQL46010", ")")); + + // Too few arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_CLASSIFY('1')", + new ParserErrorInfo(22, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + $"SELECT AI_CLASSIFY({string.Join(", ", Enumerable.Repeat("'1'", 23))})", + new ParserErrorInfo(129, "SQL46010", "AI_CLASSIFY")); + } + + /// + /// Negative tests for AI_EXTRACT syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiExtractNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_EXTRACT()", + new ParserErrorInfo(18, "SQL46010", ")")); + + // Too few arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_EXTRACT('1')", + new ParserErrorInfo(21, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + $"SELECT AI_EXTRACT({string.Join(", ", Enumerable.Repeat("'1'", 23))})", + new ParserErrorInfo(128, "SQL46010", "AI_EXTRACT")); + } + + /// + /// Negative tests for AI_SUMMARIZE syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiFixGrammarNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_FIX_GRAMMAR()", + new ParserErrorInfo(22, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_FIX_GRAMMAR('1', '2')", + new ParserErrorInfo(25, "SQL46010", ",")); + } + + /// + /// Negative tests for AI_GENERATE_RESPONSE syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiGenerateResponseNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_GENERATE_RESPONSE()", + new ParserErrorInfo(28, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_GENERATE_RESPONSE('1', '2', '3')", + new ParserErrorInfo(36, "SQL46010", ",")); + } + + /// + /// Negative tests for AI_SUMMARIZE syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiSummarizeNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_SUMMARIZE()", + new ParserErrorInfo(20, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_SUMMARIZE('1', '2')", + new ParserErrorInfo(23, "SQL46010", ",")); + } + + /// + /// Negative tests for AI_GENERATE_RESPONSE syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiTranslateNegativeTestsFabricDw() + { + // Missing arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE()", + new ParserErrorInfo(20, "SQL46010", ")")); + + // Too few arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('1')", + new ParserErrorInfo(23, "SQL46010", ")")); + + // Too many arguments + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('1', '2', '3')", + new ParserErrorInfo(28, "SQL46010", ",")); + } } } diff --git a/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql new file mode 100644 index 00000000..7c2656f9 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT AI_ANALYZE_SENTIMENT('text'); + +SELECT AI_ANALYZE_SENTIMENT(t.text_col) +FROM dbo.Texts AS t; + +SELECT AI_ANALYZE_SENTIMENT(text_col) +FROM Texts; + +DECLARE @s0 AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_ANALYZE_SENTIMENT(@s0 + 'a'); + +SELECT AI_ANALYZE_SENTIMENT('b' + 'a'); + +SELECT * +FROM AI_ANALYZE_SENTIMENT((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_ANALYZE_SENTIMENT(@s)); +END diff --git a/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql new file mode 100644 index 00000000..2a623c02 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql @@ -0,0 +1,23 @@ +-- Scalar input + two string labels +SELECT AI_CLASSIFY('text', 'spam', 'ham'); + +-- Column input + two string labels +SELECT AI_CLASSIFY(t.text_col, 'spam', 'ham') +FROM dbo.Texts AS t; + +-- Variable input + three labels +DECLARE @s NVARCHAR(MAX) = N'Hello world'; +SELECT AI_CLASSIFY(@s, 'topic', 'sentiment', 'intent'); +SELECT AI_CLASSIFY('b' + 'a', 'topic', 'sentiment', 'intent'); +SELECT AI_CLASSIFY(@s + 'a', 'topic', 'sentiment', 'intent'); +SELECT * FROM AI_CLASSIFY((SELECT t.text_col FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); +GO + +-- RETURN context +CREATE OR ALTER FUNCTION dbo.fx(@s NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN (AI_CLASSIFY(@s, 'labelA', 'labelB')); +END; +GO diff --git a/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql new file mode 100644 index 00000000..cf2c82e2 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql @@ -0,0 +1,23 @@ +-- Scalar input + two string labels +SELECT AI_EXTRACT('text', 'spam', 'ham'); + +-- Column input + two string labels +SELECT AI_EXTRACT(t.text_col, 'spam', 'ham') +FROM dbo.Texts AS t; + +-- Variable input + three labels +DECLARE @s NVARCHAR(MAX) = N'Hello world'; +SELECT AI_EXTRACT(@s, 'topic', 'sentiment', 'intent'); +SELECT AI_EXTRACT('b' + 'a', 'topic', 'sentiment', 'intent'); +SELECT AI_EXTRACT(@s + 'a', 'topic', 'sentiment', 'intent'); +SELECT * FROM AI_EXTRACT((SELECT t.text_col FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); +GO + +-- RETURN context +CREATE OR ALTER FUNCTION dbo.fx(@s NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN (AI_EXTRACT(@s, 'labelA', 'labelB')); +END; +GO diff --git a/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql new file mode 100644 index 00000000..7e6225a6 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT AI_FIX_GRAMMAR('text'); + +SELECT AI_FIX_GRAMMAR(t.text_col) +FROM dbo.Texts AS t; + +SELECT AI_FIX_GRAMMAR(text_col) +FROM Texts; + +DECLARE @s0 AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_FIX_GRAMMAR(@s0 + 'a'); + +SELECT AI_FIX_GRAMMAR('b' + 'a'); + +SELECT * +FROM AI_FIX_GRAMMAR((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_FIX_GRAMMAR(@s)); +END diff --git a/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql new file mode 100644 index 00000000..55cec5a1 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql @@ -0,0 +1,19 @@ +SELECT AI_GENERATE_RESPONSE('Hello'); + +SELECT AI_GENERATE_RESPONSE('Question:', ' What is the time?'); + +DECLARE @p1 NVARCHAR(MAX) = N'Prompt '; +DECLARE @p2 NVARCHAR(MAX) = N'Continuation'; +SELECT AI_GENERATE_RESPONSE(@p1 + 'part1', @p2); +SELECT AI_GENERATE_RESPONSE('b' + 'a'); +SELECT * FROM AI_GENERATE_RESPONSE((SELECT t.text_col + FROM dbo.Texts AS t)); +GO + +CREATE OR ALTER FUNCTION dbo.fx(@p NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN (AI_GENERATE_RESPONSE(@p)); +END; +GO diff --git a/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql new file mode 100644 index 00000000..fbb972d0 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT AI_SUMMARIZE('text'); + +SELECT AI_SUMMARIZE(t.text_col) +FROM dbo.Texts AS t; + +SELECT AI_SUMMARIZE(text_col) +FROM Texts; + +DECLARE @s0 AS NVARCHAR (MAX) = N'Hello world'; + +SELECT AI_SUMMARIZE(@s0 + 'a'); + +SELECT AI_SUMMARIZE('b' + 'a'); + +SELECT * +FROM AI_SUMMARIZE((SELECT t.text_col + FROM dbo.Texts AS t)); + + +GO +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_SUMMARIZE(@s)); +END diff --git a/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql new file mode 100644 index 00000000..bcda9fb0 --- /dev/null +++ b/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql @@ -0,0 +1,26 @@ +SELECT AI_TRANSLATE (t.text_col, 'es') +FROM dbo.Texts AS t; + +SELECT AI_TRANSLATE ('text', 'es'); +SELECT AI_TRANSLATE ('text' + 'text', 'e' + 's'); + +DECLARE @s AS NVARCHAR (MAX) = N'Hello world'; +DECLARE @lang AS NVARCHAR (5) = N'en'; +SELECT AI_TRANSLATE (@s, @lang); +SELECT AI_TRANSLATE (@s + 'a', @lang + 'a'); +SELECT * FROM AI_TRANSLATE((SELECT t.text_col + FROM dbo.Texts AS t), 'e' + 's'); +GO + +CREATE OR ALTER FUNCTION dbo.fx +(@s NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (AI_TRANSLATE (@s, 'fr')); +END + +GO + +SELECT AI_TRANSLATE (@s, t.lang) +FROM dbo.Texts AS t; diff --git a/Test/SqlDom/TestScripts/ComplexQueryTests170.sql b/Test/SqlDom/TestScripts/ComplexQueryTests170.sql new file mode 100644 index 00000000..0275e036 --- /dev/null +++ b/Test/SqlDom/TestScripts/ComplexQueryTests170.sql @@ -0,0 +1,72 @@ +SELECT 139 AS [p_1_0] +FROM ( +[dbo].[table_0] AS [alias_1_0] CROSS JOIN +(( +[dbo].[table_6] AS [alias_1_4] +RIGHT OUTER JOIN +[dbo].[table_3] AS [alias_1_5] +ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR (3)) +))) + + +SELECT CAST('test' AS VECTOR (3, Float32)) + +SELECT CAST('test' AS VECTOR(3, Float32)) + +SELECT 1 WHERE col = CAST('test' AS VECTOR (3, Float32)); + +SELECT 1 WHERE col IN (SELECT CAST('test' AS VECTOR (3, Float32))); + +-- Complex query with nested subqueries and various joins with VECTOR(3, Float32) +SELECT CAST ($492050157978986.2129 AS MONEY) AS [p_0_0] +FROM ([dbo].[table_6] AS [alias_0_0] CROSS JOIN [dbo].[table_4] AS [alias_0_1]) +WHERE (NOT (SYSDATETIME() IN (SELECT 139 AS [p_1_0] +FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN ([dbo].[table_6] AS [alias_1_1] + LEFT OUTER JOIN +([dbo].[table_6] AS [alias_1_2] + INNER JOIN +([dbo].[table_5] AS [alias_1_3] CROSS APPLY ([dbo].[table_6] AS [alias_1_4] +RIGHT OUTER JOIN +[dbo].[table_3] AS [alias_1_5] +ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR (3, Float32)))) +ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) +ON [alias_1_1].[c_1] = CONVERT (VECTOR (77), '[-7.230808E+08,4.075427E+08]')))) +OR (CONVERT (BIGINT, CONVERT (INT, 8)) >= 157) +OR (140 <= 19))) + +-- Complex query with nested subqueries and various joins with VECTOR(3) +SELECT CAST ($492050157978986.2129 AS MONEY) AS [p_0_0] +FROM ([dbo].[table_6] AS [alias_0_0] CROSS JOIN [dbo].[table_4] AS [alias_0_1]) +WHERE (NOT (SYSDATETIME() IN (SELECT 139 AS [p_1_0] +FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN ([dbo].[table_6] AS [alias_1_1] + LEFT OUTER JOIN +([dbo].[table_6] AS [alias_1_2] + INNER JOIN +([dbo].[table_5] AS [alias_1_3] CROSS APPLY ([dbo].[table_6] AS [alias_1_4] +RIGHT OUTER JOIN +[dbo].[table_3] AS [alias_1_5] +ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR (3)))) +ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) +ON [alias_1_1].[c_1] = CONVERT (VECTOR (77), '[-7.230808E+08,4.075427E+08]')))) +OR (CONVERT (BIGINT, CONVERT (INT, 8)) >= 157) +OR (140 <= 19))) + +-- Complex query involving multiple joins, CROSS APPLY, and filtering conditions +SELECT TOP 100 t1.order_id, t1.customer_id, t2.product_name, t3.category_name +FROM ([dbo].[orders] AS t1 + CROSS JOIN ([dbo].[order_items] AS t2 + LEFT OUTER JOIN + ([dbo].[products] AS t3 + INNER JOIN + ([dbo].[categories] AS t4 + CROSS APPLY ([dbo].[suppliers] AS t5 + RIGHT OUTER JOIN + [dbo].[regions] AS t6 + ON t5.region_id = t6.id AND t5.active = 1)) + ON t3.category_id = t4.id) + ON t2.product_id = t3.id)) +WHERE (t1.order_date >= '2025-01-01' + AND t2.quantity > 0 + AND EXISTS (SELECT 1 FROM [dbo].[inventory] AS inv + WHERE inv.product_id = t2.product_id + AND inv.stock_level > 10)) \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/IifParenthesesTests160.sql b/Test/SqlDom/TestScripts/IifParenthesesTests160.sql new file mode 100644 index 00000000..2c6bda6b --- /dev/null +++ b/Test/SqlDom/TestScripts/IifParenthesesTests160.sql @@ -0,0 +1,75 @@ +-- Test IIF with parentheses wrapping - regression test for customer-reported bug +-- The parser was incorrectly rejecting valid T-SQL like WHERE (IIF(...)) = 1 + +-- Original repro case: IIF with multiple boolean operators wrapped in parentheses +SELECT +( + SELECT 1 + WHERE (IIF(1 > 0 AND 2 > 1, 1, 0)) = 1 +); +GO + +-- Simple IIF wrapped in parentheses with comparison +SELECT 1 WHERE (IIF(1 > 0, 1, 0)) = 1; +GO + +-- IIF with multiple boolean operators (AND, OR) wrapped in parentheses +SELECT 1 WHERE (IIF(1 > 0 AND 2 > 1 OR 3 < 4, 1, 0)) = 1; +GO + +-- IIF with comparison operators inside, wrapped in parentheses +SELECT 1 WHERE (IIF(1 >= 0 AND 2 <= 1 AND 3 <> 4, 1, 0)) = 1; +GO + +-- Nested IIF wrapped in parentheses +SELECT 1 WHERE (IIF(IIF(1 > 0, 1, 0) > 0, 'yes', 'no')) = 'yes'; +GO + +-- IIF in SELECT clause wrapped in parentheses +SELECT (IIF(1 > 0, 1, 0)) + 1 AS result; +GO + +-- Multiple IIF expressions with parentheses +SELECT 1 WHERE (IIF(1 > 0, 1, 0)) = 1 AND (IIF(2 > 1, 1, 0)) = 1; +GO + +-- IIF without parentheses (should still work - baseline) +SELECT 1 WHERE IIF(1 > 0 AND 2 > 1, 1, 0) = 1; +GO + +-- Deeply nested parentheses (4 levels) around IIF +SELECT 1 WHERE ((((IIF(1 > 0 AND 2 > 1, 1, 0))))) = 1; +GO + +-- Deeply nested parentheses (5 levels) around IIF with complex boolean +SELECT 1 WHERE (((((IIF(1 > 0 AND 2 > 1 OR 3 < 4, 1, 0)))))) = 1; +GO + +-- Mixed nesting: parentheses around boolean operators and IIF +SELECT 1 WHERE (((IIF(1 > 0, 1, 0)) = 1) AND ((IIF(2 > 1, 1, 0)) = 1)); +GO + +-- Deeply nested IIF inside arithmetic expression +SELECT ((((IIF(1 > 0 AND 2 > 1, 10, 20))))) + 5 AS result; +GO + +-- Nested IIF with extra parentheses around outer IIF +SELECT 1 WHERE ((IIF((IIF(1 > 0, 1, 0)) > 0, 'yes', 'no'))) = 'yes'; +GO + +-- Nested IIF with extra parentheses around inner IIF +SELECT 1 WHERE (IIF(((IIF(1 > 0 AND 2 > 1, 1, 0))) > 0, 'a', 'b')) = 'a'; +GO + +-- Triple nested IIF with parentheses +SELECT 1 WHERE ((IIF((IIF((IIF(1 > 0, 1, 0)) > 0, 2, 3)) > 1, 'x', 'y'))) = 'x'; +GO + +-- Nested IIF with boolean operators and extra parentheses +SELECT 1 WHERE (((IIF(((IIF(1 > 0 AND 2 > 1, 1, 0))) = 1 AND 3 < 5, 'pass', 'fail')))) = 'pass'; +GO + +-- Edge case: IIF used as column alias (not a function call) +-- This tests that pendingIIf flag is reset when IIF is not followed by ( +SELECT 1 AS IIF FROM T1; +GO diff --git a/release-notes/170/170.157.0.md b/release-notes/170/170.157.0.md new file mode 100644 index 00000000..4e9cb54d --- /dev/null +++ b/release-notes/170/170.157.0.md @@ -0,0 +1,26 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 170.157.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates .NET SDK to latest patch version 8.0.415 + +#### .NET Framework +#### .NET Core + +### New Features +* Adds support for Fabric DW specific AI functions + +### Fixed +* Fixes https://github.com/microsoft/SqlScriptDOM/issues/161 +* Fixes https://github.com/microsoft/SqlScriptDOM/issues/28 +### Changes + +### Known Issues From 5ddf970e359e33dfc5fa1fd9483257f8beca2c00 Mon Sep 17 00:00:00 2001 From: Drew Skwiers-Koballa Date: Wed, 4 Feb 2026 13:59:37 -0800 Subject: [PATCH 19/45] adds formatter option for preserving comments (redo) (#187) --- .../SqlScriptGeneratorVisitor.Comments.cs | 284 ++++++ .../SqlScriptGeneratorVisitor.TSqlScript.cs | 9 + .../SqlScriptGeneratorVisitor.Utils.cs | 7 + .../Settings/SqlScriptGeneratorOptions.xml | 3 + .../Baselines170/MultiLineCommentTests170.sql | 9 + .../SingleLineCommentTests170.sql | 10 + Test/SqlDom/Only170SyntaxTests.cs | 5 +- Test/SqlDom/ScriptGeneratorTests.cs | 923 ++++++++++++++++++ .../TestScripts/MultiLineCommentTests170.sql | 16 + .../TestScripts/SingleLineCommentTests170.sql | 14 + 10 files changed, 1279 insertions(+), 1 deletion(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs create mode 100644 Test/SqlDom/Baselines170/MultiLineCommentTests170.sql create mode 100644 Test/SqlDom/Baselines170/SingleLineCommentTests170.sql create mode 100644 Test/SqlDom/TestScripts/MultiLineCommentTests170.sql create mode 100644 Test/SqlDom/TestScripts/SingleLineCommentTests170.sql diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs new file mode 100644 index 00000000..1ea9fec8 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs @@ -0,0 +1,284 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System; +using System.Collections.Generic; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + internal abstract partial class SqlScriptGeneratorVisitor + { + #region Comment Tracking Fields + + /// + /// Tracks the last token index processed for comment emission. + /// Used to find comments between visited fragments. + /// + private int _lastProcessedTokenIndex = -1; + + /// + /// The current script's token stream, set when visiting begins. + /// + private IList _currentTokenStream; + + /// + /// Tracks which comment tokens have already been emitted to avoid duplicates. + /// + private readonly HashSet _emittedComments = new HashSet(); + + /// + /// Tracks whether leading (file-level) comments have been emitted. + /// + private bool _leadingCommentsEmitted = false; + + #endregion + + #region Comment Preservation Methods + + /// + /// Sets the token stream for comment tracking. + /// Call this before visiting the root node when PreserveComments is enabled. + /// + /// The token stream from the parsed script. + protected void SetTokenStreamForComments(IList tokenStream) + { + _currentTokenStream = tokenStream; + _lastProcessedTokenIndex = -1; + _emittedComments.Clear(); + _leadingCommentsEmitted = false; + } + + /// + /// Emits comments that appear before the first fragment in the script (file-level leading comments). + /// Called once when generating the first fragment. + /// + /// The first fragment being generated. + protected void EmitLeadingComments(TSqlFragment fragment) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return; + } + + if (fragment.FirstTokenIndex <= 0) + { + return; + } + + for (int i = 0; i < fragment.FirstTokenIndex && i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + if (IsCommentToken(token) && !_emittedComments.Contains(token)) + { + EmitCommentToken(token, isLeading: true); + _emittedComments.Add(token); + } + } + } + + /// + /// Emits comments that appear in the gap between the last emitted token and the current fragment. + /// This captures comments embedded within sub-expressions. + /// + /// The fragment about to be generated. + protected void EmitGapComments(TSqlFragment fragment) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return; + } + + int startIndex = _lastProcessedTokenIndex + 1; + int endIndex = fragment.FirstTokenIndex; + + if (endIndex <= startIndex) + { + return; + } + + for (int i = startIndex; i < endIndex && i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + if (IsCommentToken(token) && !_emittedComments.Contains(token)) + { + EmitCommentToken(token, isLeading: true); + _emittedComments.Add(token); + _lastProcessedTokenIndex = i; + } + } + } + + /// + /// Emits trailing comments that appear immediately after the fragment. + /// + /// The fragment that was just generated. + protected void EmitTrailingComments(TSqlFragment fragment) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return; + } + + int lastTokenIndex = fragment.LastTokenIndex; + if (lastTokenIndex < 0 || lastTokenIndex >= _currentTokenStream.Count) + { + return; + } + + // Scan for comments immediately following the fragment + for (int i = lastTokenIndex + 1; i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + + if (IsCommentToken(token) && !_emittedComments.Contains(token)) + { + EmitCommentToken(token, isLeading: false); + _emittedComments.Add(token); + _lastProcessedTokenIndex = i; + } + else if (token.TokenType != TSqlTokenType.WhiteSpace) + { + // Stop at next non-whitespace, non-comment token + break; + } + } + } + + /// + /// Updates tracking after generating a fragment. + /// + /// The fragment that was just generated. + protected void UpdateLastProcessedIndex(TSqlFragment fragment) + { + if (fragment != null && fragment.LastTokenIndex > _lastProcessedTokenIndex) + { + _lastProcessedTokenIndex = fragment.LastTokenIndex; + } + } + + /// + /// Called from GenerateFragmentIfNotNull to handle comments before generating a fragment. + /// This is the key integration point that enables comments within sub-expressions. + /// + /// The fragment about to be generated. + protected void HandleCommentsBeforeFragment(TSqlFragment fragment) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return; + } + + // Emit file-level leading comments once + if (!_leadingCommentsEmitted) + { + EmitLeadingComments(fragment); + _leadingCommentsEmitted = true; + } + + // Emit any comments in the gap between last processed token and this fragment + EmitGapComments(fragment); + } + + /// + /// Called from GenerateFragmentIfNotNull to handle comments after generating a fragment. + /// + /// The fragment that was just generated. + protected void HandleCommentsAfterFragment(TSqlFragment fragment) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return; + } + + // Emit trailing comments and update tracking + EmitTrailingComments(fragment); + UpdateLastProcessedIndex(fragment); + } + + /// + /// Emits a comment token to the output. + /// + /// The comment token. + /// True if this is a leading comment, false for trailing. + private void EmitCommentToken(TSqlParserToken token, bool isLeading) + { + if (token == null) + { + return; + } + + if (token.TokenType == TSqlTokenType.SingleLineComment) + { + if (!isLeading) + { + // Trailing: add space before comment + _writer.AddToken(ScriptGeneratorSupporter.CreateWhitespaceToken(1)); + } + + _writer.AddToken(new TSqlParserToken(TSqlTokenType.SingleLineComment, token.Text)); + + if (isLeading) + { + // After a leading comment, add newline + _writer.NewLine(); + } + } + else if (token.TokenType == TSqlTokenType.MultilineComment) + { + if (!isLeading) + { + // Trailing: add space before comment + _writer.AddToken(ScriptGeneratorSupporter.CreateWhitespaceToken(1)); + } + + _writer.AddToken(new TSqlParserToken(TSqlTokenType.MultilineComment, token.Text)); + + if (isLeading) + { + // After a leading multi-line comment, add newline + _writer.NewLine(); + } + } + } + + /// + /// Emits any remaining comments at the end of the token stream. + /// Call this after visiting the root fragment to capture comments that appear + /// after the last statement (end-of-script comments). + /// + protected void EmitRemainingComments() + { + if (!_options.PreserveComments || _currentTokenStream == null) + { + return; + } + + // Scan from the last processed token to the end of the token stream + for (int i = _lastProcessedTokenIndex + 1; i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + if (IsCommentToken(token) && !_emittedComments.Contains(token)) + { + // End-of-script comments: add newline before, emit comment + _writer.NewLine(); + _writer.AddToken(new TSqlParserToken(token.TokenType, token.Text)); + _emittedComments.Add(token); + } + } + } + + /// + /// Checks if a token is a comment token. + /// + private static bool IsCommentToken(TSqlParserToken token) + { + return token != null && + (token.TokenType == TSqlTokenType.SingleLineComment || + token.TokenType == TSqlTokenType.MultilineComment); + } + + #endregion + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs index f7f51bb0..5f568500 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs @@ -12,6 +12,12 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(TSqlScript node) { + // Initialize token stream for comment preservation + if (_options.PreserveComments && node.ScriptTokenStream != null) + { + SetTokenStreamForComments(node.ScriptTokenStream); + } + Boolean firstItem = true; foreach (var item in node.Batches) { @@ -28,6 +34,9 @@ public override void ExplicitVisit(TSqlScript node) GenerateFragmentIfNotNull(item); } + + // Emit any remaining comments at end of script (after the last statement) + EmitRemainingComments(); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs index f6465233..381c6271 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs @@ -171,7 +171,14 @@ protected void GenerateFragmentIfNotNull(TSqlFragment fragment) { if (fragment != null) { + // Handle comments before generating the fragment + // This is the key integration point that enables comments within sub-expressions + HandleCommentsBeforeFragment(fragment); + fragment.Accept(this); + + // Handle comments after generating the fragment + HandleCommentsAfterFragment(fragment); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml index 551033ac..44853885 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml +++ b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml @@ -43,6 +43,9 @@ Gets or sets the number of newlines to include after each statement + + Gets or sets a boolean indicating if comments from the original script should be preserved in the generated output + diff --git a/Test/SqlDom/Baselines170/MultiLineCommentTests170.sql b/Test/SqlDom/Baselines170/MultiLineCommentTests170.sql new file mode 100644 index 00000000..663908db --- /dev/null +++ b/Test/SqlDom/Baselines170/MultiLineCommentTests170.sql @@ -0,0 +1,9 @@ +SELECT 1; + +SELECT 2; + +SELECT 3; + +SELECT 4; + +SELECT 5; diff --git a/Test/SqlDom/Baselines170/SingleLineCommentTests170.sql b/Test/SqlDom/Baselines170/SingleLineCommentTests170.sql new file mode 100644 index 00000000..badb4f94 --- /dev/null +++ b/Test/SqlDom/Baselines170/SingleLineCommentTests170.sql @@ -0,0 +1,10 @@ +SELECT 1; + +SELECT * +FROM dbo.MyTable; + +SELECT 2; + +SELECT 3; + +SELECT 4; diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 50394937..b4c10620 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -33,7 +33,10 @@ public partial class SqlDomTests new ParserTest170("OptimizedLockingTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), new ParserTest170("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), // Complex query with VECTOR types - parses syntactically in all versions (optimization fix), but VECTOR type only valid in TSql170 - new ParserTest170("ComplexQueryTests170.sql") + new ParserTest170("ComplexQueryTests170.sql"), + // Comment preservation tests - basic SQL syntax works in all versions + new ParserTest170("SingleLineCommentTests170.sql"), + new ParserTest170("MultiLineCommentTests170.sql") }; private static readonly ParserTest[] SqlAzure170_TestInfos = diff --git a/Test/SqlDom/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGeneratorTests.cs index 9a92ce38..5a21409d 100644 --- a/Test/SqlDom/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGeneratorTests.cs @@ -334,5 +334,928 @@ void ParseAndAssertEquality(string sqlText, SqlScriptGeneratorOptions generatorO Assert.AreEqual(sqlText, generatedSqlText); } + + #region Comment Preservation Tests + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsDefault() + { + // Verify default is false + var options = new SqlScriptGeneratorOptions(); + Assert.AreEqual(false, options.PreserveComments); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsDisabled() + { + // When PreserveComments is false (default), comments should be stripped + var sqlWithComments = "-- This is a leading comment\nSELECT 1; -- trailing comment"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = false // default + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Without PreserveComments, comments should not appear + Assert.IsFalse(generatedSql.Contains("--"), "Comments should be stripped when PreserveComments is false"); + Assert.IsFalse(generatedSql.Contains("leading comment"), "Comment text should not appear"); + Assert.IsFalse(generatedSql.Contains("trailing comment"), "Trailing comment should not appear"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_SingleLineLeading() + { + // When PreserveComments is true, leading single-line comments should be preserved + var sqlWithComments = "-- This is a leading comment\nSELECT 1;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // With PreserveComments, the comment should appear in output + Assert.IsTrue(generatedSql.Contains("-- This is a leading comment"), + "Leading comment should be preserved when PreserveComments is true"); + + // Verify comment appears BEFORE the SELECT keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("-- This is a leading comment"); + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < selectIndex, + $"Leading comment should appear before SELECT. Comment at {commentIndex}, SELECT at {selectIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_SingleLineTrailing() + { + // When PreserveComments is true, trailing single-line comments should be preserved + var sqlWithComments = "SELECT 1; -- trailing comment"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // With PreserveComments, the trailing comment should appear + Assert.IsTrue(generatedSql.Contains("-- trailing comment"), + "Trailing comment should be preserved when PreserveComments is true"); + + // Verify trailing comment appears AFTER the SELECT (correct positioning) + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + int commentIndex = generatedSql.IndexOf("-- trailing comment"); + Assert.IsTrue(commentIndex > selectIndex, + $"Trailing comment should appear after SELECT. SELECT at {selectIndex}, comment at {commentIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_MultipleStatements() + { + // Test comments between multiple statements + var sqlWithComments = @"-- First statement +SELECT 1; +-- Comment between statements +SELECT 2;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Both comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- First statement"), + "First comment should be preserved"); + Assert.IsTrue(generatedSql.Contains("-- Comment between statements"), + "Comment between statements should be preserved"); + + // Verify ordering: first comment -> SELECT 1 -> between comment -> SELECT 2 + int firstCommentIndex = generatedSql.IndexOf("-- First statement"); + int firstSelectIndex = generatedSql.IndexOf("SELECT 1", StringComparison.OrdinalIgnoreCase); + int betweenCommentIndex = generatedSql.IndexOf("-- Comment between statements"); + int secondSelectIndex = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(firstCommentIndex < firstSelectIndex, + "First comment should appear before first SELECT"); + Assert.IsTrue(firstSelectIndex < betweenCommentIndex, + "Between comment should appear after first SELECT"); + Assert.IsTrue(betweenCommentIndex < secondSelectIndex, + "Between comment should appear before second SELECT"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_MultiLineComment() + { + // When PreserveComments is true, multi-line comments should be preserved + var sqlWithComments = "/* This is a multi-line comment */\nSELECT 1;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // With PreserveComments, the multi-line comment should appear + Assert.IsTrue(generatedSql.Contains("/* This is a multi-line comment */"), + "Multi-line comment should be preserved when PreserveComments is true"); + + // Verify comment appears BEFORE the SELECT keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("/* This is a multi-line comment */"); + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < selectIndex, + $"Multi-line comment should appear before SELECT. Comment at {commentIndex}, SELECT at {selectIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_MultiLineBlockComment() + { + // Test that decorative patterns are preserved + var sqlWithComments = @"/***** Header Comment *****/ +SELECT 1;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Decorative pattern should be preserved exactly + Assert.IsTrue(generatedSql.Contains("/***** Header Comment *****/"), + "Decorative comment pattern should be preserved exactly"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_Subquery() + { + // Test comments with subqueries + var sqlWithComments = @"-- Outer query comment +SELECT * FROM ( + -- Inner subquery comment + SELECT id, name FROM users +) AS subq;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Outer comment should be preserved + Assert.IsTrue(generatedSql.Contains("-- Outer query comment"), + "Outer query comment should be preserved"); + + // Verify comment appears BEFORE the SELECT keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("-- Outer query comment"); + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < selectIndex, + $"Outer query comment should appear before SELECT. Comment at {commentIndex}, SELECT at {selectIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CTE() + { + // Test comments with Common Table Expressions + var sqlWithComments = @"-- CTE definition comment +WITH cte AS ( + SELECT id FROM users +) +-- Main query comment +SELECT * FROM cte;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // CTE comment should be preserved AND appear before the WITH keyword + Assert.IsTrue(generatedSql.Contains("-- CTE definition comment"), + "CTE definition comment should be preserved"); + + // Verify comment appears BEFORE the WITH keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("-- CTE definition comment"); + int withIndex = generatedSql.IndexOf("WITH", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < withIndex, + $"CTE comment should appear before WITH keyword. Comment at {commentIndex}, WITH at {withIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_InsertSelect() + { + // Test comments with INSERT...SELECT statements + var sqlWithComments = @"-- Insert with select comment +INSERT INTO target_table (col1, col2) +-- Select portion comment +SELECT a, b FROM source_table;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Insert comment should be preserved + Assert.IsTrue(generatedSql.Contains("-- Insert with select comment"), + "Insert statement comment should be preserved"); + + // Verify comment appears BEFORE the INSERT keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("-- Insert with select comment"); + int insertIndex = generatedSql.IndexOf("INSERT", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < insertIndex, + $"Insert comment should appear before INSERT. Comment at {commentIndex}, INSERT at {insertIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_StoredProcedure() + { + // Test comments within stored procedure body + var sqlWithComments = @"-- Procedure header comment +CREATE PROCEDURE TestProc +AS +BEGIN + -- First statement in proc + SELECT 1; + -- Second statement in proc + SELECT 2; +END;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Procedure header comment should be preserved + Assert.IsTrue(generatedSql.Contains("-- Procedure header comment"), + "Procedure header comment should be preserved"); + + // Verify comment appears BEFORE the CREATE keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("-- Procedure header comment"); + int createIndex = generatedSql.IndexOf("CREATE", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < createIndex, + $"Procedure comment should appear before CREATE. Comment at {commentIndex}, CREATE at {createIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_MixedCommentStyles() + { + // Test mixing single-line and multi-line comments + var sqlWithComments = @"/* Block comment at start */ +-- Single line after block +SELECT 1; /* inline block */ -- trailing single"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Both comment styles should be preserved + Assert.IsTrue(generatedSql.Contains("/* Block comment at start */"), + "Block comment should be preserved"); + Assert.IsTrue(generatedSql.Contains("-- Single line after block"), + "Single line comment should be preserved"); + + // Verify ordering: block comment -> single line comment -> SELECT + int blockCommentIndex = generatedSql.IndexOf("/* Block comment at start */"); + int singleLineIndex = generatedSql.IndexOf("-- Single line after block"); + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(blockCommentIndex < singleLineIndex, + "Block comment should appear before single-line comment"); + Assert.IsTrue(singleLineIndex < selectIndex, + "Single-line comment should appear before SELECT"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CreateTable() + { + // Test comments with CREATE TABLE statement + var sqlWithComments = @"-- Table creation comment +CREATE TABLE TestTable ( + -- Primary key column + Id INT PRIMARY KEY, + -- Name column + Name NVARCHAR(100) +);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Table creation comment should be preserved + Assert.IsTrue(generatedSql.Contains("-- Table creation comment"), + "Table creation comment should be preserved"); + + // Verify comment appears BEFORE the CREATE keyword (correct positioning) + int commentIndex = generatedSql.IndexOf("-- Table creation comment"); + int createIndex = generatedSql.IndexOf("CREATE", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(commentIndex < createIndex, + $"Table comment should appear before CREATE. Comment at {commentIndex}, CREATE at {createIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_EndOfScriptComment() + { + // Test comments at the very end of the script (after the last statement) + // This is an edge case: there's no "next fragment" to capture these as leading comments + var sqlWithComments = @"SELECT 1; +-- End of script comment"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // End-of-script comment should be preserved + Assert.IsTrue(generatedSql.Contains("-- End of script comment"), + "End-of-script comment should be preserved. Actual output: " + generatedSql); + + // Verify comment appears AFTER the SELECT (correct positioning) + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + int commentIndex = generatedSql.IndexOf("-- End of script comment"); + Assert.IsTrue(commentIndex > selectIndex, + $"End-of-script comment should appear after SELECT. SELECT at {selectIndex}, comment at {commentIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_EndOfScriptMultiLineComment() + { + // Test multi-line comments at the very end of the script + var sqlWithComments = @"SELECT 1; +/* End of script + multi-line comment */"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // End-of-script multi-line comment should be preserved + Assert.IsTrue(generatedSql.Contains("/* End of script"), + "End-of-script multi-line comment should be preserved. Actual output: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("multi-line comment */"), + "End-of-script multi-line comment should be complete"); + + // Verify comment appears AFTER the SELECT + int selectIndex = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + int commentIndex = generatedSql.IndexOf("/* End of script"); + Assert.IsTrue(commentIndex > selectIndex, + $"End-of-script comment should appear after SELECT. SELECT at {selectIndex}, comment at {commentIndex}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInWhereClause() + { + // Test comments within WHERE clause expressions + // This tests the improved centralized comment handling in GenerateFragmentIfNotNull + var sqlWithComments = @"SELECT id, name +FROM users +WHERE /* filter active users */ status = 'active';"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Comment in WHERE clause should be preserved + Assert.IsTrue(generatedSql.Contains("/* filter active users */"), + "Comment in WHERE clause should be preserved. Actual output: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInSelectList() + { + // Test comments within SELECT list (between columns) + var sqlWithComments = @"SELECT + id, -- primary key + name, -- user name + email -- contact info +FROM users;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // At least one of the column comments should be preserved + Assert.IsTrue( + generatedSql.Contains("-- primary key") || + generatedSql.Contains("-- user name") || + generatedSql.Contains("-- contact info"), + "At least one column comment should be preserved. Actual output: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInColumnDefinitions() + { + // Test comments inside column definitions in CREATE TABLE + var sqlWithComments = @"CREATE TABLE TestTable ( + -- Primary key column + Id INT NOT NULL, + -- User's full name + FullName NVARCHAR(100), + /* Email address for notifications */ + Email NVARCHAR(255), + -- Timestamp for auditing + CreatedDate DATETIME DEFAULT GETDATE() +);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Column definition comments should be preserved and in correct positions + Assert.IsTrue(generatedSql.Contains("-- Primary key column"), + "Primary key column comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- User's full name"), + "FullName column comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Email address for notifications */"), + "Email column block comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- Timestamp for auditing"), + "CreatedDate column comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear before their respective columns + int pkCommentIdx = generatedSql.IndexOf("-- Primary key column"); + int idColumnIdx = generatedSql.IndexOf("Id", StringComparison.OrdinalIgnoreCase); + int nameCommentIdx = generatedSql.IndexOf("-- User's full name"); + int fullNameColumnIdx = generatedSql.IndexOf("FullName", StringComparison.OrdinalIgnoreCase); + int emailCommentIdx = generatedSql.IndexOf("/* Email address for notifications */"); + int emailColumnIdx = generatedSql.IndexOf("Email", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(pkCommentIdx < idColumnIdx, + $"Primary key comment should appear before Id column. Comment at {pkCommentIdx}, Id at {idColumnIdx}"); + Assert.IsTrue(nameCommentIdx < fullNameColumnIdx, + $"FullName comment should appear before FullName column. Comment at {nameCommentIdx}, FullName at {fullNameColumnIdx}"); + Assert.IsTrue(emailCommentIdx < emailColumnIdx, + $"Email comment should appear before Email column. Comment at {emailCommentIdx}, Email at {emailColumnIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInCaseExpression() + { + // Test comments within CASE expressions + var sqlWithComments = @"SELECT + CASE + -- Check for high priority + WHEN priority = 1 THEN 'High' + /* Medium priority items */ + WHEN priority = 2 THEN 'Medium' + -- Default to low priority + ELSE 'Low' + END AS PriorityLevel +FROM tasks;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // CASE expression comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- Check for high priority"), + "High priority WHEN comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Medium priority items */"), + "Medium priority block comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- Default to low priority"), + "ELSE comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear before their respective WHEN/ELSE clauses + int highPriorityCommentIdx = generatedSql.IndexOf("-- Check for high priority"); + int firstWhenIdx = generatedSql.IndexOf("WHEN", StringComparison.OrdinalIgnoreCase); + int mediumCommentIdx = generatedSql.IndexOf("/* Medium priority items */"); + int secondWhenIdx = generatedSql.IndexOf("WHEN", firstWhenIdx + 1, StringComparison.OrdinalIgnoreCase); + int elseCommentIdx = generatedSql.IndexOf("-- Default to low priority"); + int elseIdx = generatedSql.IndexOf("ELSE", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(highPriorityCommentIdx < firstWhenIdx, + $"High priority comment should appear before first WHEN. Comment at {highPriorityCommentIdx}, WHEN at {firstWhenIdx}"); + Assert.IsTrue(mediumCommentIdx < secondWhenIdx, + $"Medium priority comment should appear before second WHEN. Comment at {mediumCommentIdx}, WHEN at {secondWhenIdx}"); + Assert.IsTrue(elseCommentIdx < elseIdx, + $"ELSE comment should appear before ELSE. Comment at {elseCommentIdx}, ELSE at {elseIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInJoinClauses() + { + // Test comments in JOIN clauses + var sqlWithComments = @"SELECT u.name, o.order_date +FROM users u +-- Join to get user orders +INNER JOIN orders o ON u.id = o.user_id +/* Left join for optional address */ +LEFT JOIN addresses a ON u.id = a.user_id +-- Cross join for all combinations +CROSS JOIN products p;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // JOIN clause comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- Join to get user orders"), + "INNER JOIN comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Left join for optional address */"), + "LEFT JOIN block comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- Cross join for all combinations"), + "CROSS JOIN comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear before their respective JOIN clauses + int innerJoinCommentIdx = generatedSql.IndexOf("-- Join to get user orders"); + int innerJoinIdx = generatedSql.IndexOf("INNER JOIN", StringComparison.OrdinalIgnoreCase); + int leftJoinCommentIdx = generatedSql.IndexOf("/* Left join for optional address */"); + int leftJoinIdx = generatedSql.IndexOf("LEFT", StringComparison.OrdinalIgnoreCase); + int crossJoinCommentIdx = generatedSql.IndexOf("-- Cross join for all combinations"); + int crossJoinIdx = generatedSql.IndexOf("CROSS JOIN", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(innerJoinCommentIdx < innerJoinIdx, + $"INNER JOIN comment should appear before INNER JOIN. Comment at {innerJoinCommentIdx}, JOIN at {innerJoinIdx}"); + Assert.IsTrue(leftJoinCommentIdx < leftJoinIdx, + $"LEFT JOIN comment should appear before LEFT JOIN. Comment at {leftJoinCommentIdx}, JOIN at {leftJoinIdx}"); + Assert.IsTrue(crossJoinCommentIdx < crossJoinIdx, + $"CROSS JOIN comment should appear before CROSS JOIN. Comment at {crossJoinCommentIdx}, JOIN at {crossJoinIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInWherePredicates() + { + // Test comments within WHERE clause predicates + var sqlWithComments = @"SELECT * FROM orders +WHERE + -- Filter by active status + status = 'active' + /* Date range filter */ + AND order_date >= '2024-01-01' + -- Exclude test orders + AND is_test = 0 + -- Amount threshold + AND amount > 100;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // WHERE predicate comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- Filter by active status"), + "Status filter comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Date range filter */"), + "Date range block comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- Exclude test orders"), + "Test orders exclusion comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- Amount threshold"), + "Amount threshold comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear before their respective predicates + int statusCommentIdx = generatedSql.IndexOf("-- Filter by active status"); + int statusPredicateIdx = generatedSql.IndexOf("status", StringComparison.OrdinalIgnoreCase); + int dateCommentIdx = generatedSql.IndexOf("/* Date range filter */"); + int datePredicateIdx = generatedSql.IndexOf("order_date", StringComparison.OrdinalIgnoreCase); + int testCommentIdx = generatedSql.IndexOf("-- Exclude test orders"); + int testPredicateIdx = generatedSql.IndexOf("is_test", StringComparison.OrdinalIgnoreCase); + int amountCommentIdx = generatedSql.IndexOf("-- Amount threshold"); + int amountPredicateIdx = generatedSql.IndexOf("amount", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(statusCommentIdx < statusPredicateIdx, + $"Status comment should appear before status predicate. Comment at {statusCommentIdx}, predicate at {statusPredicateIdx}"); + Assert.IsTrue(dateCommentIdx < datePredicateIdx, + $"Date comment should appear before order_date predicate. Comment at {dateCommentIdx}, predicate at {datePredicateIdx}"); + Assert.IsTrue(testCommentIdx < testPredicateIdx, + $"Test orders comment should appear before is_test predicate. Comment at {testCommentIdx}, predicate at {testPredicateIdx}"); + Assert.IsTrue(amountCommentIdx < amountPredicateIdx, + $"Amount comment should appear before amount predicate. Comment at {amountCommentIdx}, predicate at {amountPredicateIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInGroupByHaving() + { + // Test comments in GROUP BY and HAVING clauses + var sqlWithComments = @"SELECT department, COUNT(*) as emp_count +FROM employees +-- Group by department +GROUP BY department +/* Filter groups with more than 5 employees */ +HAVING COUNT(*) > 5;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // GROUP BY and HAVING comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- Group by department"), + "GROUP BY comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Filter groups with more than 5 employees */"), + "HAVING block comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear before their respective clauses + int groupByCommentIdx = generatedSql.IndexOf("-- Group by department"); + int groupByIdx = generatedSql.IndexOf("GROUP BY", StringComparison.OrdinalIgnoreCase); + int havingCommentIdx = generatedSql.IndexOf("/* Filter groups with more than 5 employees */"); + int havingIdx = generatedSql.IndexOf("HAVING", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(groupByCommentIdx < groupByIdx, + $"GROUP BY comment should appear before GROUP BY. Comment at {groupByCommentIdx}, GROUP BY at {groupByIdx}"); + Assert.IsTrue(havingCommentIdx < havingIdx, + $"HAVING comment should appear before HAVING. Comment at {havingCommentIdx}, HAVING at {havingIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInOrderBy() + { + // Test comments in ORDER BY clause + var sqlWithComments = @"SELECT name, created_date, priority +FROM tasks +ORDER BY + -- Primary sort: highest priority first + priority ASC, + /* Secondary sort: newest first */ + created_date DESC;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // ORDER BY comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- Primary sort: highest priority first"), + "Primary sort comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Secondary sort: newest first */"), + "Secondary sort block comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear before their respective sort columns + int primarySortCommentIdx = generatedSql.IndexOf("-- Primary sort: highest priority first"); + int orderByIdx = generatedSql.IndexOf("ORDER BY", StringComparison.OrdinalIgnoreCase); + // Find priority AFTER ORDER BY (since it also appears in SELECT list) + int priorityInOrderByIdx = generatedSql.IndexOf("priority", orderByIdx, StringComparison.OrdinalIgnoreCase); + int secondarySortCommentIdx = generatedSql.IndexOf("/* Secondary sort: newest first */"); + // Find created_date AFTER ORDER BY (since it also appears in SELECT list) + int createdDateInOrderByIdx = generatedSql.IndexOf("created_date", orderByIdx, StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(primarySortCommentIdx > orderByIdx && primarySortCommentIdx < priorityInOrderByIdx, + $"Primary sort comment should appear between ORDER BY and priority. ORDER BY at {orderByIdx}, Comment at {primarySortCommentIdx}, priority at {priorityInOrderByIdx}"); + Assert.IsTrue(secondarySortCommentIdx < createdDateInOrderByIdx, + $"Secondary sort comment should appear before created_date column. Comment at {secondarySortCommentIdx}, created_date at {createdDateInOrderByIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInUnionQueries() + { + // Test comments between UNION queries + var sqlWithComments = @"-- First query: active users +SELECT id, name FROM users WHERE status = 'active' +/* Combine with archived users */ +UNION ALL +-- Second query: archived users +SELECT id, name FROM archived_users;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // UNION query comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- First query: active users"), + "First query comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Combine with archived users */"), + "UNION block comment should be preserved. Actual: " + generatedSql); + + // Verify position: comments should appear at correct positions relative to queries + int firstQueryCommentIdx = generatedSql.IndexOf("-- First query: active users"); + int firstSelectIdx = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); + int unionCommentIdx = generatedSql.IndexOf("/* Combine with archived users */"); + int unionIdx = generatedSql.IndexOf("UNION", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(firstQueryCommentIdx < firstSelectIdx, + $"First query comment should appear before first SELECT. Comment at {firstQueryCommentIdx}, SELECT at {firstSelectIdx}"); + Assert.IsTrue(unionCommentIdx < unionIdx, + $"UNION comment should appear before UNION. Comment at {unionCommentIdx}, UNION at {unionIdx}"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_CommentInNestedSubquery() + { + // Test comments in deeply nested subqueries + var sqlWithComments = @"SELECT * FROM ( + -- Outer subquery + SELECT * FROM ( + /* Inner subquery */ + SELECT id, name FROM users + ) AS inner_q +) AS outer_q;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Nested subquery comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- Outer subquery"), + "Outer subquery comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("/* Inner subquery */"), + "Inner subquery block comment should be preserved. Actual: " + generatedSql); + + // Verify position: outer comment before inner comment (based on nesting order) + int outerCommentIdx = generatedSql.IndexOf("-- Outer subquery"); + int innerCommentIdx = generatedSql.IndexOf("/* Inner subquery */"); + int innerQAliasIdx = generatedSql.IndexOf("inner_q", StringComparison.OrdinalIgnoreCase); + int outerQAliasIdx = generatedSql.IndexOf("outer_q", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(outerCommentIdx < innerCommentIdx, + $"Outer subquery comment should appear before inner subquery comment. Outer at {outerCommentIdx}, inner at {innerCommentIdx}"); + Assert.IsTrue(innerCommentIdx < innerQAliasIdx, + $"Inner subquery comment should appear before inner_q alias. Comment at {innerCommentIdx}, alias at {innerQAliasIdx}"); + Assert.IsTrue(innerQAliasIdx < outerQAliasIdx, + $"inner_q alias should appear before outer_q alias. inner_q at {innerQAliasIdx}, outer_q at {outerQAliasIdx}"); + } + + #endregion } } diff --git a/Test/SqlDom/TestScripts/MultiLineCommentTests170.sql b/Test/SqlDom/TestScripts/MultiLineCommentTests170.sql new file mode 100644 index 00000000..016dd73f --- /dev/null +++ b/Test/SqlDom/TestScripts/MultiLineCommentTests170.sql @@ -0,0 +1,16 @@ +/* Leading multi-line comment */ +SELECT 1; + +/* + * Multi-line block comment + * with multiple lines + */ +SELECT 2; + +SELECT 3; /* Trailing multi-line comment */ + +/***** Decorative header *****/ +SELECT 4; + +/* Empty multi-line comment */ +SELECT 5; diff --git a/Test/SqlDom/TestScripts/SingleLineCommentTests170.sql b/Test/SqlDom/TestScripts/SingleLineCommentTests170.sql new file mode 100644 index 00000000..66e077db --- /dev/null +++ b/Test/SqlDom/TestScripts/SingleLineCommentTests170.sql @@ -0,0 +1,14 @@ +-- Leading comment before SELECT +SELECT 1; -- Trailing comment after SELECT + +-- Comment before table reference +SELECT * FROM dbo.MyTable; -- End of line comment + +-- Multiple leading comments +-- Second leading comment +SELECT 2; + +-- Comment between statements +SELECT 3; +-- Another comment +SELECT 4; From c6e10b2831b58c0abbea64ac313f25c07cf64541 Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Fri, 13 Feb 2026 12:25:28 -0800 Subject: [PATCH 20/45] Sync Repos: Release 170.168.0 (#190) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Merged PR 1952906: JSON_ARRAYAGG support for OVER clause # Pull Request Template for ScriptDom ## Description `JSON_ARRAYAGG` supports windowed aggregate usage via the `OVER (PARTITION BY ...)` clause in SQL Server, but ScriptDOM was missing support for parsing and generating it. This PR adds OVER clause support for `JSON_ARRAYAGG` in the TSql170 parser and script generator. **SQL syntax now supported:** ```sql SELECT JSON_ARRAYAGG(name) OVER (PARTITION BY dept) FROM employees; SELECT JSON_ARRAYAGG(name ABSENT ON NULL) OVER (PARTITION BY dept) FROM employees; SELECT JSON_ARRAYAGG(name NULL ON NULL) OVER (PARTITION BY dept) FROM employees; SELECT JSON_ARRAYAGG(name ORDER BY name NULL ON NULL RETURNING JSON) OVER (PARTITION BY dept) FROM employees; ``` * Merged PR 1948594: Fix allocation issue in TSql80ParserBaseInternal.AddAndUpdateTokenInfo High memory allocations were detected in the `TSql80ParserBaseInternal.AddAndUpdateTokenInfo` method, specifically in the overload that processes collections. The method uses a `foreach` loop to iterate over an `IList` collection, which causes the allocation of a boxed `List.Enumerator` object on every invocation. Since this is a hot path in the SQL parser (called frequently during parsing operations), these repeated allocations contribute significantly to GC pressure. Performance impact: This issue appears in 0.28% of high allocation traces and allocates 3.0 MB/sec at both the 50th and 90th percentiles. ## Solution Replaced the `foreach` loop with an index-based `for` loop in the `AddAndUpdateTokenInfo` method. The new implementation iterates using an integer index from 0 to `otherCollection.Count`, accessing each element via the indexer. This eliminates the enumerator allocation while preserving identical functionality and behavior. The change is made in `/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs` at lines 292-299. **Before:** ```csharp foreach (TFragmentType item in otherCollection) { AddAndUpdateTokenInfo(node, collection, item); } ``` **After:** ```csharp for (int i = 0; i < otherCollection.Count; i++) { TFragmentType item = otherCollection[i]; AddAndUpdateTokenInfo(node, collection, item); } ``` ## Benefits - Eliminates boxing allocation of `List.Enumerator` on hot path - Reduces GC pressure and improves parser performance - Maintains identical behavior and semantics - Minimal code change with no API modifications * Merged PR 1881483: Add support for 3-part and 4-part identifiers in VECTOR_SEARCH TOP_N parameter ## Summary This PR enables the VECTOR_SEARCH table-valued function to accept 3-part and 4-part column identifiers in the TOP_N parameter, allowing queries like: ```sql SELECT qt.qid, src.id, ann.distance FROM QueryTable qt CROSS APPLY VECTOR_SEARCH( TABLE = graphnode AS src, COLUMN = embedding, SIMILAR_TO = qt.qembedding, METRIC = 'euclidean', TOP_N = dbo.qt.top_n -- 3-part identifier now supported ) AS ann ``` Previously, the parser only accepted up to 2-part identifiers (e.g., `qt.top_n`) in the TOP_N parameter, which prevented queries using schema-qualified column references in CROSS APPLY scenarios. ## Changes Made ### Grammar Rule Update Modified the `vectorSearchColumnReferenceExpression` rule in `SqlScriptDom/Parser/TSql/TSql170.g` to allow up to 4-part identifiers instead of the previous 2-part limit. This change enables the TOP_N parameter to accept: - Simple identifiers: `@variable` or `columnName` - 2-part identifiers: `table.column` - 3-part identifiers: `schema.table.column` (the primary use case from the issue) - 4-part identifiers: `database.schema.table.column` The change was minimal—updating a single parameter from `multiPartIdentifier[2]` to `multiPartIdentifier[4]` in line 33971 of TSql170.g. This aligns with standard SQL Server column reference behavior in other contexts. ### Test Coverage Added comprehensive test coverage in `Test/SqlDom/TestScripts/VectorSearchCrossApplyTests170.sql` with a test case that validates the exact query pattern from the issue. The test includes: - A DECLARE statement setting up a VECTOR variable - A SELECT query with CROSS APPLY using VECTOR_SEARCH - The TOP_N parameter specified as a 3-part identifier (`dbo.qt.top_n`) The corresponding baseline file `Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql` captures the expected formatted output from the parser. Updated `Test/SqlDom/Only170SyntaxTests.cs` to register the new test case with appropriate error counts for older parser versions (TSql80 through TSql160), which still use the 2-part identifier limit and correctly report parse errors for this syntax. ## Impact This change only affects the TSql170 (SQL Server 2025) parser and is backward compatible. The AST definition already used `ScalarExpression` for the TopN member, so no AST changes were required. Older parser versions continue to enforce the 2-part identifier limit and generate expected parse errors for 3-part identifiers. The fix enables real-world scenarios where VECTOR_SEARCH is used in CROSS APPLY with outer references that require schema qualification, which is common in production databases with explicit schema naming conventions. Fixes: #4843961 * Merged PR 1881565: ## Fix VECTOR_SEARCH SIMILAR_TO Parameter to Reject Subqueries ### Summary The VECTOR_SEARCH function in the TSql170 parser was incorrectly allowing subqueries in the SIMILAR_TO parameter. This fix adds validation to properly reject subqueries and throw an appropriate parse error, aligning with SQL Server 2025 implementation requirements. ### Problem The SIMILAR_TO parameter was accepting any scalar expression, including subqueries wrapped in parentheses. This allowed invalid syntax like: ```sql SELECT * FROM VECTOR_SEARCH( TABLE = graphnode, COLUMN = embedding, SIMILAR_TO = (SELECT TOP 1 embedding FROM GTQuery), -- Should error but didn't METRIC = 'euclidean', TOP_N = 20 ) AS ann ``` This syntax should be rejected because subqueries are not supported in the SIMILAR_TO parameter, similar to how they are restricted in other contexts. ### Solution Added validation logic in the `vectorSearchTableReference` grammar rule (`SqlScriptDom/Parser/TSql/TSql170.g`) that checks if the SIMILAR_TO expression is a `ScalarSubquery` type. When detected, the parser now throws a SQL46098 error with the message "Subqueries are not allowed in this context. Only scalar expressions are allowed." The validation follows the same pattern used elsewhere in the grammar for similar restrictions and is placed immediately after matching the SIMILAR_TO identifier, before assigning the expression to the result object. ### Testing Added a comprehensive error test case in `Test/SqlDom/ParserErrorsTests.cs` within the existing `VectorSearchErrorTest170` method. The test verifies that: - Subqueries in the SIMILAR_TO parameter are properly rejected - The correct error code (SQL46098) is generated - The error position is accurately reported Valid syntax continues to work correctly, including: - Variables: `SIMILAR_TO = @qv` - Column references: `SIMILAR_TO = outerref.vector_col` - Other scalar expressions that are not subqueries ### Impact - **All 558 existing tests pass** with no regressions - **Minimal change**: Only 12 lines added across 2 files - **Consistent behavior**: Uses the same error code and message pattern as other subquery restrictions in the parser - **Backward compatible**: Only rejects previously invalid syntax that should not have been allowed Fixes: #4844065 Related work items: #4844065 * Merged PR 1959169: Adding release notes for 170.168.0 # Pull Request Template for ScriptDom ## Description Please provide a detailed description, include the link to the design specification or SQL feature document for the new TSQL syntaxes. Make sure to add links to the Github or DevDiv issue Before submitting your pull request, please ensure you have completed the following: ## Code Change - [ ] The [Common checklist](https://msdata.visualstudio.com/SQLToolsAndLibraries/_git/Common?path=/Templates/PR%20Checklist%20for%20SQLToolsAndLibraries.md&version=GBmain&_a=preview) has been reviewed and followed - [ ] Code changes are accompanied by appropriate unit tests - [ ] Identified and included SMEs needed to review code changes - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=make-the-changes-in) here to make changes in the code ## Testing - [ ] Follow the [steps](https://msdata.visualstudio.com/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki/33838/Adding-or-Extending-TSql-support-in-Sql-Dom?anchor=to-extend-the-tests-do-the-following%3A) here to add new tests for your feature ## Documentation - [ ] Update relevant documentation in the [wiki](https://dev.azure.com/msdata/SQLToolsAndLibraries/_wiki/wikis/SQLToolsAndLibraries.wiki) and the README.md file ## Additional Information Please provide any additional information that might be helpful for the reviewers Adding release notes for 170.168.0 --------- Co-authored-by: Shiv Prashant Sood Co-authored-by: GitHub Copilot --- SqlScriptDom/Parser/TSql/TSql170.g | 16 +++++++++++- .../Parser/TSql/TSql80ParserBaseInternal.cs | 3 ++- .../SqlScriptGeneratorVisitor.FunctionCall.cs | 10 ++++--- .../Baselines170/JsonArrayAggOrderBy170.sql | 14 +++++++++- .../Baselines170/VectorFunctionTests170.sql | 2 +- .../VectorSearchCrossApplyTests170.sql | 12 +++++++++ Test/SqlDom/Only170SyntaxTests.cs | 3 ++- Test/SqlDom/ParserErrorsTests.cs | 5 ++++ .../TestScripts/JsonArrayAggOrderBy170.sql | 14 +++++++++- .../TestScripts/VectorFunctionTests170.sql | 2 +- .../VectorSearchCrossApplyTests170.sql | 12 +++++++++ release-notes/170/170.168.0.md | 26 +++++++++++++++++++ 12 files changed, 108 insertions(+), 11 deletions(-) create mode 100644 Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql create mode 100644 Test/SqlDom/TestScripts/VectorSearchCrossApplyTests170.sql create mode 100644 release-notes/170/170.168.0.md diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index b793bf56..85ec9cf4 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -19306,6 +19306,13 @@ vectorSearchTableReference returns [VectorSearchTableReference vResult = Fragmen Comma tSimilarTo:Identifier EqualsSign vSimilarTo = expression { Match(tSimilarTo, CodeGenerationSupporter.SimilarTo); + + // Validate that SIMILAR_TO does not contain a subquery + if (vSimilarTo is ScalarSubquery) + { + ThrowParseErrorException("SQL46098", vSimilarTo, TSqlParserResource.SQL46098Message); + } + vResult.SimilarTo = vSimilarTo; } Comma tMetric:Identifier EqualsSign vMetric = stringLiteral @@ -33104,6 +33111,7 @@ jsonArrayAggBuiltInFunctionCall [FunctionCall vParent] { ScalarExpression vExpression; OrderByClause vOrderByClause; + OverClause vOverClause; } : ( vExpression=expression @@ -33133,6 +33141,12 @@ jsonArrayAggBuiltInFunctionCall [FunctionCall vParent] { UpdateTokenInfo(vParent, tRParen); } + ( + vOverClause=overClauseNoOrderBy + { + vParent.OverClause = vOverClause; + } + )? ; jsonObjectBuiltInFunctionCall [FunctionCall vParent] @@ -33980,7 +33994,7 @@ vectorSearchColumnReferenceExpression returns [ColumnReferenceExpression vResult MultiPartIdentifier vMultiPartIdentifier; } : - vMultiPartIdentifier=multiPartIdentifier[2] + vMultiPartIdentifier=multiPartIdentifier[4] { vResult.ColumnType = ColumnType.Regular; vResult.MultiPartIdentifier = vMultiPartIdentifier; diff --git a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs index a17fe591..4f474299 100644 --- a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs @@ -292,8 +292,9 @@ protected static void AddAndUpdateTokenInfo(TSqlFragment node, IL protected static void AddAndUpdateTokenInfo(TSqlFragment node, IList collection, IList otherCollection) where TFragmentType : TSqlFragment { - foreach (TFragmentType item in otherCollection) + for (int i = 0; i < otherCollection.Count; i++) { + TFragmentType item = otherCollection[i]; AddAndUpdateTokenInfo(node, collection, item); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs index 20de09c6..70d7111c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs @@ -94,6 +94,8 @@ public override void ExplicitVisit(FunctionCall node) GenerateSpace(); GenerateReturnType(node?.ReturnType); GenerateSymbol(TSqlTokenType.RightParenthesis); + // Generate OVER clause for windowed json_arrayagg + GenerateSpaceAndFragmentIfNotNull(node.OverClause); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonQuery) { @@ -115,10 +117,10 @@ public override void ExplicitVisit(FunctionCall node) else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonValue) { GenerateCommaSeparatedList(node.Parameters); - if (node.ReturnType?.Count > 0) //If there are return types then generate space and return type clause - { - GenerateSpace(); - GenerateReturnType(node?.ReturnType); + if (node.ReturnType?.Count > 0) //If there are return types then generate space and return type clause + { + GenerateSpace(); + GenerateReturnType(node?.ReturnType); } GenerateSymbol(TSqlTokenType.RightParenthesis); } diff --git a/Test/SqlDom/Baselines170/JsonArrayAggOrderBy170.sql b/Test/SqlDom/Baselines170/JsonArrayAggOrderBy170.sql index d2ab25fe..8d8beef9 100644 --- a/Test/SqlDom/Baselines170/JsonArrayAggOrderBy170.sql +++ b/Test/SqlDom/Baselines170/JsonArrayAggOrderBy170.sql @@ -16,4 +16,16 @@ FROM data; SELECT TOP (5) c.object_id, JSON_ARRAYAGG(c.name ORDER BY c.column_id) AS column_list FROM sys.columns AS c -GROUP BY c.object_id; \ No newline at end of file +GROUP BY c.object_id; + +SELECT JSON_ARRAYAGG(name) OVER (PARTITION BY dept) +FROM employees; + +SELECT JSON_ARRAYAGG(name ABSENT ON NULL) OVER (PARTITION BY dept) +FROM employees; + +SELECT JSON_ARRAYAGG(name NULL ON NULL) OVER (PARTITION BY dept) +FROM employees; + +SELECT JSON_ARRAYAGG(name ORDER BY name NULL ON NULL RETURNING JSON) OVER (PARTITION BY dept) +FROM employees; \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/VectorFunctionTests170.sql b/Test/SqlDom/Baselines170/VectorFunctionTests170.sql index 9ab5f853..95e076d0 100644 --- a/Test/SqlDom/Baselines170/VectorFunctionTests170.sql +++ b/Test/SqlDom/Baselines170/VectorFunctionTests170.sql @@ -45,4 +45,4 @@ WHERE outerref.id IN (SELECT src.id SIMILAR_TO = @qv, METRIC = 'cosine', TOP_N = outerref.max_results - ) AS ann); \ No newline at end of file + ) AS ann); diff --git a/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql b/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql new file mode 100644 index 00000000..3e715b61 --- /dev/null +++ b/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql @@ -0,0 +1,12 @@ +DECLARE @qv AS VECTOR(1536); + +SELECT qt.qid, + src.id, + ann.distance +FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = dbo.qt.top_n + ) AS ann; diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index b4c10620..a881c8ef 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -20,7 +20,7 @@ public partial class SqlDomTests new ParserTest170("RegexpTests170.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), new ParserTest170("AiGenerateChunksTests170.sql", nErrors80: 19, nErrors90: 16, nErrors100: 15, nErrors110: 15, nErrors120: 15, nErrors130: 15, nErrors140: 15, nErrors150: 15, nErrors160: 15), new ParserTest170("JsonFunctionTests170.sql", nErrors80: 29, nErrors90: 8, nErrors100: 54, nErrors110: 54, nErrors120: 54, nErrors130: 54, nErrors140: 54, nErrors150: 54, nErrors160: 54), - new ParserTest170("JsonArrayAggOrderBy170.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6), + new ParserTest170("JsonArrayAggOrderBy170.sql", nErrors80: 10, nErrors90: 9, nErrors100: 9, nErrors110: 9, nErrors120: 9, nErrors130: 9, nErrors140: 9, nErrors150: 9, nErrors160: 9), new ParserTest170("ComplexJsonObjectFunctionTests170.sql"), new ParserTest170("AiGenerateEmbeddingsTests170.sql", nErrors80: 14, nErrors90: 11, nErrors100: 11, nErrors110: 11, nErrors120: 11, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11), new ParserTest170("CreateExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), @@ -32,6 +32,7 @@ public partial class SqlDomTests new ParserTest170("RegexpLikeTests170.sql", nErrors80: 15, nErrors90: 15, nErrors100: 15, nErrors110: 18, nErrors120: 18, nErrors130: 18, nErrors140: 18, nErrors150: 18, nErrors160: 18), new ParserTest170("OptimizedLockingTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), new ParserTest170("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), + new ParserTest170("VectorSearchCrossApplyTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1, nErrors160: 1), // Complex query with VECTOR types - parses syntactically in all versions (optimization fix), but VECTOR type only valid in TSql170 new ParserTest170("ComplexQueryTests170.sql"), // Comment preservation tests - basic SQL syntax works in all versions diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 2204c307..5a89afe1 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -7544,6 +7544,11 @@ public void VectorSearchErrorTest170() ParserTestUtils.ErrorTest170( "SELECT * FROM VECTOR_SEARCH('tbl1', 'col1', 'query_vector', 'dot', 5)", new ParserErrorInfo(28, "SQL46010", "'tbl1'")); + + // Subquery not allowed in SIMILAR_TO parameter + ParserTestUtils.ErrorTest170( + "SELECT * FROM VECTOR_SEARCH(TABLE = graphnode, COLUMN = embedding, SIMILAR_TO = (SELECT TOP 1 embedding FROM GTQuery), METRIC = 'euclidean', TOP_N = 20) AS ann", + new ParserErrorInfo(80, "SQL46098")); } /// diff --git a/Test/SqlDom/TestScripts/JsonArrayAggOrderBy170.sql b/Test/SqlDom/TestScripts/JsonArrayAggOrderBy170.sql index 094fb21d..5062e67b 100644 --- a/Test/SqlDom/TestScripts/JsonArrayAggOrderBy170.sql +++ b/Test/SqlDom/TestScripts/JsonArrayAggOrderBy170.sql @@ -18,4 +18,16 @@ SELECT JSON_ARRAYAGG(value ORDER BY value NULL ON NULL) FROM data; -- Real-world example with GROUP BY and system tables SELECT TOP(5) c.object_id, JSON_ARRAYAGG(c.name ORDER BY c.column_id) AS column_list FROM sys.columns AS c -GROUP BY c.object_id; \ No newline at end of file +GROUP BY c.object_id; + +-- JSON_ARRAYAGG with OVER clause (PARTITION BY) +SELECT JSON_ARRAYAGG(name) OVER (PARTITION BY dept) FROM employees; + +-- JSON_ARRAYAGG with ABSENT ON NULL and OVER clause +SELECT JSON_ARRAYAGG(name ABSENT ON NULL) OVER (PARTITION BY dept) FROM employees; + +-- JSON_ARRAYAGG with NULL ON NULL and OVER clause +SELECT JSON_ARRAYAGG(name NULL ON NULL) OVER (PARTITION BY dept) FROM employees; + +-- JSON_ARRAYAGG with ORDER BY, NULL ON NULL, RETURNING JSON, and OVER clause +SELECT JSON_ARRAYAGG(name ORDER BY name NULL ON NULL RETURNING JSON) OVER (PARTITION BY dept) FROM employees; \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/VectorFunctionTests170.sql b/Test/SqlDom/TestScripts/VectorFunctionTests170.sql index a06f083f..76795ae9 100644 --- a/Test/SqlDom/TestScripts/VectorFunctionTests170.sql +++ b/Test/SqlDom/TestScripts/VectorFunctionTests170.sql @@ -52,4 +52,4 @@ WHERE outerref.id IN ( METRIC = 'cosine', TOP_N = outerref.max_results ) AS ann -) \ No newline at end of file +) diff --git a/Test/SqlDom/TestScripts/VectorSearchCrossApplyTests170.sql b/Test/SqlDom/TestScripts/VectorSearchCrossApplyTests170.sql new file mode 100644 index 00000000..71dfcc53 --- /dev/null +++ b/Test/SqlDom/TestScripts/VectorSearchCrossApplyTests170.sql @@ -0,0 +1,12 @@ +DECLARE @qv VECTOR(1536); + +SELECT qt.qid, src.id, ann.distance +FROM QueryTable qt +CROSS APPLY + VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = dbo.qt.top_n + ) AS ann diff --git a/release-notes/170/170.168.0.md b/release-notes/170/170.168.0.md new file mode 100644 index 00000000..1f4253bd --- /dev/null +++ b/release-notes/170/170.168.0.md @@ -0,0 +1,26 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 170.168.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates .NET SDK to latest patch version 8.0.415 + +#### .NET Framework +#### .NET Core + +### New Features +* Adds formatter option for preserving comments + +### Fixed +* Fixes parsing VECTOR_SEARCH SIMILAR_TO parameter to reject subquery. +* Fixes parsing VECTOR_SEARCH TOP_N parameter to support multi-part indentifier. +### Changes + +### Known Issues From a54bcd5f573d2e302df067c87506132d3ead42e1 Mon Sep 17 00:00:00 2001 From: Sai Avishkar Sreerama <74571829+ssreerama@users.noreply.github.com> Date: Thu, 5 Mar 2026 15:21:50 -0600 Subject: [PATCH 21/45] Sync Repos: Release 170.179.0 (#192) * JSON_OBJECTAGG support for OVER clause ## Description JSON_OBJECTAGG supports windowed aggregate usage via the OVER (PARTITION BY ...) clause in SQL Server, but ScriptDOM was missing support for parsing and generating it. This PR adds OVER clause support for JSON_OBJECTAGG in the TSql170 parser and script generator. SQL syntax now supported: `sql SELECT JSON_OBJECTAGG(CustomerName:OrderDate) OVER (PARTITION BY OrderDate) FROM Customers; SELECT JSON_OBJECTAGG(CustomerName:OrderDate ABSENT ON NULL) OVER (PARTITION BY OrderDate) FROM Customers; SELECT JSON_OBJECTAGG(CustomerName:OrderDate NULL ON NULL) OVER (PARTITION BY OrderDate) FROM Customers; SELECT JSON_OBJECTAGG(CustomerName:OrderDate NULL ON NULL RETURNING JSON) OVER (PARTITION BY OrderDate) FROM Customers; ` ## Changes - Updated JSON_OBJECTAGG production in TSql170.g to optionally parse an OVER clause - Enhanced SqlScriptGeneratorVisitor.FunctionCall.cs to generate the OVER clause in the output - Added new baseline and test scripts (JsonObjectAggOverClause170.sql in both Baselines170 and TestScripts) ## Additional Information No AST changes were needed -- FunctionCall.OverClause already exists in Ast.xml. The grammar uses overClauseNoOrderBy (not overClause) since, like regular aggregates (e.g., SUM() OVER (...)), the ORDER BY within the OVER clause is not applicable for JSON_OBJECTAGG as a windowed aggregate. All older parsers (80-160) produce 4 errors each (one per test statement) since the JSON_OBJECTAGG key:value syntax is not recognized pre-TSql170. * [SECURITY] Bump dotnet-sdk from 8.0.415 to 8.0.418 * Fix: Make VECTOR_SEARCH TOP_N parameter optional and add WITH (FORCE_ANN_ONLY) support ## Summary Fixes ScriptDOM parser to correctly handle optional `TOP_N` parameter and `WITH (FORCE_ANN_ONLY)` query hint in `VECTOR_SEARCH` syntax, aligning with SQL Server 2025 behavior. ## Changes **Grammar (TSql170.g)** - Made `TOP_N` parameter optional - Added `WITH (FORCE_ANN_ONLY)` clause parsing **AST & Script Generator** - Added `ForceAnnOnly` boolean to `VectorSearchTableReference` - Updated script generator for nullable `TOP_N` and `WITH` clause output - Full round-trip fidelity maintained **Tests** - Added `VectorSearchOptionalTopNTests170.sql` (4 test scenarios) - Removed obsolete error test expecting mandatory `TOP_N` ## Example Syntax Now Supported ```sql -- Without TOP_N SELECT * FROM VECTOR_SEARCH(...) AS ann -- With query hint SELECT * FROM VECTOR_SEARCH(...) WITH (FORCE_ANN_ONLY) AS ann -- With TOP_N (backward compatible) SELECT * FROM VECTOR_SEARCH(..., TOP_N = 10) AS ann ``` Backward compatible - No breaking changes. * Simplifies CREATE/ALTER EXTERNAL DATA SOURCE syntax for Fabric DW Simplifies CREATE/ALTER EXTERNAL DATA SOURCE syntax for Fabric DW to only support the LOCATION parameter, removing support for TYPE, PUSHDOWN, and other literal/ identifier options in the Fabric DW parser. Added positive and negative tests for this based on the specification. * Adding release notes for 170.179.0 --- .../testing.guidelines.instructions.md | 57 +++++- .gitignore | 13 +- SqlScriptDom/Parser/TSql/Ast.xml | 1 + .../Parser/TSql/CodeGenerationSupporter.cs | 1 + SqlScriptDom/Parser/TSql/TSql170.g | 43 +++-- SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 166 +----------------- .../SqlScriptGeneratorVisitor.FunctionCall.cs | 2 + ...ratorVisitor.VectorSearchTableReference.cs | 29 ++- .../JsonObjectAggOverClause170.sql | 11 ++ .../VectorSearchOptionalTopNTests170.sql | 33 ++++ ...teAlterExternalDataSourceTestsFabricDW.sql | 11 ++ Test/SqlDom/Only170SyntaxTests.cs | 2 + Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 3 +- Test/SqlDom/ParserErrorsTests.cs | 71 +++++++- ...teAlterExternalDataSourceTestsFabricDW.sql | 11 ++ .../JsonObjectAggOverClause170.sql | 11 ++ .../VectorSearchOptionalTopNTests170.sql | 33 ++++ global.json | 2 +- release-notes/170/170.179.0.md | 28 +++ 19 files changed, 334 insertions(+), 194 deletions(-) create mode 100644 Test/SqlDom/Baselines170/JsonObjectAggOverClause170.sql create mode 100644 Test/SqlDom/Baselines170/VectorSearchOptionalTopNTests170.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/CreateAlterExternalDataSourceTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/CreateAlterExternalDataSourceTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/JsonObjectAggOverClause170.sql create mode 100644 Test/SqlDom/TestScripts/VectorSearchOptionalTopNTests170.sql create mode 100644 release-notes/170/170.179.0.md diff --git a/.github/instructions/testing.guidelines.instructions.md b/.github/instructions/testing.guidelines.instructions.md index ec628119..5b1b4770 100644 --- a/.github/instructions/testing.guidelines.instructions.md +++ b/.github/instructions/testing.guidelines.instructions.md @@ -321,6 +321,25 @@ Expected: 'SELECT JSON_ARRAY('value1', 'value2');' **Solution**: Copy the "Actual" output to your baseline file (note spacing differences). +**CRITICAL CHECK**: After copying baseline, compare it against your test script: +```sql +-- Input script (TestScripts/MyTest.sql) +SELECT * FROM FUNC() WITH (HINT); + +-- Generated baseline (Baselines170/MyTest.sql) +SELECT * +FROM FUNC(); +-- ⚠️ WHERE IS 'WITH (HINT)'? +``` + +**If baseline is missing syntax from input:** +1. **This is likely a BUG** - not just formatting difference +2. Check if AST has member to store the missing syntax +3. Verify grammar stores value: `vResult.PropertyName = vValue;` +4. Check script generator outputs the value: `GenerateFragmentIfNotNull(node.Property)` +5. If syntax should be preserved, add AST storage and script generation +6. Document in spec if intentional omission (e.g., query optimizer hints) + #### 2. Error Count Mismatch ``` TestYourFeature.sql: number of errors after parsing is different from expected. @@ -800,6 +819,38 @@ new ParserTest160("RegressionBugFix12345Tests160.sql", nErrors150: 1), // Bug e new ParserTest170("RegressionBugFix12345Tests170.sql", nErrors160: 1), // Bug existed in SQL 2022 ``` +## Round-Trip Fidelity Validation Checklist + +**CRITICAL: After generating baseline files, ALWAYS verify:** + +✅ **Input Preservation Check**: +1. Open test script side-by-side with baseline file +2. For each SQL statement, verify baseline preserves all syntax from input +3. Check optional clauses: `WITH`, `WHERE`, `HAVING`, `ORDER BY`, etc. +4. Check hints: Table hints, query hints, join hints +5. Check keywords: All keywords from input should appear in baseline (unless documented normalization) + +✅ **Missing Syntax Investigation**: +If baseline omits syntax from input: +- [ ] Is this intentional keyword normalization? (e.g., APPROX → APPROXIMATE) +- [ ] Is this a query optimizer hint that doesn't need preservation? +- [ ] Is this a BUG where AST doesn't store the value? + +✅ **Bug Indicators**: +- ❌ Input: `FUNCTION() WITH (HINT)` → Baseline: `FUNCTION()` = **LIKELY BUG** +- ❌ Input: `SELECT ... ORDER BY col` → Baseline: `SELECT ...` = **BUG** +- ✅ Input: `FETCH APPROX` → Baseline: `FETCH APPROXIMATE` = Acceptable normalization +- ✅ Input: `SELECT /*+ HINT */` → Baseline: `SELECT` = Query hint (document in spec) + +✅ **Resolution Steps**: +1. Check AST definition in `Ast.xml` for member to store value +2. Verify grammar assigns value: `vResult.Property = vValue;` +3. Check script generator outputs value: `if (node.Property != null) { ... }` +4. If missing: Add AST member, update grammar, update script generator, rebuild +5. Document decision in spec if intentional omission + +--- + ## Summary The SqlScriptDOM testing framework provides comprehensive validation of parser functionality through: @@ -808,7 +859,11 @@ The SqlScriptDOM testing framework provides comprehensive validation of parser f - **Cross-version validation** (Test syntax across SQL Server versions) - **Error condition testing** (Invalid syntax produces expected errors) - **Exact syntax verification** (Exact T-SQL from user requests is tested precisely) +- **Round-trip fidelity validation** (Baseline preserves all input syntax unless documented) Following these guidelines ensures robust test coverage for parser functionality and prevents regressions when adding new features or fixing bugs. -**Key Principle**: Always test the exact T-SQL syntax provided in user prompts or requests to verify that the specific syntax works as expected, rather than testing generalized or simplified versions of the syntax. \ No newline at end of file +**Key Principles**: +1. Always test the exact T-SQL syntax provided in user prompts or requests +2. Always verify baseline output preserves input syntax (missing syntax may indicate bugs) +3. Document any intentional omissions (normalization, query hints) in spec \ No newline at end of file diff --git a/.gitignore b/.gitignore index 997c1729..adb0b54f 100644 --- a/.gitignore +++ b/.gitignore @@ -359,4 +359,15 @@ out/ .packages/ # Temporary build artifacts -tmp/ \ No newline at end of file +tmp/ + +# Speckit files +speckit.files +.github/.specify/ +.github/agents/speckit.*.agent.md +.github/prompts/speckit.* + +# Specs directory - ignore all files except spec.md +specs/**/* +!specs/**/ +!specs/**/spec.md diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index d17d34eb..1976cb16 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -4808,5 +4808,6 @@ + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 4f7e5be1..4c8a97d2 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -75,6 +75,7 @@ internal static class CodeGenerationSupporter internal const string AnsiWarnings = "ANSI_WARNINGS"; internal const string ForcePlan = "FORCEPLAN"; internal const string ForAppend = "FOR_APPEND"; + internal const string ForceAnnOnly = "FORCE_ANN_ONLY"; internal const string ShowPlanAll = "SHOWPLAN_ALL"; internal const string ShowPlanText = "SHOWPLAN_TEXT"; internal const string IO = "IO"; diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 85ec9cf4..a8a1b49d 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -19321,19 +19321,35 @@ vectorSearchTableReference returns [VectorSearchTableReference vResult = Fragmen MatchString(vMetric, CodeGenerationSupporter.Cosine, CodeGenerationSupporter.Dot, CodeGenerationSupporter.Euclidean); vResult.Metric = vMetric; } - Comma tTopN:Identifier EqualsSign vTopN = signedIntegerOrVariableOrColumnReference - { - Match(tTopN, CodeGenerationSupporter.TopN); - - // Validate that TOP_N is not a negative number - if (vTopN is UnaryExpression unaryExpr && unaryExpr.UnaryExpressionType == UnaryExpressionType.Negative) + // TOP_N is optional per SQL Server 2025 (commit 12d3e8fc) + ( + Comma tTopN:Identifier EqualsSign vTopN = signedIntegerOrVariableOrColumnReference { - ThrowParseErrorException("SQL46010", unaryExpr, TSqlParserResource.SQL46010Message, "-"); + Match(tTopN, CodeGenerationSupporter.TopN); + + // Validate that TOP_N is not a negative number + if (vTopN is UnaryExpression unaryExpr && unaryExpr.UnaryExpressionType == UnaryExpressionType.Negative) + { + ThrowParseErrorException("SQL46010", unaryExpr, TSqlParserResource.SQL46010Message, "-"); + } + + vResult.TopN = vTopN; } - - vResult.TopN = vTopN; + )? + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); } - RightParenthesis simpleTableReferenceAliasOpt[vResult] + // WITH clause per SQL Server 2025 (commit 12d3e8fc) + ( + With LeftParenthesis tForceAnnOnly:Identifier tRParen2:RightParenthesis + { + Match(tForceAnnOnly, CodeGenerationSupporter.ForceAnnOnly); + UpdateTokenInfo(vResult, tRParen2); + vResult.ForceAnnOnly = true; + } + )? + simpleTableReferenceAliasOpt[vResult] ; predictTableReference[SubDmlFlags subDmlFlags] returns [PredictTableReference vResult] @@ -33167,6 +33183,7 @@ jsonObjectBuiltInFunctionCall [FunctionCall vParent] jsonObjectAggBuiltInFunctionCall [FunctionCall vParent] { + OverClause vOverClause; } : ( jsonObjectAggExpressionList[vParent] @@ -33177,6 +33194,12 @@ jsonObjectAggBuiltInFunctionCall [FunctionCall vParent] { UpdateTokenInfo(vParent, tRParen); } + ( + vOverClause=overClauseNoOrderBy + { + vParent.OverClause = vOverClause; + } + )? ; jsonQueryBuiltInFunctionCall [FunctionCall vParent] diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index 77019ed7..21fd33d8 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -23761,8 +23761,6 @@ dropSecurityPolicyStatement returns [DropSecurityPolicyStatement vResult = Fragm createExternalDataSourceStatement returns [CreateExternalDataSourceStatement vResult = FragmentFactory.CreateFragment()] { Identifier vName; - ExternalDataSourceOption vExternalDataSourceOption; - long encounteredOptions = 0; vResult.DataSourceType = ExternalDataSourceType.EXTERNAL_GENERICS; } : tData:Identifier tSource:Identifier vName = identifier @@ -23774,42 +23772,8 @@ createExternalDataSourceStatement returns [CreateExternalDataSourceStatement vRe } tWith:With LeftParenthesis - ( - {NextTokenMatches(CodeGenerationSupporter.Type)}? - externalDataSourceType[vResult] - | - {NextTokenMatches(CodeGenerationSupporter.Location)}? - externalDataSourceLocation[vResult] - | - {NextTokenMatches(CodeGenerationSupporter.PushdownOption)}? - externalDataSourcePushdownOption[vResult] - | - vExternalDataSourceOption = externalDataSourceLiteralOrIdentifierOption - { - CheckOptionDuplication(ref encounteredOptions, (int)vExternalDataSourceOption.OptionKind, vExternalDataSourceOption); - AddAndUpdateTokenInfo(vResult, vResult.ExternalDataSourceOptions, vExternalDataSourceOption); - } - ) - ( - tComma:Comma - ( - {NextTokenMatches(CodeGenerationSupporter.Type)}? - externalDataSourceType[vResult] - | - {NextTokenMatches(CodeGenerationSupporter.Location)}? - externalDataSourceLocation[vResult] - | - {NextTokenMatches(CodeGenerationSupporter.PushdownOption)}? - externalDataSourcePushdownOption[vResult] - | - vExternalDataSourceOption = externalDataSourceLiteralOrIdentifierOption - { - CheckOptionDuplication(ref encounteredOptions, (int)vExternalDataSourceOption.OptionKind, vExternalDataSourceOption); - AddAndUpdateTokenInfo(vResult, vResult.ExternalDataSourceOptions, vExternalDataSourceOption); - } - ) - )* + externalDataSourceLocation[vResult] tRParen:RightParenthesis { @@ -23817,45 +23781,6 @@ createExternalDataSourceStatement returns [CreateExternalDataSourceStatement vRe } ; -externalDataSourceType[CreateExternalDataSourceStatement vParent] - : - tDataSourceType:Identifier EqualsSign - { - Match(tDataSourceType, CodeGenerationSupporter.Type); - UpdateTokenInfo(vParent, tDataSourceType); - } - ( - tExternalDataSourceType:Identifier - { - if (TryMatch(tExternalDataSourceType, CodeGenerationSupporter.Hadoop)) - { - UpdateTokenInfo(vParent, tExternalDataSourceType); - vParent.DataSourceType = ExternalDataSourceType.HADOOP; - } - else if (TryMatch(tExternalDataSourceType, CodeGenerationSupporter.Rdbms)) - { - UpdateTokenInfo(vParent, tExternalDataSourceType); - vParent.DataSourceType = ExternalDataSourceType.RDBMS; - } - else if (TryMatch(tExternalDataSourceType, CodeGenerationSupporter.ShardMapManager)) - { - UpdateTokenInfo(vParent, tExternalDataSourceType); - vParent.DataSourceType = ExternalDataSourceType.SHARD_MAP_MANAGER; - } - else if (TryMatch(tExternalDataSourceType, CodeGenerationSupporter.BlobStorage)) - { - UpdateTokenInfo(vParent, tExternalDataSourceType); - vParent.DataSourceType = ExternalDataSourceType.BLOB_STORAGE; - } - else - { - UpdateTokenInfo(vParent, tExternalDataSourceType); - vParent.DataSourceType = ExternalDataSourceType.EXTERNAL_GENERICS; - } - } - ) - ; - externalDataSourceLocation[ExternalDataSourceStatement vParent] { Literal vLocation; @@ -23868,68 +23793,9 @@ externalDataSourceLocation[ExternalDataSourceStatement vParent] } ; -externalDataSourcePushdownOption[ExternalDataSourceStatement vParent] - : - tPushdownOption:Identifier - { - Match(tPushdownOption, CodeGenerationSupporter.PushdownOption); - UpdateTokenInfo(vParent, tPushdownOption); - } - EqualsSign - ( - tOn:On - { - vParent.PushdownOption = ExternalDataSourcePushdownOption.ON; - UpdateTokenInfo(vParent, tOn); - } - | tOff:Off - { - vParent.PushdownOption = ExternalDataSourcePushdownOption.OFF; - UpdateTokenInfo(vParent, tOff); - } - ) - ; - -externalDataSourceLiteralOrIdentifierOption returns [ExternalDataSourceLiteralOrIdentifierOption vResult = this.FragmentFactory.CreateFragment()] -{ - Literal vLiteral; - Identifier vIdentifier; -} - : - tOption:Identifier - { - vResult.OptionKind = ExternalDataSourceOptionHelper.Instance.ParseOption(tOption); - } - EqualsSign - ( - vIdentifier = identifier - { - if (vResult.OptionKind != ExternalDataSourceOptionKind.Credential) - { - throw GetUnexpectedTokenErrorException(tOption); - } - vResult.Value = IdentifierOrValueExpression(vIdentifier); - } - | - vLiteral = stringLiteral - { - if (vResult.OptionKind != ExternalDataSourceOptionKind.ResourceManagerLocation && - vResult.OptionKind != ExternalDataSourceOptionKind.DatabaseName && - vResult.OptionKind != ExternalDataSourceOptionKind.ShardMapName && - vResult.OptionKind != ExternalDataSourceOptionKind.ConnectionOptions) - { - throw GetUnexpectedTokenErrorException(tOption); - } - vResult.Value = IdentifierOrValueExpression(vLiteral); - } - ) - ; - alterExternalDataSourceStatement returns [AlterExternalDataSourceStatement vResult = FragmentFactory.CreateFragment()] { Identifier vName; - ExternalDataSourceOption vExternalDataSourceOption; - long encounteredOptions = 0; } : tData:Identifier tSource:Identifier vName = identifier { @@ -23940,36 +23806,8 @@ alterExternalDataSourceStatement returns [AlterExternalDataSourceStatement vResu } tSet:Set - ( - {NextTokenMatches(CodeGenerationSupporter.Location)}? - externalDataSourceLocation[vResult] - | - {NextTokenMatches(CodeGenerationSupporter.PushdownOption)}? - externalDataSourcePushdownOption[vResult] - | - vExternalDataSourceOption = externalDataSourceLiteralOrIdentifierOption - { - CheckOptionDuplication(ref encounteredOptions, (int)vExternalDataSourceOption.OptionKind, vExternalDataSourceOption); - AddAndUpdateTokenInfo(vResult, vResult.ExternalDataSourceOptions, vExternalDataSourceOption); - } - ) - ( - tComma:Comma - ( - {NextTokenMatches(CodeGenerationSupporter.Location)}? - externalDataSourceLocation[vResult] - | - {NextTokenMatches(CodeGenerationSupporter.PushdownOption)}? - externalDataSourcePushdownOption[vResult] - | - vExternalDataSourceOption = externalDataSourceLiteralOrIdentifierOption - { - CheckOptionDuplication(ref encounteredOptions, (int)vExternalDataSourceOption.OptionKind, vExternalDataSourceOption); - AddAndUpdateTokenInfo(vResult, vResult.ExternalDataSourceOptions, vExternalDataSourceOption); - } - ) - )* + externalDataSourceLocation[vResult] ; dropExternalDataSourceStatement returns [DropExternalDataSourceStatement vResult = FragmentFactory.CreateFragment()] diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs index 70d7111c..ffa50996 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs @@ -70,6 +70,8 @@ public override void ExplicitVisit(FunctionCall node) GenerateSpace(); GenerateReturnType(node?.ReturnType); GenerateSymbol(TSqlTokenType.RightParenthesis); + // Generate OVER clause for windowed json_objectagg + GenerateSpaceAndFragmentIfNotNull(node.OverClause); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonArray) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs index 55e4730a..09b9aa42 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.VectorSearchTableReference.cs @@ -15,9 +15,9 @@ partial class SqlScriptGeneratorVisitor /// TABLE = object[AS source_table_alias], /// COLUMN = vector_column, /// SIMILAR_TO = query_vector, - /// METRIC = { 'cosine' | 'dot' | 'euclidean' }, - /// TOP_N = k - /// ) [AS result_table_alias] + /// METRIC = { 'cosine' | 'dot' | 'euclidean' } + /// [, TOP_N = k] + /// ) [WITH (FORCE_ANN_ONLY)] [AS result_table_alias] /// public override void ExplicitVisit(VectorSearchTableReference node) { @@ -41,13 +41,28 @@ public override void ExplicitVisit(VectorSearchTableReference node) NewLineAndIndent(); GenerateNameEqualsValue(CodeGenerationSupporter.Metric, node.Metric); - GenerateSymbol(TSqlTokenType.Comma); - - NewLineAndIndent(); - GenerateNameEqualsValue(CodeGenerationSupporter.TopN, node.TopN); + + // TOP_N is optional per SQL Server 2025 (commit 12d3e8fc) + if (node.TopN != null) + { + GenerateSymbol(TSqlTokenType.Comma); + NewLineAndIndent(); + GenerateNameEqualsValue(CodeGenerationSupporter.TopN, node.TopN); + } NewLine(); GenerateSymbol(TSqlTokenType.RightParenthesis); + + // WITH (FORCE_ANN_ONLY) hint per SQL Server 2025 (commit 12d3e8fc) + if (node.ForceAnnOnly) + { + GenerateSpaceAndKeyword(TSqlTokenType.With); + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateIdentifier(CodeGenerationSupporter.ForceAnnOnly); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + GenerateSpaceAndAlias(node.Alias); PopAlignmentPoint(); diff --git a/Test/SqlDom/Baselines170/JsonObjectAggOverClause170.sql b/Test/SqlDom/Baselines170/JsonObjectAggOverClause170.sql new file mode 100644 index 00000000..8aa7b2e5 --- /dev/null +++ b/Test/SqlDom/Baselines170/JsonObjectAggOverClause170.sql @@ -0,0 +1,11 @@ +SELECT JSON_OBJECTAGG(CustomerName:OrderDate) OVER (PARTITION BY OrderDate) +FROM Customers; + +SELECT JSON_OBJECTAGG(CustomerName:OrderDate ABSENT ON NULL) OVER (PARTITION BY OrderDate) +FROM Customers; + +SELECT JSON_OBJECTAGG(CustomerName:OrderDate NULL ON NULL) OVER (PARTITION BY OrderDate) +FROM Customers; + +SELECT JSON_OBJECTAGG(CustomerName:OrderDate NULL ON NULL RETURNING JSON) OVER (PARTITION BY OrderDate) +FROM Customers; \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/VectorSearchOptionalTopNTests170.sql b/Test/SqlDom/Baselines170/VectorSearchOptionalTopNTests170.sql new file mode 100644 index 00000000..6d31f39e --- /dev/null +++ b/Test/SqlDom/Baselines170/VectorSearchOptionalTopNTests170.sql @@ -0,0 +1,33 @@ +SELECT * +FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean' + ); + +SELECT * +FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean' + ) WITH (FORCE_ANN_ONLY); + +SELECT * +FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean', + TOP_N = 20 + ); + +SELECT * +FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean', + TOP_N = 20 + ) WITH (FORCE_ANN_ONLY); diff --git a/Test/SqlDom/BaselinesFabricDW/CreateAlterExternalDataSourceTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/CreateAlterExternalDataSourceTestsFabricDW.sql new file mode 100644 index 00000000..fb3aef43 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/CreateAlterExternalDataSourceTestsFabricDW.sql @@ -0,0 +1,11 @@ +CREATE EXTERNAL DATA SOURCE MyDataSource + WITH ( + LOCATION = 'sqlserver://10.10.10.10:1433' + ); + +CREATE EXTERNAL DATA SOURCE BlobSource + WITH ( + LOCATION = 'wasbs://container@account.blob.core.windows.net' + ); + +ALTER EXTERNAL DATA SOURCE MyDataSource SET LOCATION = 'sqlserver://192.168.1.100:1433'; \ No newline at end of file diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index a881c8ef..12478fd6 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -15,12 +15,14 @@ public partial class SqlDomTests new ParserTest170("RegexpTVFTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), new ParserTest170("JsonIndexTests170.sql", nErrors80: 2, nErrors90: 10, nErrors100: 10, nErrors110: 10, nErrors120: 10, nErrors130: 10, nErrors140: 10, nErrors150: 10, nErrors160: 10), new ParserTest170("VectorIndexTests170.sql", nErrors80: 2, nErrors90: 12, nErrors100: 12, nErrors110: 12, nErrors120: 12, nErrors130: 12, nErrors140: 12, nErrors150: 12, nErrors160: 12), + new ParserTest170("VectorSearchOptionalTopNTests170.sql"), new ParserTest170("AlterDatabaseManualCutoverTests170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("CreateColumnStoreIndexTests170.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), new ParserTest170("RegexpTests170.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0), new ParserTest170("AiGenerateChunksTests170.sql", nErrors80: 19, nErrors90: 16, nErrors100: 15, nErrors110: 15, nErrors120: 15, nErrors130: 15, nErrors140: 15, nErrors150: 15, nErrors160: 15), new ParserTest170("JsonFunctionTests170.sql", nErrors80: 29, nErrors90: 8, nErrors100: 54, nErrors110: 54, nErrors120: 54, nErrors130: 54, nErrors140: 54, nErrors150: 54, nErrors160: 54), new ParserTest170("JsonArrayAggOrderBy170.sql", nErrors80: 10, nErrors90: 9, nErrors100: 9, nErrors110: 9, nErrors120: 9, nErrors130: 9, nErrors140: 9, nErrors150: 9, nErrors160: 9), + new ParserTest170("JsonObjectAggOverClause170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("ComplexJsonObjectFunctionTests170.sql"), new ParserTest170("AiGenerateEmbeddingsTests170.sql", nErrors80: 14, nErrors90: 11, nErrors100: 11, nErrors110: 11, nErrors120: 11, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11), new ParserTest170("CreateExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index 5bee5e26..a2eaab85 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -10,6 +10,7 @@ public partial class SqlDomTests private static readonly ParserTest[] OnlyFabricDWTestInfos = { new ParserTestFabricDW("CloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), + new ParserTestFabricDW("CreateAlterExternalDataSourceTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), new ParserTestFabricDW("CreateAlterTableClusterByTestsFabricDW.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 6), new ParserTestFabricDW("CreateExternalTableStatementTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 0, nErrors170: 0), new ParserTestFabricDW("CreateProcedureCloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), @@ -23,7 +24,7 @@ public partial class SqlDomTests new ParserTestFabricDW("AiFixGrammarTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), + new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0) }; [TestMethod] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 5a89afe1..34b0a92c 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -5236,6 +5236,30 @@ public void CreateExternalDataSourceNegativeTest() ParserTestUtils.ErrorTest130("CREATE EXTERNAL DATA SOURCE eds1 WITH (TYPE = RDBMS, LOCATION = someServer, DATABASE_NAME = 'someDatabase', CREDENTIAL = someCred)", new ParserErrorInfo(64, "SQL46010", "someServer")); ParserTestUtils.ErrorTest130("CREATE EXTERNAL DATA SOURCE eds1 WITH (TYPE = RDBMS, LOCATION = 'someServer', DATABASE_NAME = someDatabase, CREDENTIAL = someCred)", new ParserErrorInfo(78, "SQL46010", "DATABASE_NAME")); ParserTestUtils.ErrorTest130("CREATE EXTERNAL DATA SOURCE eds1 WITH (TYPE = RDBMS, LOCATION = 'someServer', DATABASE_NAME = 'someDatabase', CREDENTIAL = 'someCred')", new ParserErrorInfo(110, "SQL46010", "CREDENTIAL")); + + // CREATE with TYPE parameter (no longer supported — parser expects LOCATION) + // + ParserTestUtils.ErrorTestFabricDW("CREATE EXTERNAL DATA SOURCE eds1 WITH (TYPE = HADOOP, LOCATION = 'protocol://ip_address:port')", new ParserErrorInfo(46, "SQL46010", "HADOOP")); + + // CREATE with extra CREDENTIAL option after LOCATION (only LOCATION allowed, no additional options) + // + ParserTestUtils.ErrorTestFabricDW("CREATE EXTERNAL DATA SOURCE eds1 WITH (LOCATION = 'protocol://ip_address:port', CREDENTIAL = cred1)", new ParserErrorInfo(78, "SQL46010", ",")); + + // CREATE with extra PUSHDOWN option after LOCATION + // + ParserTestUtils.ErrorTestFabricDW("CREATE EXTERNAL DATA SOURCE eds1 WITH (LOCATION = 'protocol://ip_address:port', PUSHDOWN = ON)", new ParserErrorInfo(78, "SQL46010", ",")); + + // CREATE with extra RESOURCE_MANAGER_LOCATION option after LOCATION + // + ParserTestUtils.ErrorTestFabricDW("CREATE EXTERNAL DATA SOURCE eds1 WITH (LOCATION = 'protocol://ip_address:port', RESOURCE_MANAGER_LOCATION = 'ip_address:port')", new ParserErrorInfo(78, "SQL46010", ",")); + + // CREATE with extra DATABASE_NAME option after LOCATION + // + ParserTestUtils.ErrorTestFabricDW("CREATE EXTERNAL DATA SOURCE eds1 WITH (LOCATION = 'someServer', DATABASE_NAME = 'someDatabase')", new ParserErrorInfo(62, "SQL46010", ",")); + + // CREATE with extra CONNECTION_OPTIONS after LOCATION + // + ParserTestUtils.ErrorTestFabricDW("CREATE EXTERNAL DATA SOURCE eds1 WITH (LOCATION = 'protocol://ip_address:port', CONNECTION_OPTIONS = 'some_options')", new ParserErrorInfo(78, "SQL46010", ",")); } @@ -5295,6 +5319,24 @@ public void AlterExternalDataSourceNegativeTest() ParserTestUtils.ErrorTest130("ALTER EXTERNAL DATA SOURCE eds1 SET LOCATION = 'someServer', DATABASE_NAME = someDatabase, SHARD_MAP_NAME = 'someShardMap', CREDENTIAL = someCred", new ParserErrorInfo(61, "SQL46010", "DATABASE_NAME")); ParserTestUtils.ErrorTest130("ALTER EXTERNAL DATA SOURCE eds1 SET LOCATION = 'someServer', DATABASE_NAME = 'someDatabase', SHARD_MAP_NAME = someShardMap, CREDENTIAL = someCred", new ParserErrorInfo(93, "SQL46010", "SHARD_MAP_NAME")); ParserTestUtils.ErrorTest130("ALTER EXTERNAL DATA SOURCE eds1 SET LOCATION = 'someServer', DATABASE_NAME = 'someDatabase', SHARD_MAP_NAME = 'someShardMap', CREDENTIAL = 'someCred'", new ParserErrorInfo(126, "SQL46010", "CREDENTIAL")); + + // ALTER with unsupported option instead of LOCATION + // + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET RESOURCE_MANAGER_LOCATION = 'ip_address:port'", new ParserErrorInfo(36, "SQL46005", "LOCATION", "RESOURCE_MANAGER_LOCATION")); + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET DATABASE_NAME = 'someDb'", new ParserErrorInfo(36, "SQL46005", "LOCATION", "DATABASE_NAME")); + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET CONNECTION_OPTIONS = 'some_options'", new ParserErrorInfo(36, "SQL46005", "LOCATION", "CONNECTION_OPTIONS")); + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET SHARD_MAP_NAME = 'someShardMap'", new ParserErrorInfo(36, "SQL46005", "LOCATION", "SHARD_MAP_NAME")); + + // ALTER with unsupported option where the value is not a string literal + // + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET PUSHDOWN = ON", new ParserErrorInfo(47, "SQL46010", "ON")); + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET CREDENTIAL = cred1", new ParserErrorInfo(49, "SQL46010", "cred1")); + + // ALTER with LOCATION followed by extra unsupported options (comma not expected after LOCATION value) + // + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET LOCATION = 'sqlserver://10.10.10.10:1433', PUSHDOWN = ON", new ParserErrorInfo(77, "SQL46010", ",")); + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET LOCATION = 'sqlserver://10.10.10.10:1433', CREDENTIAL = cred1", new ParserErrorInfo(77, "SQL46010", ",")); + ParserTestUtils.ErrorTestFabricDW("ALTER EXTERNAL DATA SOURCE eds1 SET LOCATION = 'sqlserver://10.10.10.10:1433', DATABASE_NAME = 'someDb'", new ParserErrorInfo(77, "SQL46010", ",")); } @@ -7059,6 +7101,7 @@ RETURNS NVARCHAR(101) RETURN @first + ' ' + @last END;"; ParserTestUtils.ErrorTestFabricDW(scalarFunctionSyntax2, new ParserErrorInfo(scalarFunctionSyntax2.IndexOf("INLINE"), "SQL46010", "INLINE")); + string scalarFunctionSyntax3 = @"CREATE OR ALTER FUNCTION dbo.CountProducts ( @ProductTable AS dbo.ProductType READONLY @@ -7097,11 +7140,22 @@ FROM @SalesData [SqlStudioTestCategory(Category.UnitTest)] public void IdentityColumnNegativeTestsFabricDW() { - string identityColumnSyntax = @"CREATE TABLE TestTable1 (ID INT IDENTITY(1,1), Name VARCHAR(50));"; - ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax, new ParserErrorInfo(40, "SQL46010", "(")); - - string identityColumnSyntax2 = @"CREATE TABLE TestTable2 (RecordID BIGINT IDENTITY(100,5), Description NVARCHAR(200));"; - ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax2, new ParserErrorInfo(49, "SQL46010", "(")); + string identityColumnSyntax = @"CREATE TABLE TestTable1 ( + ID INT IDENTITY(1,1), + Name VARCHAR(50) + ); + "; + string token = "IDENTITY"; + int errorOffSet = identityColumnSyntax.IndexOf(token) + token.Length; + ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax, new ParserErrorInfo(errorOffSet, "SQL46010", "(")); + + string identityColumnSyntax2 = @"CREATE TABLE TestTable2 ( + RecordID BIGINT IDENTITY(100,5), + Description NVARCHAR(200) + ); + "; + errorOffSet = identityColumnSyntax2.IndexOf(token) + token.Length; + ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax2, new ParserErrorInfo(errorOffSet, "SQL46010", "(")); } /// @@ -7445,10 +7499,9 @@ public void VectorSearchErrorTest170() "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector)", new ParserErrorInfo(82, "SQL46010", ")")); - // Missing required parameters: TOP_N - ParserTestUtils.ErrorTest170( - "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot')", - new ParserErrorInfo(98, "SQL46010", ")")); + // TOP_N is now OPTIONAL per SQL Server 2025 (commit 12d3e8fc) + // The following test case has been removed as it tested for TOP_N being mandatory + // which is no longer the case. VECTOR_SEARCH now accepts queries without TOP_N. // Invalid order: COLUMN before TABLE ParserTestUtils.ErrorTest170( diff --git a/Test/SqlDom/TestScripts/CreateAlterExternalDataSourceTestsFabricDW.sql b/Test/SqlDom/TestScripts/CreateAlterExternalDataSourceTestsFabricDW.sql new file mode 100644 index 00000000..fb3aef43 --- /dev/null +++ b/Test/SqlDom/TestScripts/CreateAlterExternalDataSourceTestsFabricDW.sql @@ -0,0 +1,11 @@ +CREATE EXTERNAL DATA SOURCE MyDataSource + WITH ( + LOCATION = 'sqlserver://10.10.10.10:1433' + ); + +CREATE EXTERNAL DATA SOURCE BlobSource + WITH ( + LOCATION = 'wasbs://container@account.blob.core.windows.net' + ); + +ALTER EXTERNAL DATA SOURCE MyDataSource SET LOCATION = 'sqlserver://192.168.1.100:1433'; \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/JsonObjectAggOverClause170.sql b/Test/SqlDom/TestScripts/JsonObjectAggOverClause170.sql new file mode 100644 index 00000000..16edf835 --- /dev/null +++ b/Test/SqlDom/TestScripts/JsonObjectAggOverClause170.sql @@ -0,0 +1,11 @@ +-- JSON_OBJECTAGG with OVER clause (PARTITION BY) +SELECT JSON_OBJECTAGG(CustomerName:OrderDate) OVER (PARTITION BY OrderDate) FROM Customers; + +-- JSON_OBJECTAGG with ABSENT ON NULL and OVER clause +SELECT JSON_OBJECTAGG(CustomerName:OrderDate ABSENT ON NULL) OVER (PARTITION BY OrderDate) FROM Customers; + +-- JSON_OBJECTAGG with NULL ON NULL and OVER clause +SELECT JSON_OBJECTAGG(CustomerName:OrderDate NULL ON NULL) OVER (PARTITION BY OrderDate) FROM Customers; + +-- JSON_OBJECTAGG with NULL ON NULL, RETURNING JSON, and OVER clause +SELECT JSON_OBJECTAGG(CustomerName:OrderDate NULL ON NULL RETURNING JSON) OVER (PARTITION BY OrderDate) FROM Customers; \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/VectorSearchOptionalTopNTests170.sql b/Test/SqlDom/TestScripts/VectorSearchOptionalTopNTests170.sql new file mode 100644 index 00000000..e6ebb71e --- /dev/null +++ b/Test/SqlDom/TestScripts/VectorSearchOptionalTopNTests170.sql @@ -0,0 +1,33 @@ +-- Test 1: VECTOR_SEARCH without TOP_N (validates optional parameter) +SELECT * FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean' +); + +-- Test 2: VECTOR_SEARCH without TOP_N + WITH (FORCE_ANN_ONLY) (validates both changes) +SELECT * FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean' +) WITH (FORCE_ANN_ONLY); + +-- Test 3: VECTOR_SEARCH with TOP_N (validates backward compatibility) +SELECT * FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean', + TOP_N = 20 +); + +-- Test 4: VECTOR_SEARCH with TOP_N + WITH (FORCE_ANN_ONLY) (validates both features together) +SELECT * FROM VECTOR_SEARCH( + TABLE = graphnode, + COLUMN = embedding, + SIMILAR_TO = @qembedding, + METRIC = 'euclidean', + TOP_N = 20 +) WITH (FORCE_ANN_ONLY); diff --git a/global.json b/global.json index b2e90b51..f64b7fb9 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.415", + "version": "8.0.418", "rollForward": "latestMajor" }, "msbuild-sdks": { diff --git a/release-notes/170/170.179.0.md b/release-notes/170/170.179.0.md new file mode 100644 index 00000000..42788f0b --- /dev/null +++ b/release-notes/170/170.179.0.md @@ -0,0 +1,28 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 170.179.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates .NET SDK to latest patch version 8.0.418 + +#### .NET Framework +#### .NET Core + +### New Features +* Adds JSON_OBJECTAGG support for OVER clause (windowed aggregate usage). +* Simplifies CREATE/ALTER EXTERNAL DATA SOURCE syntax for Fabric DW to only support the LOCATION parameter, removes support for TYPE, PUSHDOWN, and other literal/identifier options in the Fabric DW parser. + +### Fixed +* Fixes VECTOR_SEARCH TOP_N parameter to be optional. +* Fixes VECTOR_SEARCH to support WITH (FORCE_ANN_ONLY) query hint. + +### Changes + +### Known Issues From d503232d59d1e33d2645e53392c3e2f6a4d35e0e Mon Sep 17 00:00:00 2001 From: Sai Avishkar Sreerama <74571829+ssreerama@users.noreply.github.com> Date: Wed, 18 Mar 2026 13:23:37 -0500 Subject: [PATCH 22/45] Sync Repos: Release 170.191 (#193) * Fix allocation performance issue in ScriptWriter token list initialization * Add SQL Server 2025 TOP WITH APPROXIMATE and FETCH APPROXIMATE support * Adding release notes for 170.191.0 --- SqlScriptDom/Parser/TSql/Ast.xml | 2 + .../Parser/TSql/CodeGenerationSupporter.cs | 2 + SqlScriptDom/Parser/TSql/TSql170.g | 123 ++++++++++++++---- .../Parser/TSql/TSql170ParserBaseInternal.cs | 16 +++ .../SqlServer/ScriptGenerator/ScriptWriter.cs | 2 +- .../SqlScriptGeneratorVisitor.OffsetClause.cs | 22 +++- .../SqlScriptGeneratorVisitor.TopRowFilter.cs | 13 +- SqlScriptDom/TSqlParserResource.Designer.cs | 9 ++ SqlScriptDom/TSqlParserResource.resx | 3 + .../Baselines170/FetchApproximateTests170.sql | 34 +++++ .../TopWithApproximateTests170.sql | 27 ++++ .../VectorSearchApproximateTests170.sql | 55 ++++++++ Test/SqlDom/Only170SyntaxTests.cs | 3 + Test/SqlDom/ParserErrorsTests.cs | 45 +++++++ .../TestScripts/FetchApproximateTests170.sql | 35 +++++ .../TopWithApproximateTests170.sql | 30 +++++ .../VectorSearchApproximateTests170.sql | 57 ++++++++ release-notes/170/170.191.0.md | 27 ++++ 18 files changed, 474 insertions(+), 31 deletions(-) create mode 100644 Test/SqlDom/Baselines170/FetchApproximateTests170.sql create mode 100644 Test/SqlDom/Baselines170/TopWithApproximateTests170.sql create mode 100644 Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql create mode 100644 Test/SqlDom/TestScripts/FetchApproximateTests170.sql create mode 100644 Test/SqlDom/TestScripts/TopWithApproximateTests170.sql create mode 100644 Test/SqlDom/TestScripts/VectorSearchApproximateTests170.sql create mode 100644 release-notes/170/170.191.0.md diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index 1976cb16..4c5a4f4f 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -3630,10 +3630,12 @@ + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 4c8a97d2..d10f1b87 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -143,6 +143,8 @@ internal static class CodeGenerationSupporter internal const string Atomic = "ATOMIC"; internal const string Append = "APPEND"; internal const string AppendOnly = "APPEND_ONLY"; + internal const string Approximate = "APPROXIMATE"; + internal const string Approx = "APPROX"; internal const string Avg = "AVG"; internal const string Attested = "ATTESTED"; internal const string AuditGuid = "AUDIT_GUID"; diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index a8a1b49d..88ce6606 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -18389,33 +18389,99 @@ offsetClause returns [OffsetClause vResult = this.FragmentFactory.CreateFragment ScalarExpression vExpression; } : - tOffset:Identifier vExpression = expression - { - Match(tOffset, CodeGenerationSupporter.Offset); - UpdateTokenInfo(vResult,tOffset); - vResult.OffsetExpression = vExpression; - } - tOffsetRowOrRows:Identifier - { - Match(tOffsetRowOrRows, CodeGenerationSupporter.Row, CodeGenerationSupporter.Rows); - UpdateTokenInfo(vResult,tOffsetRowOrRows); - } ( - options {greedy=true;} : //Greedy due to conflict with FETCH statements - tFetch:Fetch tFirstOrNext:Identifier vExpression = expression + // Pattern 1: OFFSET with optional FETCH + tOffset:Identifier vExpression = expression + { + Match(tOffset, CodeGenerationSupporter.Offset); + UpdateTokenInfo(vResult,tOffset); + vResult.OffsetExpression = vExpression; + } + tOffsetRowOrRows:Identifier + { + Match(tOffsetRowOrRows, CodeGenerationSupporter.Row, CodeGenerationSupporter.Rows); + UpdateTokenInfo(vResult,tOffsetRowOrRows); + } + ( + options {greedy=true;} : //Greedy due to conflict with FETCH statements + tFetch:Fetch + tFirstOrNext:Identifier + { + // Check if this is APPROXIMATE/APPROX before FIRST/NEXT + if (TryMatch(tFirstOrNext, CodeGenerationSupporter.Approximate) || + TryMatch(tFirstOrNext, CodeGenerationSupporter.Approx)) + { + vResult.WithApproximate = true; + UpdateTokenInfo(vResult,tFirstOrNext); + + // Consume the actual FIRST/NEXT token + tFirstOrNext = LT(1); + consume(); + Match(tFirstOrNext, CodeGenerationSupporter.First, CodeGenerationSupporter.Next); + UpdateTokenInfo(vResult,tFirstOrNext); + } + else + { + // This is the FIRST/NEXT token directly + Match(tFirstOrNext, CodeGenerationSupporter.First, CodeGenerationSupporter.Next); + UpdateTokenInfo(vResult,tFirstOrNext); + } + } + vExpression = expression + { + vResult.FetchExpression = vExpression; + } + tFetchRowOrRows:Identifier tOnly:Identifier + { + Match(tFetchRowOrRows, CodeGenerationSupporter.Row, CodeGenerationSupporter.Rows); + Match(tOnly, CodeGenerationSupporter.Only); + UpdateTokenInfo(vResult, tOnly); + + // Validate: OFFSET cannot be used with FETCH APPROXIMATE + ValidateFetchApproximate(vResult); + } + )? + | + // Pattern 2: Standalone FETCH (APPROXIMATE only in TSql170+) + tFetch2:Fetch + { + UpdateTokenInfo(vResult,tFetch2); + } + tFirstOrNext2:Identifier + { + // Check if this is APPROXIMATE/APPROX before FIRST/NEXT + if (TryMatch(tFirstOrNext2, CodeGenerationSupporter.Approximate) || + TryMatch(tFirstOrNext2, CodeGenerationSupporter.Approx)) + { + vResult.WithApproximate = true; + UpdateTokenInfo(vResult,tFirstOrNext2); + + // Consume the actual FIRST/NEXT token + tFirstOrNext2 = LT(1); + consume(); + Match(tFirstOrNext2, CodeGenerationSupporter.First, CodeGenerationSupporter.Next); + UpdateTokenInfo(vResult,tFirstOrNext2); + } + else + { + // This is the FIRST/NEXT token directly + Match(tFirstOrNext2, CodeGenerationSupporter.First, CodeGenerationSupporter.Next); + UpdateTokenInfo(vResult,tFirstOrNext2); + } + } + vExpression = expression { - UpdateTokenInfo(vResult,tFetch); - Match(tFirstOrNext, CodeGenerationSupporter.First, CodeGenerationSupporter.Next); - UpdateTokenInfo(vResult,tFirstOrNext); vResult.FetchExpression = vExpression; } - tFetchRowOrRows:Identifier tOnly:Identifier + tFetchRowOrRows2:Identifier tOnly2:Identifier { - Match(tFetchRowOrRows, CodeGenerationSupporter.Row, CodeGenerationSupporter.Rows); - Match(tOnly, CodeGenerationSupporter.Only); - UpdateTokenInfo(vResult, tOnly); + Match(tFetchRowOrRows2, CodeGenerationSupporter.Row, CodeGenerationSupporter.Rows); + Match(tOnly2, CodeGenerationSupporter.Only); + UpdateTokenInfo(vResult, tOnly2); + + // No validation needed for standalone FETCH APPROXIMATE (no OFFSET present) } - )? + ) ; // This rule corresponds to topn in Sql Server grammar. @@ -18447,9 +18513,18 @@ topRowFilter returns [TopRowFilter vResult = this.FragmentFactory.CreateFragment ( With tId:Identifier { - Match(tId,CodeGenerationSupporter.Ties); - UpdateTokenInfo(vResult,tId); - vResult.WithTies = true; + if (TryMatch(tId, CodeGenerationSupporter.Approximate) || + TryMatch(tId, CodeGenerationSupporter.Approx)) + { + UpdateTokenInfo(vResult,tId); + vResult.WithApproximate = true; + } + else + { + Match(tId,CodeGenerationSupporter.Ties); + UpdateTokenInfo(vResult,tId); + vResult.WithTies = true; + } } )? ; diff --git a/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs index 9b5146b3..be2cfa99 100644 --- a/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql170ParserBaseInternal.cs @@ -109,5 +109,21 @@ protected bool ContainsVectorInLookahead() return false; } + + /// + /// Validates that OFFSET is not used with FETCH APPROXIMATE. + /// SQL Server does not support combining OFFSET with FETCH APPROXIMATE. + /// + /// The offset clause to validate. + protected void ValidateFetchApproximate(OffsetClause offsetClause) + { + if (offsetClause != null && + offsetClause.WithApproximate && + offsetClause.OffsetExpression != null) + { + ThrowParseErrorException("SQL46145", offsetClause, + TSqlParserResource.SQL46145Message); + } + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs index 85d2faca..e1ceb0ed 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs @@ -321,7 +321,7 @@ private List Align() } // generate aligned token stream - List tokens = new List(); + List tokens = new List(_scriptWriterElements.Count); Int32 offset = 0; for (Int32 index = 0; index < _scriptWriterElements.Count; ++index) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OffsetClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OffsetClause.cs index 104be060..7c4a3718 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OffsetClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OffsetClause.cs @@ -14,13 +14,27 @@ public override void ExplicitVisit(OffsetClause node) AlignmentPoint start = new AlignmentPoint(); MarkAndPushAlignmentPoint(start); - GenerateIdentifier(CodeGenerationSupporter.Offset); - GenerateSpaceAndFragmentIfNotNull(node.OffsetExpression); - GenerateSpaceAndIdentifier(CodeGenerationSupporter.Rows); + if (node.OffsetExpression != null) + { + GenerateIdentifier(CodeGenerationSupporter.Offset); + GenerateSpaceAndFragmentIfNotNull(node.OffsetExpression); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Rows); + } if (node.FetchExpression != null) { - GenerateSpaceAndKeyword(TSqlTokenType.Fetch); + if (node.OffsetExpression != null) + { + GenerateSpace(); + } + + GenerateKeyword(TSqlTokenType.Fetch); + + if (node.WithApproximate) + { + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Approximate); + } + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Next); GenerateSpaceAndFragmentIfNotNull(node.FetchExpression); GenerateSpaceAndIdentifier(CodeGenerationSupporter.Rows); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TopRowFilter.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TopRowFilter.cs index b8b9d8d9..fcead26b 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TopRowFilter.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TopRowFilter.cs @@ -19,10 +19,19 @@ public override void ExplicitVisit(TopRowFilter node) GenerateSpaceAndKeyword(TSqlTokenType.Percent); } - if (node.WithTies) + if (node.WithTies || node.WithApproximate) { GenerateSpaceAndKeyword(TSqlTokenType.With); - GenerateSpaceAndIdentifier(CodeGenerationSupporter.Ties); + + if (node.WithApproximate) + { + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Approximate); + } + + if (node.WithTies) + { + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Ties); + } } } } diff --git a/SqlScriptDom/TSqlParserResource.Designer.cs b/SqlScriptDom/TSqlParserResource.Designer.cs index 5cc8c0aa..c189e191 100644 --- a/SqlScriptDom/TSqlParserResource.Designer.cs +++ b/SqlScriptDom/TSqlParserResource.Designer.cs @@ -1329,6 +1329,15 @@ internal static string SQL46144Message { } } + /// + /// Looks up a localized string similar to OFFSET clause cannot be used with FETCH APPROXIMATE. Use FETCH APPROXIMATE without OFFSET.. + /// + internal static string SQL46145Message { + get { + return ResourceManager.GetString("SQL46145Message", resourceCulture); + } + } + /// /// Looks up a localized string similar to User-defined. /// diff --git a/SqlScriptDom/TSqlParserResource.resx b/SqlScriptDom/TSqlParserResource.resx index c6d7213a..49274a4a 100644 --- a/SqlScriptDom/TSqlParserResource.resx +++ b/SqlScriptDom/TSqlParserResource.resx @@ -631,4 +631,7 @@ Required parameter {0} must be provided. + + OFFSET clause cannot be used with FETCH APPROXIMATE. Use FETCH APPROXIMATE without OFFSET. + \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/FetchApproximateTests170.sql b/Test/SqlDom/Baselines170/FetchApproximateTests170.sql new file mode 100644 index 00000000..b29e66d4 --- /dev/null +++ b/Test/SqlDom/Baselines170/FetchApproximateTests170.sql @@ -0,0 +1,34 @@ +SELECT OrderID, + CustomerName +FROM Orders +ORDER BY OrderDate +FETCH APPROXIMATE NEXT 20 ROWS ONLY; + +SELECT OrderID, + CustomerName +FROM Orders +ORDER BY OrderDate +FETCH APPROXIMATE NEXT 20 ROWS ONLY; + +SELECT ProductID, + ProductName +FROM Products +ORDER BY Price +FETCH APPROXIMATE NEXT 15 ROWS ONLY; + +DECLARE @take AS INT = 50; + +SELECT OrderID, + CustomerName, + OrderDate +FROM Orders +ORDER BY OrderDate +FETCH APPROXIMATE NEXT @take ROWS ONLY; + +SELECT TOP 100 * +FROM (SELECT OrderID, + CustomerName + FROM Orders + ORDER BY OrderDate + FETCH APPROXIMATE NEXT 1000 ROWS ONLY) AS RecentOrders +ORDER BY OrderID; diff --git a/Test/SqlDom/Baselines170/TopWithApproximateTests170.sql b/Test/SqlDom/Baselines170/TopWithApproximateTests170.sql new file mode 100644 index 00000000..2c4d00e5 --- /dev/null +++ b/Test/SqlDom/Baselines170/TopWithApproximateTests170.sql @@ -0,0 +1,27 @@ +SELECT TOP 10 WITH APPROXIMATE * +FROM Orders +ORDER BY OrderDate; + +SELECT TOP 10 WITH APPROXIMATE * +FROM Orders +ORDER BY OrderDate; + +SELECT TOP (10) WITH APPROXIMATE * +FROM Orders +ORDER BY OrderDate; + +SELECT TOP (LEN(DB_NAME())) WITH APPROXIMATE * +FROM Orders +ORDER BY OrderDate; + +SELECT TOP 5 WITH APPROXIMATE OrderID, + CustomerName, + OrderDate +FROM Orders +ORDER BY OrderDate DESC; + +DECLARE @top AS INT = 20; + +SELECT TOP (@top) WITH APPROXIMATE * +FROM Products +ORDER BY Price; diff --git a/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql b/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql new file mode 100644 index 00000000..958e8a47 --- /dev/null +++ b/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql @@ -0,0 +1,55 @@ +SELECT TOP 10 WITH APPROXIMATE qt.qid, + src.id, + ann.distance +FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance; + + +GO +SELECT TOP 10 WITH APPROXIMATE qt.qid, + src.id, + ann.distance +FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance; + + +GO +SELECT qt.qid, + src.id, + ann.distance +FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance +FETCH APPROXIMATE NEXT 10 ROWS ONLY; + + +GO +SELECT qt.qid, + src.id, + ann.distance +FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance +FETCH APPROXIMATE NEXT 10 ROWS ONLY; \ No newline at end of file diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 12478fd6..f987f4a7 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -30,6 +30,9 @@ public partial class SqlDomTests new ParserTest170("DropExternalModelStatementTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1, nErrors160: 1), new ParserTest170("VectorFunctionTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 3, nErrors140: 3, nErrors150: 3, nErrors160: 3), new ParserTest170("SecurityStatementExternalModelTests170.sql", nErrors80: 2, nErrors90: 17, nErrors100: 17, nErrors110: 17, nErrors120: 17, nErrors130: 17, nErrors140: 17, nErrors150: 17, nErrors160: 17), + new ParserTest170("TopWithApproximateTests170.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6), + new ParserTest170("FetchApproximateTests170.sql"), + new ParserTest170("VectorSearchApproximateTests170.sql"), new ParserTest170("VectorTypeSecondParameterTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), new ParserTest170("RegexpLikeTests170.sql", nErrors80: 15, nErrors90: 15, nErrors100: 15, nErrors110: 18, nErrors120: 18, nErrors130: 18, nErrors140: 18, nErrors150: 18, nErrors160: 18), new ParserTest170("OptimizedLockingTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2), diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 34b0a92c..636c5260 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -7832,5 +7832,50 @@ public void AiTranslateNegativeTestsFabricDw() "SELECT AI_TRANSLATE('1', '2', '3')", new ParserErrorInfo(28, "SQL46010", ",")); } + + /// + /// Negative test for OFFSET with FETCH APPROXIMATE - SQL46145 error + /// OFFSET clause cannot be used with FETCH APPROXIMATE (introduced in SQL Server 2025) + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void OffsetWithFetchApproximateError() + { + // OFFSET + FETCH APPROXIMATE is invalid + ParserTestUtils.ErrorTest170( + "SELECT * FROM MyTable ORDER BY id OFFSET 5 ROWS FETCH APPROXIMATE NEXT 10 ROWS ONLY;", + new ParserErrorInfo(34, "SQL46145")); + } + + /// + /// Negative test for combining TIES with APPROXIMATE - syntax error + /// APPROXIMATE and TIES are mutually exclusive (introduced in SQL Server 2025) + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TopWithTiesAndApproximateError() + { + // Cannot use both TIES and APPROXIMATE together + ParserTestUtils.ErrorTest170( + "SELECT TOP 10 WITH TIES WITH APPROXIMATE * FROM MyTable ORDER BY id;", + new ParserErrorInfo(24, "SQL46010", "WITH")); + } + + /// + /// Negative test for OFFSET with FETCH APPROX (abbreviated) - SQL46145 error + /// Verifies that abbreviated APPROX keyword also triggers validation + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void OffsetWithFetchApproxError() + { + // OFFSET + FETCH APPROX (abbreviated) is invalid + ParserTestUtils.ErrorTest170( + "SELECT * FROM MyTable ORDER BY id OFFSET 10 ROWS FETCH APPROX NEXT 5 ROWS ONLY;", + new ParserErrorInfo(34, "SQL46145")); + } } } diff --git a/Test/SqlDom/TestScripts/FetchApproximateTests170.sql b/Test/SqlDom/TestScripts/FetchApproximateTests170.sql new file mode 100644 index 00000000..e9b54056 --- /dev/null +++ b/Test/SqlDom/TestScripts/FetchApproximateTests170.sql @@ -0,0 +1,35 @@ +-- Test 1: FETCH APPROXIMATE NEXT (full keyword) - NO OFFSET +SELECT OrderID, CustomerName +FROM Orders +ORDER BY OrderDate +FETCH APPROXIMATE NEXT 20 ROWS ONLY; + +-- Test 2: FETCH APPROX NEXT (abbreviated keyword) - NO OFFSET +SELECT OrderID, CustomerName +FROM Orders +ORDER BY OrderDate +FETCH APPROX NEXT 20 ROWS ONLY; + +-- Test 3: FETCH APPROXIMATE FIRST (with FIRST instead of NEXT) - NO OFFSET +SELECT ProductID, ProductName +FROM Products +ORDER BY Price +FETCH APPROXIMATE FIRST 15 ROWS ONLY; + +-- Test 4: FETCH APPROXIMATE with parameter - NO OFFSET +DECLARE @take INT = 50; + +SELECT OrderID, CustomerName, OrderDate +FROM Orders +ORDER BY OrderDate +FETCH APPROXIMATE NEXT @take ROWS ONLY; + +-- Test 5: FETCH APPROXIMATE with complex expression - NO OFFSET +SELECT TOP 100 * +FROM ( + SELECT OrderID, CustomerName + FROM Orders + ORDER BY OrderDate + FETCH APPROXIMATE NEXT 1000 ROWS ONLY +) AS RecentOrders +ORDER BY OrderID; diff --git a/Test/SqlDom/TestScripts/TopWithApproximateTests170.sql b/Test/SqlDom/TestScripts/TopWithApproximateTests170.sql new file mode 100644 index 00000000..64bcd961 --- /dev/null +++ b/Test/SqlDom/TestScripts/TopWithApproximateTests170.sql @@ -0,0 +1,30 @@ +-- Test 1: TOP WITH APPROXIMATE (full keyword) +SELECT TOP 10 WITH APPROXIMATE * +FROM Orders +ORDER BY OrderDate; + +-- Test 2: TOP WITH APPROX (abbreviated form) +SELECT TOP 10 WITH APPROX * +FROM Orders +ORDER BY OrderDate; + +-- Test 3: TOP(expression) WITH APPROXIMATE +SELECT TOP(10) WITH APPROXIMATE * +FROM Orders +ORDER BY OrderDate; + +-- Test 4: TOP(function) WITH APPROX +SELECT TOP(LEN(DB_NAME())) WITH APPROX * +FROM Orders +ORDER BY OrderDate; + +-- Test 5: TOP WITH APPROXIMATE and column list +SELECT TOP 5 WITH APPROXIMATE OrderID, CustomerName, OrderDate +FROM Orders +ORDER BY OrderDate DESC; + +-- Test 6: TOP(variable) WITH APPROXIMATE +DECLARE @top INT = 20; +SELECT TOP(@top) WITH APPROXIMATE * +FROM Products +ORDER BY Price; diff --git a/Test/SqlDom/TestScripts/VectorSearchApproximateTests170.sql b/Test/SqlDom/TestScripts/VectorSearchApproximateTests170.sql new file mode 100644 index 00000000..1583f34f --- /dev/null +++ b/Test/SqlDom/TestScripts/VectorSearchApproximateTests170.sql @@ -0,0 +1,57 @@ +-- Tests for VECTOR_SEARCH with TOP WITH APPROXIMATE and FETCH APPROXIMATE +-- From ADO commit: 355ed5f69d5c8a589271a5a5d4df76665bb4e985 +-- Source: VectorSearch.xml tests top_with_approx, top_with_approximate, order_by_fetch_approx, order_by_fetch_approximate + +-- Test 1: TOP WITH APPROX (abbreviated) +SELECT TOP 10 WITH APPROX qt.qid, src.id, ann.distance FROM QueryTable qt +CROSS APPLY + VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance; +GO + +-- Test 2: TOP WITH APPROXIMATE (full keyword) +SELECT TOP 10 WITH APPROXIMATE qt.qid, src.id, ann.distance FROM QueryTable qt +CROSS APPLY + VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance; +GO + +-- Test 3: ORDER BY FETCH APPROX (abbreviated) +SELECT qt.qid, src.id, ann.distance FROM QueryTable qt +CROSS APPLY + VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance +FETCH APPROX NEXT 10 ROWS ONLY; +GO + +-- Test 4: ORDER BY FETCH APPROXIMATE (full keyword) +SELECT qt.qid, src.id, ann.distance FROM QueryTable qt +CROSS APPLY + VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann +ORDER BY ann.distance +FETCH APPROXIMATE NEXT 10 ROWS ONLY; +GO diff --git a/release-notes/170/170.191.0.md b/release-notes/170/170.191.0.md new file mode 100644 index 00000000..b023b3ec --- /dev/null +++ b/release-notes/170/170.191.0.md @@ -0,0 +1,27 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 170.191.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies + +#### .NET Framework +#### .NET Core + +### New Features +* Adds TOP WITH APPROXIMATE and FETCH APPROXIMATE support. + +### Fixed +* Fixes allocation performance issue in ScriptWriter token list initialization. + +### Changes +* None + +### Known Issues +* None \ No newline at end of file From 265ba33df3c61aae9b0d3f035ff2899bd01f7e8d Mon Sep 17 00:00:00 2001 From: Randolph West MSFT <97149825+rwestMSFT@users.noreply.github.com> Date: Mon, 13 Apr 2026 20:57:09 -0600 Subject: [PATCH 23/45] Place semicolon before inline comment (#197) --- .../SqlScriptGeneratorVisitor.Comments.cs | 26 +++++ ...SqlScriptGeneratorVisitor.CommonPhrases.cs | 40 ++++++++ .../SqlScriptGeneratorVisitor.IfStatement.cs | 6 +- ...SqlScriptGeneratorVisitor.StatementList.cs | 3 +- .../SqlScriptGeneratorVisitor.TSqlBatch.cs | 4 +- ...qlScriptGeneratorVisitor.WhileStatement.cs | 3 +- Test/SqlDom/ScriptGeneratorTests.cs | 96 +++++++++++++++++++ 7 files changed, 167 insertions(+), 11 deletions(-) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs index 1ea9fec8..697e8b19 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs @@ -33,6 +33,20 @@ internal abstract partial class SqlScriptGeneratorVisitor /// private bool _leadingCommentsEmitted = false; + /// + /// When true, suppresses trailing comment emission in HandleCommentsAfterFragment + /// for fragments whose LastTokenIndex matches or exceeds _suppressTrailingCommentsAfterIndex. + /// Used by GenerateStatementWithSemiColon to defer trailing comments until after + /// the semicolon has been placed, without affecting inter-clause comments. + /// + private bool _suppressTrailingComments = false; + + /// + /// The LastTokenIndex of the statement for which trailing comments are being suppressed. + /// Only comments after this index are suppressed. + /// + private int _suppressTrailingCommentsAfterIndex = -1; + #endregion #region Comment Preservation Methods @@ -48,6 +62,8 @@ protected void SetTokenStreamForComments(IList tokenStream) _lastProcessedTokenIndex = -1; _emittedComments.Clear(); _leadingCommentsEmitted = false; + _suppressTrailingComments = false; + _suppressTrailingCommentsAfterIndex = -1; } /// @@ -192,6 +208,16 @@ protected void HandleCommentsAfterFragment(TSqlFragment fragment) return; } + // When trailing comments are suppressed (e.g., during statement body generation + // before semicolon placement), skip emitting trailing comments only for fragments + // whose last token is at or past the statement boundary. Inter-clause comments + // (within the statement) are still emitted normally. + if (_suppressTrailingComments && fragment.LastTokenIndex >= _suppressTrailingCommentsAfterIndex) + { + UpdateLastProcessedIndex(fragment); + return; + } + // Emit trailing comments and update tracking EmitTrailingComments(fragment); UpdateLastProcessedIndex(fragment); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs index f66d6fe1..bcfb13ad 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs @@ -440,6 +440,46 @@ protected void GenerateSemiColonWhenNecessary(TSqlStatement node) } } + /// + /// Generates a statement fragment with semicolon placed before any trailing comments. + /// This prevents semicolons from being appended after single-line comments (-- style), + /// which would make them part of the comment text. + /// + protected void GenerateStatementWithSemiColon(TSqlStatement statement) + { + if (statement == null) + { + return; + } + + // Handle comments before + HandleCommentsBeforeFragment(statement); + + // Suppress trailing comment emission during statement body generation + // so that the semicolon can be placed before trailing comments. + // Only suppress for fragments at the statement boundary (LastTokenIndex). + bool previousSuppressState = _suppressTrailingComments; + int previousSuppressIndex = _suppressTrailingCommentsAfterIndex; + if (_options.PreserveComments && _generateSemiColon && !StatementsThatCannotHaveSemiColon.Contains(statement.GetType())) + { + _suppressTrailingComments = true; + _suppressTrailingCommentsAfterIndex = statement.LastTokenIndex; + } + + // Generate the statement body + statement.Accept(this); + + // Restore suppression state and emit semicolon before trailing comments + _suppressTrailingComments = previousSuppressState; + _suppressTrailingCommentsAfterIndex = previousSuppressIndex; + + // Semicolon BEFORE trailing comments + GenerateSemiColonWhenNecessary(statement); + + // Now emit trailing comments (after the semicolon) + HandleCommentsAfterFragment(statement); + } + protected void GenerateCommaSeparatedWithClause(IList fragments, bool indent, bool includeParentheses) where T : TSqlFragment { if (fragments != null && fragments.Count > 0) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IfStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IfStatement.cs index c5ea4f5d..c73aa156 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IfStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IfStatement.cs @@ -18,8 +18,7 @@ public override void ExplicitVisit(IfStatement node) NewLineAndIndent(); MarkAndPushAlignmentPoint(branchStatements); - GenerateFragmentIfNotNull(node.ThenStatement); - GenerateSemiColonWhenNecessary(node.ThenStatement); + GenerateStatementWithSemiColon(node.ThenStatement); PopAlignmentPoint(); if (node.ElseStatement != null) @@ -28,8 +27,7 @@ public override void ExplicitVisit(IfStatement node) GenerateKeyword(TSqlTokenType.Else); NewLineAndIndent(); MarkAndPushAlignmentPoint(branchStatements); - GenerateFragmentIfNotNull(node.ElseStatement); - GenerateSemiColonWhenNecessary(node.ElseStatement); + GenerateStatementWithSemiColon(node.ElseStatement); PopAlignmentPoint(); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs index 6dedb215..4c872987 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs @@ -29,8 +29,7 @@ public override void ExplicitVisit(StatementList node) } } - GenerateFragmentIfNotNull(statement); - GenerateSemiColonWhenNecessary(statement); + GenerateStatementWithSemiColon(statement); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs index e40318ae..04205900 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs @@ -13,9 +13,7 @@ public override void ExplicitVisit(TSqlBatch node) { foreach (TSqlStatement statement in node.Statements) { - GenerateFragmentIfNotNull(statement); - - GenerateSemiColonWhenNecessary(statement); + GenerateStatementWithSemiColon(statement); if (statement is TSqlStatementSnippet == false) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhileStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhileStatement.cs index e7cb6d86..4369666e 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhileStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhileStatement.cs @@ -18,8 +18,7 @@ public override void ExplicitVisit(WhileStatement node) NewLineAndIndent(); MarkAndPushAlignmentPoint(whileBody); - GenerateFragmentIfNotNull(node.Statement); - GenerateSemiColonWhenNecessary(node.Statement); + GenerateStatementWithSemiColon(node.Statement); PopAlignmentPoint(); } } diff --git a/Test/SqlDom/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGeneratorTests.cs index 5a21409d..34eebbc1 100644 --- a/Test/SqlDom/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGeneratorTests.cs @@ -1256,6 +1256,102 @@ public void TestPreserveCommentsEnabled_CommentInNestedSubquery() $"inner_q alias should appear before outer_q alias. inner_q at {innerQAliasIdx}, outer_q at {outerQAliasIdx}"); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_SemicolonBeforeTrailingComment() + { + // Test that semicolons are placed BEFORE trailing single-line comments, + // not after them (which would make the semicolon part of the comment text). + // Bug fix: previously "SELECT 1 -- comment;" was generated instead of "SELECT 1; -- comment" + var sqlWithComments = "SELECT 1 -- trailing comment"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // The semicolon must appear BEFORE the trailing comment + int semicolonIndex = generatedSql.IndexOf(";"); + int commentIndex = generatedSql.IndexOf("-- trailing comment"); + + Assert.IsTrue(semicolonIndex >= 0, "Semicolon should be present in output. Actual: " + generatedSql); + Assert.IsTrue(commentIndex >= 0, "Trailing comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(semicolonIndex < commentIndex, + $"Semicolon should appear before trailing comment. Semicolon at {semicolonIndex}, comment at {commentIndex}. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_SemicolonBeforeTrailingComment_MultipleStatements() + { + // Test semicolon placement with multiple statements each having trailing comments + var sqlWithComments = @"SELECT 1 -- first comment +SELECT 2 -- second comment"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // Both comments should be preserved + Assert.IsTrue(generatedSql.Contains("-- first comment"), + "First trailing comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- second comment"), + "Second trailing comment should be preserved. Actual: " + generatedSql); + + // Verify semicolons appear before their respective comments, not after + Assert.IsFalse(generatedSql.Contains("-- first comment;"), + "Semicolon should not appear after first comment text. Actual: " + generatedSql); + Assert.IsFalse(generatedSql.Contains("-- second comment;"), + "Semicolon should not appear after second comment text. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_SemicolonBeforeTrailingBlockComment() + { + // Test semicolon placement with trailing block comments + var sqlWithComments = "SELECT 1 /* trailing block comment */"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // The semicolon must appear BEFORE the trailing block comment + int semicolonIndex = generatedSql.IndexOf(";"); + int commentIndex = generatedSql.IndexOf("/* trailing block comment */"); + + Assert.IsTrue(semicolonIndex >= 0, "Semicolon should be present in output. Actual: " + generatedSql); + Assert.IsTrue(commentIndex >= 0, "Trailing block comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(semicolonIndex < commentIndex, + $"Semicolon should appear before trailing block comment. Semicolon at {semicolonIndex}, comment at {commentIndex}. Actual: " + generatedSql); + } + #endregion } } From 656cfee750d47bbbe8675f5e5f6a0671be2dbd0e Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Mon, 20 Apr 2026 13:52:50 -0700 Subject: [PATCH 24/45] Sync repos: commits for release 180.6.0 (#199) Sync repos: commits for release 180.6.0 (#199) --- .github/copilot-instructions.md | 2 + ...ding_new_parser.guidelines.instructions.md | 797 + ...database_option.guidelines.instructions.md | 493 + .github/skills/add-feature/SKILL.md | 282 + SqlScriptDom/GenerateFiles.props | 1 + .../Parser/TSql/CodeGenerationSupporter.cs | 1 + .../Parser/TSql/DatabaseOptionKind.cs | 7 +- .../Parser/TSql/OnOffSimpleDbOptionsHelper.cs | 5 +- SqlScriptDom/Parser/TSql/OptionsHelper.cs | 2 + SqlScriptDom/Parser/TSql/SqlVersionFlags.cs | 27 +- SqlScriptDom/Parser/TSql/TSql180.g | 35473 ++++++++++++++++ SqlScriptDom/Parser/TSql/TSql180Parser.cs | 269 + .../Parser/TSql/TSql180ParserBaseInternal.cs | 75 + SqlScriptDom/Parser/TSql/TSqlParser.cs | 2 + .../Sql180ScriptGeneratorVisitor.cs | 252 + .../SqlServer/Sql180ScriptGenerator.cs | 42 + .../ScriptDom/SqlServer/SqlVersion.cs | 5 + .../AutomaticIndexCompactionTests180.sql | 5 + Test/SqlDom/Only170SyntaxTests.cs | 2 +- Test/SqlDom/Only180SyntaxTests.cs | 92 + Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 32 +- Test/SqlDom/ParserErrorsTests.cs | 174 + Test/SqlDom/ParserTest.cs | 84 +- Test/SqlDom/TSqlParserTest.cs | 1 + .../AutomaticIndexCompactionTests180.sql | 9 + Test/SqlDom/TestUtilities.cs | 12 + Test/SqlDom/UTSqlScriptDom.csproj | 1 + global.json | 2 +- release-notes/180/180.6.0.md | 26 + 29 files changed, 38122 insertions(+), 53 deletions(-) create mode 100644 .github/instructions/adding_new_parser.guidelines.instructions.md create mode 100644 .github/instructions/database_option.guidelines.instructions.md create mode 100644 .github/skills/add-feature/SKILL.md create mode 100644 SqlScriptDom/Parser/TSql/TSql180.g create mode 100644 SqlScriptDom/Parser/TSql/TSql180Parser.cs create mode 100644 SqlScriptDom/Parser/TSql/TSql180ParserBaseInternal.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/Sql180ScriptGeneratorVisitor.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/Sql180ScriptGenerator.cs create mode 100644 Test/SqlDom/Baselines180/AutomaticIndexCompactionTests180.sql create mode 100644 Test/SqlDom/Only180SyntaxTests.cs create mode 100644 Test/SqlDom/TestScripts/AutomaticIndexCompactionTests180.sql create mode 100644 release-notes/180/180.6.0.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9920c5e8..afc4929c 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -28,6 +28,7 @@ ScriptDom is a library for parsing and generating T-SQL scripts. It is primarily - `Test/SqlDom/` — unit tests, baselines and test scripts. See `Only170SyntaxTests.cs`, `TestScripts/`, and `Baselines170/`. - `.github/instructions/testing.guidelines.instructions.md` — comprehensive testing framework guide with patterns and best practices. - `.github/instructions/function.guidelines.instructions.md` — specialized guide for adding new T-SQL system functions. +- `.github/instructions/database_option.guidelines.instructions.md` — specialized guide for adding database options (ALTER/CREATE DATABASE SET options). ## Developer workflow & conventions (typical change cycle) 1. Add/modify grammar rule(s) in the correct `TSql*.g` (pick the _version_ the syntax belongs to). @@ -202,6 +203,7 @@ include: .github/instructions/parser.guidelines.instructions.md include: .github/instructions/function.guidelines.instructions.md include: .github/instructions/new_data_types.guidelines.instructions.md include: .github/instructions/new_index_types.guidelines.instructions.md +include: .github/instructions/database_option.guidelines.instructions.md include: .github/instructions/debugging_workflow.guidelines.instructions.md include: .github/instructions/grammer.guidelines.instructions.md include: .github/instructions/testing.guidelines.instructions.md diff --git a/.github/instructions/adding_new_parser.guidelines.instructions.md b/.github/instructions/adding_new_parser.guidelines.instructions.md new file mode 100644 index 00000000..ef2c541d --- /dev/null +++ b/.github/instructions/adding_new_parser.guidelines.instructions.md @@ -0,0 +1,797 @@ +# Guidelines for Adding New Parser Versions to SqlScriptDOM + +This guide provides step-by-step instructions for adding support for a new SQL Server version parser to the SqlScriptDOM library. This pattern was established from the TSql180 parser + +## When to Use This Guide + +Use this pattern when: +- ✅ Adding support for a **new SQL Server version** (e.g., SQL Server 2025, vnext releases) +- ✅ Creating a **new parser for a specific compatibility level** (e.g., 180, 190, etc.) +- ✅ Adding a **new SQL engine variant** (e.g., Azure SQL, Fabric DW) + +**Prerequisites:** +- Understand ANTLR v2 grammar syntax +- Familiarity with the ScriptDom parser architecture +- Knowledge of the new SQL Server version's feature set + +## Version Numbering Convention + +SqlScriptDOM uses a version numbering scheme that corresponds to SQL Server versions: +- TSql80 = SQL Server 2000 +- TSql90 = SQL Server 2005 +- TSql100 = SQL Server 2008 +- TSql110 = SQL Server 2012 +- TSql120 = SQL Server 2014 +- TSql130 = SQL Server 2016 +- TSql140 = SQL Server 2017 +- TSql150 = SQL Server 2019 +- TSql160 = SQL Server 2022 +- TSql170 = SQL Server 2025 + +**Naming Pattern**: `TSql{CompatibilityLevel}` where CompatibilityLevel is typically `(MajorVersion - 1900) * 10` + +## Step-by-Step Implementation Guide + +### Step 1: Add SqlVersion Enum Value + +Update the `SqlVersion` enumeration to include the new version. + +**File**: `SqlScriptDom/ScriptDom/SqlServer/SqlVersion.cs` + +```csharp +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + public enum SqlVersion + { + // ... existing versions ... + + /// + /// Sql 18.0 mode + /// + Sql180 = 11, + } +} +``` + +**Key Points**: +- Use the next sequential enum value +- Add XML documentation comment describing the SQL Server version +- Maintain consistent naming: `Sql{CompatibilityLevel}` + +### Step 2: Create Grammar File + +Create a new ANTLR v2 grammar file that inherits from the previous version. + +**File**: `SqlScriptDom/Parser/TSql/TSql180.g` + +```antlr +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +options { + language = "CSharp"; + namespace = "Microsoft.SqlServer.TransactSql.ScriptDom"; +} + +{ + using System.Diagnostics; + using System.Globalization; + using System.Collections.Generic; +} + +class TSql180ParserInternal extends Parser("TSql180ParserBaseInternal"); +options { + k = 2; + defaultErrorHandler=false; + classHeaderPrefix = "internal partial"; + importVocab = TSql; +} + +{ + public TSql180ParserInternal(bool initialQuotedIdentifiersOn) + : base(initialQuotedIdentifiersOn) + { + initialize(); + } +} + +// Entry point rules (required for parser functionality) +entryPointChildObjectName returns [ChildObjectName vResult = null] + : + vResult=childObjectNameWithThreePrefixes + EOF + ; + +entryPointSchemaObjectName returns [SchemaObjectName vResult = null] + : + vResult=schemaObjectThreePartName + EOF + ; + +entryPointScalarDataType returns [DataTypeReference vResult = null] + : + vResult=scalarDataType + EOF + ; + +entryPointExpression returns [ScalarExpression vResult = null] + : + vResult=expression + EOF + ; + +entryPointBooleanExpression returns [BooleanExpression vResult = null] + : + vResult=booleanExpression + EOF + ; + +entryPointStatementList returns [StatementList vResult = null] + : + vResult=statementList + EOF + ; + +// Main script entry point +script returns [TSqlScript vResult = this.FragmentFactory.CreateFragment()] + : + vResult.Batches = batches + EOF + ; + +// Add new version-specific grammar rules below +// For initial version bump, typically inherit all rules from previous version +``` + +**Key Points**: +- Grammar file initially inherits all rules from the previous version via the base class +- Add version-specific rules only when new syntax is needed +- Entry point rules are required for various parsing scenarios +- The `importVocab = TSql` directive imports token definitions + +### Step 3: Add Grammar to Build Configuration + +Register the grammar file in the build system. + +**File**: `SqlScriptDom/GenerateFiles.props` + +```xml + + + + + + +``` + +**Key Points**: +- ANTLR will generate parser code during build from this grammar file +- Generated files go to `$(CsGenIntermediateOutputPath)` (under `obj/`) +- Never manually edit generated parser files + +### Step 4: Create Parser Base Internal Class + +Create the internal parser base class that inherits from the previous version. + +**File**: `SqlScriptDom/Parser/TSql/TSql180ParserBaseInternal.cs` + +```csharp +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +using antlr; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + internal abstract class TSql180ParserBaseInternal : TSql170ParserBaseInternal + { + #region Constructors + + // Required by ANTLR-generated code + protected TSql180ParserBaseInternal(TokenBuffer tokenBuf, int k) + : base(tokenBuf, k) + { + } + + protected TSql180ParserBaseInternal(ParserSharedInputState state, int k) + : base(state, k) + { + } + + protected TSql180ParserBaseInternal(TokenStream lexer, int k) + : base(lexer, k) + { + } + + /// + /// Primary constructor + /// + /// if set to true initial quoted identifiers will be set to on. + public TSql180ParserBaseInternal(bool initialQuotedIdentifiersOn) + : base(initialQuotedIdentifiersOn) + { + } + + #endregion + + /// + /// Gets the SQL version for this parser + /// + protected override SqlVersion SqlVersionCurrent + { + get { return SqlVersion.Sql180; } + } + + // Add version-specific helper methods and overrides here as needed + } +} +``` + +**Key Points**: +- Inherits from previous version's base internal class (e.g., `TSql170ParserBaseInternal`) +- Overrides `SqlVersionCurrent` property to return the new version +- Contains version-specific validation and helper methods +- The multiple constructors are required by ANTLR's generated code + +### Step 5: Create Public Parser Class + +Create the public parser class that users will instantiate. + +**File**: `SqlScriptDom/Parser/TSql/TSql180Parser.cs` + +```csharp +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom.Versioning; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// The TSql Parser for 18.0 + /// + [Serializable] + public class TSql180Parser : TSqlParser + { + /// + /// Parser flavor (standalone/azure/all) + /// + protected SqlEngineType engineType = SqlEngineType.All; + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [initial quoted identifiers]. + public TSql180Parser(bool initialQuotedIdentifiers) + : base(initialQuotedIdentifiers) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [initial quoted identifiers]. + /// Parser engine type + public TSql180Parser(bool initialQuotedIdentifiers, SqlEngineType engineType) + : base(initialQuotedIdentifiers) + { + this.engineType = engineType; + } + + internal override TSqlLexerBaseInternal GetNewInternalLexer() + { + return new TSql180LexerInternal(); + } + + #region Helper Methods + TSql180ParserInternal GetNewInternalParser() + { + return new TSql180ParserInternal(QuotedIdentifier); + } + + TSql180ParserInternal GetNewInternalParserForInput(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParser(); + InitializeInternalParserInput(parser, input, out errors, startOffset, startLine, startColumn); + return parser; + } + #endregion + + /// + /// The main parse method. + /// + /// The list of tokens to parse. + /// The parse errors. + /// The parsed TSqlFragment. + public override TSqlFragment Parse(IList tokens, out IList errors) + { + errors = new List(); + TSql180ParserInternal parser = GetNewInternalParser(); + parser.InitializeForNewInput(tokens, errors, false); + + TSqlFragment result = parser.ParseRuleWithStandardExceptionHandling(parser.script, ScriptEntryMethod); + + // Run versioning visitor for engine-specific validation + if (result != null) + { + VersioningVisitor versioningVisitor = new VersioningVisitor(engineType, SqlVersion.Sql180); + result.Accept(versioningVisitor); + + foreach (ParseError p in versioningVisitor.GetErrors()) + { + errors.Add(p); + } + } + + return result; + } + + /// + /// Parses an input string to get a ChildObjectName. + /// + public override ChildObjectName ParseChildObjectName(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.entryPointChildObjectName, "entryPointChildObjectName"); + } + + /// + /// Parses an input string to get a SchemaObjectName. + /// + public override SchemaObjectName ParseSchemaObjectName(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.entryPointSchemaObjectName, "entryPointSchemaObjectName"); + } + + /// + /// Parses an input string to get a data type. + /// + public override DataTypeReference ParseScalarDataType(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.entryPointScalarDataType, "entryPointScalarDataType"); + } + + /// + /// Parses an input string to get an expression. + /// + public override ScalarExpression ParseExpression(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.entryPointExpression, "entryPointExpression"); + } + + /// + /// Parses an input string to get a boolean expression. + /// + public override BooleanExpression ParseBooleanExpression(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.entryPointBooleanExpression, "entryPointBooleanExpression"); + } + + /// + /// Parses an input string to get a statement list. + /// + public override StatementList ParseStatementList(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.entryPointStatementList, "entryPointStatementList"); + } + + /// + /// Parses an input string to get a subquery expression with optional common table expressions. + /// + public override SelectStatement ParseSubQueryExpressionWithOptionalCTE(TextReader input, out IList errors, + int startOffset, int startLine, int startColumn) + { + TSql180ParserInternal parser = GetNewInternalParserForInput(input, out errors, startOffset, startLine, startColumn); + return parser.ParseRuleWithStandardExceptionHandling(parser.subQueryExpressionWithOptionalCTE, "subQueryExpressionWithOptionalCTE"); + } + } +} +``` + +**Key Points**: +- Public API that developers use to parse T-SQL +- Supports engine type filtering (Standalone, Azure, All) +- Implements all entry point methods for parsing specific constructs +- Runs versioning visitor for version-specific validation + +### Step 6: Create Script Generator + +Create the script generator class for generating T-SQL from the AST. + +**File**: `SqlScriptDom/ScriptDom/SqlServer/Sql180ScriptGenerator.cs` + +```csharp +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Script generator for T-SQL 180 + /// + public sealed class Sql180ScriptGenerator : SqlScriptGenerator + { + /// + /// Initializes a new instance of the class. + /// + public Sql180ScriptGenerator() + : this(new SqlScriptGeneratorOptions()) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The options. + public Sql180ScriptGenerator(SqlScriptGeneratorOptions options) + : base(options) + { + options.SqlVersion = SqlVersion.Sql180; + } + + internal override SqlScriptGeneratorVisitor CreateSqlScriptGeneratorVisitor( + SqlScriptGeneratorOptions options, ScriptWriter scriptWriter) + { + ScriptGeneratorSupporter.CheckForNullReference(options, "options"); + ScriptGeneratorSupporter.CheckForNullReference(scriptWriter, "scriptWriter"); + + return new Sql180ScriptGeneratorVisitor(options, scriptWriter); + } + } +} +``` + +**Key Points**: +- Sealed class that cannot be inherited +- Sets `SqlVersion.Sql180` in options +- Creates version-specific visitor for AST traversal + +### Step 7: Create Script Generator Visitor + +Create the visitor class that generates T-SQL from the AST. + +**File**: `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/Sql180ScriptGeneratorVisitor.cs` + +```csharp +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + internal partial class Sql180ScriptGeneratorVisitor : Sql170ScriptGeneratorVisitor + { + public Sql180ScriptGeneratorVisitor(SqlScriptGeneratorOptions options, ScriptWriter writer) + : base(options, writer) + { + } + + // Add version-specific visitor overrides here as needed + // Override visit methods for AST nodes that have new syntax in this version + } +} +``` + +**Key Points**: +- Inherits from previous version's visitor (e.g., `Sql170ScriptGeneratorVisitor`) +- Override visit methods only for nodes with new version-specific syntax +- Uses visitor pattern to traverse and generate T-SQL from AST + +### Step 8: Update TSqlParser Factory + +Add the new version to the parser factory method. + +**File**: `SqlScriptDom/Parser/TSql/TSqlParser.cs` + +Find the `CreateParser` method and add a case: + +```csharp +public static TSqlParser CreateParser(SqlVersion tsqlParserVersion, bool initialQuotedIdentifiers = false) +{ + switch (tsqlParserVersion) + { + // ... existing cases ... + case SqlVersion.Sql170: + return new TSql170Parser(initialQuotedIdentifiers); + case SqlVersion.Sql180: + return new TSql180Parser(initialQuotedIdentifiers); + default: + throw new ArgumentException( + String.Format(CultureInfo.CurrentCulture, + SqlScriptGeneratorResource.UnknownEnumValue, + tsqlParserVersion, + "TSqlParserVersion"), + "tsqlParserVersion"); + } +} +``` + +### Step 9: Add SqlVersionFlags Support + +Add version flags for the new version if needed for validation logic. + +**File**: `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` + +```csharp +[Flags] +internal enum SqlVersionFlags +{ + // ... existing flags ... + TSql170AndAbove = TSql170 | TSql180, + TSql180 = 0x00000800, + TSql180AndAbove = TSql180, +} +``` + +**Key Points**: +- Add individual version flag as power of 2 +- Add `AndAbove` flag combining all versions >= this version +- Used for validation logic that checks syntax availability + +### Step 10: Update OptionsHelper (if needed) + +If the new version introduces new options or changes option availability, update the options helper. + +**File**: `SqlScriptDom/Parser/TSql/OptionsHelper.cs` + +Add version checks where options become available: + +```csharp +// Example: if a new option becomes available in 180 +internal static bool IsOptionValidForVersion(IndexOptionKind option, SqlVersion version) +{ + switch (option) + { + // ... existing options ... + case IndexOptionKind.NewOption: + return version >= SqlVersion.Sql180; + default: + return true; + } +} +``` + +### Step 11: Create Test Infrastructure + +Create test class for version-specific syntax tests. + +**File**: `Test/SqlDom/Only180SyntaxTests.cs` + +```csharp +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using System; +using System.Collections.Generic; +using System.IO; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + public partial class SqlDomTests + { + // Note: These filenames are case sensitive, match checked-in files exactly + private static readonly ParserTest[] Only180TestInfos = + { + // Add new 180-specific tests here as needed + // Example: + // new ParserTest180("NewFeatureTest180.sql"), + }; + + private static readonly ParserTest[] SqlAzure180_TestInfos = + { + // Add Azure-specific syntax tests here + }; + + /// + /// Test method for TSql180 version-specific syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TSql180SyntaxTests() + { + TSql180Parser parser = new TSql180Parser(true); + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + + foreach (ParserTest t in Only180TestInfos) + { + ParserTest.ParseAndVerify(parser, scriptGen, t); + } + } + + /// + /// Test method for Azure-specific TSql180 syntax + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TSql180AzureSyntaxTests() + { + TSql180Parser parser = new TSql180Parser(true, SqlEngineType.SqlAzure); + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + + foreach (ParserTest t in SqlAzure180_TestInfos) + { + ParserTest.ParseAndVerify(parser, scriptGen, t); + } + } + } +} +``` + +### Step 12: Create Baselines Folder + +Create the baselines folder for test output files. + +**Directory**: `Test/SqlDom/Baselines180/` + +- Create this folder even if initially empty +- Test baseline files (expected T-SQL output) will be placed here +- Baselines are generated from test runs and verified manually + +### Step 13: Update Test Project Configuration + +Add the baselines folder to embedded resources. + +**File**: `Test/SqlDom/UTSqlScriptDom.csproj` + +```xml + + + + + + + + +``` + +### Step 14: Add Parser Test Helper Methods + +Add test utility methods for the new version. + +**File**: `Test/SqlDom/ParserTest.cs` + +Add constructor helper method: + +```csharp +/// +/// Creates a parser test for TSql180 with specified error expectations +/// +public static ParserTest ParserTest180( + string fileName, + int nErrors80 = 0, int nErrors90 = 0, int nErrors100 = 0, + int nErrors110 = 0, int nErrors120 = 0, int nErrors130 = 0, + int nErrors140 = 0, int nErrors150 = 0, int nErrors160 = 0, + int nErrors170 = 0, int nErrors180 = 0, int nErrorsFabricDW = int.MaxValue) +{ + return new ParserTest( + fileName, + new int[] + { + nErrors80, nErrors90, nErrors100, nErrors110, + nErrors120, nErrors130, nErrors140, nErrors150, + nErrors160, nErrors170, nErrors180, nErrorsFabricDW + }); +} +``` + +**File**: `Test/SqlDom/TestUtilities.cs` + +Update the error count array handling to support the new version index. + +### Step 15: Add Version Mapping Tests + +Add tests to verify version enum and parser mapping. + +**File**: `Test/SqlDom/TSqlParserTest.cs` + +```csharp +[TestMethod] +public void TSql180ParserVersionTest() +{ + TSqlParser parser = TSqlParser.CreateParser(SqlVersion.Sql180); + Assert.IsNotNull(parser); + Assert.IsInstanceOfType(parser, typeof(TSql180Parser)); +} +``` + +### Step 16: Build and Verify + +Build the project to generate parser code and verify everything compiles. + +```bash +# Build the ScriptDom project +dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug + +# Run tests to verify +dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug +``` + +**What Happens During Build**: +1. ANTLR generates lexer and parser C# files from `.g` grammar +2. Post-processing scripts clean up generated code +3. Generated files are compiled along with hand-written sources +4. Test baselines are embedded as resources + +## Summary Checklist + +When adding a new parser version, ensure you complete: + +- [ ] **Step 1**: Add `SqlVersion` enum value +- [ ] **Step 2**: Create `.g` grammar file +- [ ] **Step 3**: Add grammar to `GenerateFiles.props` +- [ ] **Step 4**: Create `TSqlXXXParserBaseInternal.cs` +- [ ] **Step 5**: Create `TSqlXXXParser.cs` +- [ ] **Step 6**: Create `SqlXXXScriptGenerator.cs` +- [ ] **Step 7**: Create `SqlXXXScriptGeneratorVisitor.cs` +- [ ] **Step 8**: Update `TSqlParser.cs` factory method +- [ ] **Step 9**: Add `SqlVersionFlags` support +- [ ] **Step 10**: Update `OptionsHelper.cs` if needed +- [ ] **Step 11**: Create `OnlyXXXSyntaxTests.cs` +- [ ] **Step 12**: Create `BaselinesXXX/` folder +- [ ] **Step 13**: Update `UTSqlScriptDom.csproj` +- [ ] **Step 14**: Add parser test helper methods +- [ ] **Step 15**: Add version mapping tests +- [ ] **Step 16**: Build and verify everything compiles + +## Common Pitfalls + +1. **Forgetting to add grammar to GenerateFiles.props**: Parser won't be generated +2. **Incorrect inheritance chain**: Must inherit from previous version's base class +3. **Missing entry point rules in grammar**: Certain parsing scenarios will fail +4. **Not creating Baselines folder**: Test project won't build due to missing embedded resources +5. **Wrong enum value**: Can conflict with existing versions or break version comparison logic +6. **Missing SqlVersionFlags**: Validation logic may not work correctly +7. **Not updating factory method**: Parser can't be instantiated via factory + +## Related Documentation + +- [Testing Guidelines](testing.guidelines.instructions.md) - How to add tests for new syntax +- [Bug Fixing Guidelines](bug_fixing.guidelines.instructions.md) - How to add new grammar rules +- [Grammar Guidelines](grammer.guidelines.instructions.md) - ANTLR v2 grammar patterns +- [Validation Fix Guidelines](Validation_fix.guidelines.instructions.md) - Version-gated validation + +## References + +- Example Implementation: TSql180 parser (commits 0b84f8f through f4f4c88) +- ANTLR v2 Documentation: See `tools/antlr-2.7.5` documentation +- Build System: See `SqlScriptDom/GenerateFiles.props` for generation targets diff --git a/.github/instructions/database_option.guidelines.instructions.md b/.github/instructions/database_option.guidelines.instructions.md new file mode 100644 index 00000000..825408d9 --- /dev/null +++ b/.github/instructions/database_option.guidelines.instructions.md @@ -0,0 +1,493 @@ +# Adding Database Options to ScriptDOM + +This guide covers how to add new database options to `ALTER DATABASE` and `CREATE DATABASE` statements in ScriptDOM. + +## Decision Tree: Choose Your Implementation Pattern + +``` +What values does your database option accept? +│ +├─ Simple ON/OFF only +│ └─ Pattern A: Use Generic OnOffDatabaseOption (easiest) +│ Examples: AutoClose, AutoShrink, DataRetention +│ +├─ ON/OFF with sub-options (e.g., CHANGE_TRACKING (AUTO_CLEANUP = ON)) +│ └─ Pattern B: Custom AST Class + Complex Sub-options +│ Examples: ChangeTrackingDatabaseOption, QueryStoreDatabaseOption +│ +├─ Specific enum values (e.g., FULL, BULK_LOGGED, SIMPLE) +│ └─ Pattern C: Custom AST Class + Enum Helper +│ Examples: RecoveryDatabaseOption, PageVerifyDatabaseOption +│ +└─ Special behavior (only output when ON, custom formatting) + └─ Pattern D: Custom AST Class + Custom Script Generator + Examples: LedgerOption, OptimizedLockingDatabaseOption +``` + +--- + +## Pattern A: Generic ON/OFF Database Option (Recommended for Simple Cases) + +Use this pattern when your option only accepts `ON` or `OFF` values. + +### Step 1: Add to DatabaseOptionKind Enum + +**File**: `SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs` + +```csharp +public enum DatabaseOptionKind +{ + // ... existing options ... + OptimizedLocking = 71, + YourNewOption = 72 // ← Add your option +} +``` + +### Step 2: Add Keyword Constant + +**File**: `SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs` + +Add in alphabetical order within the Auto* section: + +```csharp +internal const string YourOption = "YOUR_OPTION"; +internal const string AutomaticTuning = "AUTOMATIC_TUNING"; +internal const string AutoShrink = "AUTO_SHRINK"; +``` + +### Step 3: Register in OnOffSimpleDbOptionsHelper + +**File**: `SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs` + +Add to the constructor under the appropriate version: + +```csharp +// 170 options +AddOptionMapping(DatabaseOptionKind.YourNewOption, + CodeGenerationSupporter.YourOption, + SqlVersionFlags.TSql170AndAbove); +``` + +### Step 4: Add to RequiresEqualsSign Method (If Needed) + +Some options require `=` between option name and value (e.g., `LEDGER = ON`). If your option needs this: + +**File**: `SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs` + +```csharp +internal bool RequiresEqualsSign(DatabaseOptionKind optionKind) +{ + switch (optionKind) + { + case DatabaseOptionKind.MemoryOptimizedElevateToSnapshot: + case DatabaseOptionKind.NestedTriggers: + case DatabaseOptionKind.TransformNoiseWords: + case DatabaseOptionKind.Ledger: + case DatabaseOptionKind.YourNewOption: // ← Add here if needed + return true; + default: + return false; + } +} +``` + +### Step 5: Create Test Files + +**Test Script**: `Test/SqlDom/TestScripts/AlterDatabaseYourOption170.sql` + +```sql +-- YourOption for VNext and Azure +ALTER DATABASE db + SET YOUR_OPTION = ON; + +ALTER DATABASE db + SET YOUR_OPTION = OFF; +``` + +**Baseline**: `Test/SqlDom/Baselines170/AlterDatabaseYourOption170.sql` + +```sql +ALTER DATABASE db + SET YOUR_OPTION = ON; + +ALTER DATABASE db + SET YOUR_OPTION = OFF; +``` + +**Test Configuration**: `Test/SqlDom/Only170SyntaxTests.cs` + +```csharp +new ParserTest170("AlterDatabaseYourOption170.sql", + nErrors80: 2, nErrors90: 2, nErrors100: 2, + nErrors110: 2, nErrors120: 2, nErrors130: 2, + nErrors140: 2, nErrors150: 2, nErrors160: 2), +``` + +### Pattern A Complete - No Ast.xml or Script Generator Changes Needed! + +--- + +## Pattern B: Custom AST Class with Sub-Options + +Use when your option has complex sub-options (e.g., `CHANGE_TRACKING (AUTO_CLEANUP = ON)`). + +### Example: ChangeTrackingDatabaseOption + +#### Step 1-3: Same as Pattern A + +Add to enum, CodeGenerationSupporter, and helpers as in Pattern A. + +#### Step 4: Define Custom AST Class + +**File**: `SqlScriptDom/Parser/TSql/Ast.xml` + +```xml + + + + + + + + + + + + + + + + + +``` + +#### Step 5: Create Custom Script Generator + +**File**: `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.YourOptionDatabaseOption.cs` + +```csharp +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(YourOptionDatabaseOption node) + { + GenerateIdentifier(CodeGenerationSupporter.YourOption); + GenerateSpaceAndKeyword(TSqlTokenType.EqualsSign); + GenerateSpace(); + GenerateOptionStateOnOff(node.OptionState); + + if (node.Details != null && node.Details.Count > 0) + { + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.Details); + } + } + + public override void ExplicitVisit(SubOption1Detail node) + { + GenerateNameEqualsValue( + CodeGenerationSupporter.SubOption1, + node.IsOn ? TSqlTokenType.On : TSqlTokenType.Off); + } + + public override void ExplicitVisit(SubOption2Detail node) + { + GenerateNameEqualsValue( + CodeGenerationSupporter.SubOption2, + node.Value); + } + } +} +``` + +#### Step 6: Update Grammar File + +**File**: `SqlScriptDom/Parser/TSql/TSql170.g` + +Add grammar rules to parse your option and sub-options. + +--- + +## Pattern C: Custom AST Class with Enum Values + +Use when your option accepts specific enum values (not just ON/OFF). + +### Example: RecoveryDatabaseOption + +#### Step 1-2: Add Enum and Keyword + +Same as Pattern A, plus define value enum: + +**File**: `SqlScriptDom/Parser/TSql/RecoveryDatabaseOptionKind.cs` + +```csharp +public enum RecoveryDatabaseOptionKind +{ + Full = 0, + BulkLogged = 1, + Simple = 2 +} +``` + +#### Step 3: Define Custom AST Class + +**File**: `SqlScriptDom/Parser/TSql/Ast.xml` + +```xml + + + + +``` + +#### Step 4: Create Helper for Values + +**File**: `SqlScriptDom/Parser/TSql/RecoveryDbOptionsHelper.cs` + +```csharp +internal class RecoveryDbOptionsHelper : OptionsHelper +{ + private RecoveryDbOptionsHelper() + { + AddOptionMapping(RecoveryDatabaseOptionKind.Full, + CodeGenerationSupporter.Full); + AddOptionMapping(RecoveryDatabaseOptionKind.BulkLogged, + CodeGenerationSupporter.BulkLogged); + AddOptionMapping(RecoveryDatabaseOptionKind.Simple, + CodeGenerationSupporter.Simple); + } + + internal static readonly RecoveryDbOptionsHelper Instance = + new RecoveryDbOptionsHelper(); +} +``` + +#### Step 5: Create Script Generator + +**File**: `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.RecoveryDatabaseOption.cs` + +```csharp +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(RecoveryDatabaseOption node) + { + GenerateIdentifier(CodeGenerationSupporter.Recovery); + GenerateSpace(); + RecoveryDbOptionsHelper.Instance.GenerateSourceForOption( + _writer, node.Value); + } + } +} +``` + +--- + +## Pattern D: Custom AST Class with Special Script Generation + +Use when the option has special formatting or conditional output. + +### Example: LedgerOption (Only outputs when ON) + +#### Step 1-2: Same as Pattern A + +#### Step 3: Define Custom AST Class + +**File**: `SqlScriptDom/Parser/TSql/Ast.xml` + +```xml + + + + +``` + +#### Step 4: Create Custom Script Generator + +**File**: `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.LedgerOption.cs` + +```csharp +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(LedgerOption node) + { + System.Diagnostics.Debug.Assert( + node.OptionKind == DatabaseOptionKind.Ledger); + + // Special behavior: Only output when ON + if (node.OptionState == OptionState.On) + { + GenerateNameEqualsValue( + CodeGenerationSupporter.Ledger, + node.OptionState.ToString()); + } + } + } +} +``` + +--- + +## Testing Checklist + +For all patterns: + +- [ ] Database option enum added to `DatabaseOptionKind.cs` +- [ ] Keyword constant added to `CodeGenerationSupporter.cs` +- [ ] Option registered in appropriate helper class +- [ ] Test script created in `TestScripts/` +- [ ] Baseline created in `Baselines/` +- [ ] Test configured in `OnlySyntaxTests.cs` +- [ ] Parser builds successfully +- [ ] Specific test passes +- [ ] **Full test suite passes** (593/593 tests) + +For Patterns B, C, D (Custom AST): + +- [ ] AST class defined in `Ast.xml` +- [ ] Custom script generator created (if needed) +- [ ] Helper class created (for enum values) +- [ ] Grammar rules updated (if new syntax) + +--- + +## Common Pitfalls + +### 1. Forgetting to Rebuild After Ast.xml Changes + +```bash +# Always rebuild after modifying Ast.xml +dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug +``` + +### 2. Incorrect Error Counts in Tests + +Error count = number of statements in test script that use the new option. + +```csharp +// WRONG: Count doesn't match statements +new ParserTest170("TwoStatements.sql", nErrors160: 1) // ❌ + +// RIGHT: Match statement count +new ParserTest170("TwoStatements.sql", nErrors160: 2) // ✓ +``` + +### 3. Missing RequiresEqualsSign Registration + +Some options need `=` between name and value: +- With `=`: `LEDGER = ON`, `AUTOMATIC_INDEX_COMPACTION = ON` +- Without `=`: `AUTO_CLOSE ON`, `AUTO_SHRINK ON` + +Check existing similar options to determine which pattern to follow. + +### 4. Not Running Full Test Suite + +Grammar changes can break unrelated tests. Always run: + +```bash +dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug +``` + +--- + +## Examples Reference + +### Pattern A Examples (Generic ON/OFF) +- `AutoClose` +- `AutoShrink` +- `DataRetention` + +**Files to check**: +- `DatabaseOptionKind.cs` (enum value) +- `OnOffSimpleDbOptionsHelper.cs` (registration) +- No Ast.xml changes needed +- No custom script generator needed + +### Pattern B Examples (Sub-Options) +- `ChangeTrackingDatabaseOption` +- `QueryStoreDatabaseOption` +- `AutomaticTuningDatabaseOption` + +**Files to check**: +- All Pattern A files, plus: +- `Ast.xml` (custom class with Details collection) +- Custom script generator + +### Pattern C Examples (Enum Values) +- `RecoveryDatabaseOption` +- `PageVerifyDatabaseOption` +- `CursorDefaultDatabaseOption` + +**Files to check**: +- All Pattern A files, plus: +- `Ast.xml` (custom class with Value member) +- Helper class for enum mapping +- Custom script generator + +### Pattern D Examples (Special Behavior) +- `LedgerOption` (only outputs when ON) +- `OptimizedLockingDatabaseOption` (custom formatting) + +**Files to check**: +- All Pattern A files, plus: +- `Ast.xml` (custom class) +- Custom script generator with special logic + +--- + +## Quick Reference: File Locations + +| Component | Path | +|-----------|------| +| Database option enum | `SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs` | +| Keyword constants | `SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs` | +| ON/OFF helper | `SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs` | +| Other option helpers | `SqlScriptDom/Parser/TSql/DatabaseOptionKindHelper.cs` | +| AST definitions | `SqlScriptDom/Parser/TSql/Ast.xml` | +| Script generators | `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/` | +| Test scripts | `Test/SqlDom/TestScripts/` | +| Baselines | `Test/SqlDom/Baselines/` | +| Test classes | `Test/SqlDom/OnlySyntaxTests.cs` | + +--- + +## Version Flags Reference + +```csharp +SqlVersionFlags.TSql80 // SQL Server 2000 +SqlVersionFlags.TSql90 // SQL Server 2005 +SqlVersionFlags.TSql100 // SQL Server 2008 +SqlVersionFlags.TSql110 // SQL Server 2012 +SqlVersionFlags.TSql120 // SQL Server 2014 +SqlVersionFlags.TSql130 // SQL Server 2016 +SqlVersionFlags.TSql140 // SQL Server 2017 +SqlVersionFlags.TSql150 // SQL Server 2019 +SqlVersionFlags.TSql160 // SQL Server 2022 +SqlVersionFlags.TSql170 // SQL Server 2025 +SqlVersionFlags.TSqlFabricDW // Fabric DW + +// Combined flags +SqlVersionFlags.TSql170AndAbove // SQL 2025+ +SqlVersionFlags.TSql160AndAbove // SQL 2022+ +``` + +For Azure SQL Database, Fabric, VNext: Use the latest version (currently `TSql170AndAbove`). diff --git a/.github/skills/add-feature/SKILL.md b/.github/skills/add-feature/SKILL.md new file mode 100644 index 00000000..ce63becb --- /dev/null +++ b/.github/skills/add-feature/SKILL.md @@ -0,0 +1,282 @@ +--- +name: add-feature +description: Add new T-SQL features to ScriptDOM parser. Asks questions about SQL Server version and feature type, then guides through grammar changes, AST updates, script generation, and testing using existing instruction files. Handles syntax additions, new functions, data types, index types, and validation rules. +argument-hint: "Feature description (e.g., 'Add VECTOR data type', 'Add JSON_OBJECT function')" +user-invocable: true +platforms: "SQL Server, Azure SQL DB, Fabric, Fabric DW, VNext" +--- + +## Overview + +This skill helps add new T-SQL features to the ScriptDOM parser by: +1. **Interviewing** you about the feature and target platform (SQL Server, Azure SQL DB, Fabric, Fabric DW, VNext) +2. **Determining the latest parser version** from `SqlVersionFlags.cs` (currently TSql170) +3. **Routing** you to the appropriate parser: + - SQL Server → version-specific parser (TSql120-170) + - Azure SQL DB/Fabric/VNext → latest parser version + - Fabric DW → separate TSqlFabricDW parser +4. **Classifying** the change type (grammar, validation, function, data type, etc.) +5. **Guiding** through implementation and testing without duplicating existing documentation + +--- + +## Step 1: Feature Discovery Interview + +Ask the user these questions to understand the feature: + +### Required Questions +1. **What T-SQL feature are you adding?** + - Example: "VECTOR data type", "JSON_OBJECT function", "RESUMABLE option for ALTER TABLE" + +2. **Which platform is this feature for?** + - **SQL Server** (on-premises / standalone) + - **Azure SQL Database** (uses latest parser version) + - **Fabric** (uses latest parser version) + - **Fabric DW** (uses separate TSqlFabricDW parser) + - **VNext** (future version, uses latest parser version) + +3. **If SQL Server, which version introduced this feature?** + - SQL Server 2014 (TSql120) + - SQL Server 2016 (TSql130) + - SQL Server 2017 (TSql140) + - SQL Server 2019 (TSql150) + - SQL Server 2022 (TSql160) + - SQL Server 2025 (TSql170) + - *(Skip if Azure SQL DB, Fabric, or VNext - these use latest version)* + +4. **Do you have example T-SQL syntax or Microsoft documentation links?** + - This helps verify the exact syntax requirements + +### Optional Context Questions +4. **Is this a new syntax element or enabling existing syntax in a new context?** + - New syntax: Requires grammar rules, AST nodes + - Validation fix: May only need version checks in validation code + +5. **Does similar syntax already work in other contexts?** + - Example: "RESUMABLE works for ALTER INDEX but not ALTER TABLE" + - This indicates a validation issue rather than missing grammar + +--- + +## Step 2: Determine Feature Type + +Based on the answers, classify the feature into one of these types: + +### Type A: Validation-Only Fix +**Indicators:** +- Similar syntax already works elsewhere in SQL +- Error message says "Option 'X' is not valid..." or "Feature 'Y' not supported..." +- The grammar may already parse it, but validation blocks it + +**→ Route to:** [grammar_validation.guidelines.instructions.md](../../instructions/grammar_validation.guidelines.instructions.md) + +### Type B: New Grammar/Syntax +**Indicators:** +- Completely new statement, clause, or operator +- Error says "Incorrect syntax near..." or "Unexpected token..." +- Parser doesn't recognize the syntax at all + +**→ Route to:** [bug_fixing.guidelines.instructions.md](../../instructions/bug_fixing.guidelines.instructions.md) + +### Type C: New System Function +**Indicators:** +- Adding a new built-in T-SQL function (e.g., JSON_OBJECT, STRING_AGG) +- May need special handling for RETURN statement contexts + +**→ Route to:** [function.guidelines.instructions.md](../../instructions/function.guidelines.instructions.md) + +### Type D: New Data Type +**Indicators:** +- Adding a completely new SQL Server data type (e.g., VECTOR, GEOGRAPHY) +- Requires custom parameter syntax (e.g., `VECTOR(1536, FLOAT32)`) + +**→ Route to:** [new_data_types.guidelines.instructions.md](../../instructions/new_data_types.guidelines.instructions.md) + +### Type E: New Index Type +**Indicators:** +- Adding a new CREATE INDEX variant (e.g., VECTOR INDEX, JSON INDEX) +- Requires specialized syntax different from standard indexes + +**→ Route to:** [new_index_types.guidelines.instructions.md](../../instructions/new_index_types.guidelines.instructions.md) + +### Type F: Parser Predicate Recognition (Parentheses) +**Indicators:** +- Identifier-based predicate works without parentheses but fails with them +- Error near closing parenthesis: `WHERE (REGEXP_LIKE(...))` fails + +**→ Route to:** [parser.guidelines.instructions.md](../../instructions/parser.guidelines.instructions.md) + +### Type G: Database Option (ALTER/CREATE DATABASE SET) +**Indicators:** +- Adding a database option for ALTER DATABASE or CREATE DATABASE statements +- Simple ON/OFF option (e.g., `SET AUTOMATIC_INDEX_COMPACTION = ON`) +- Complex option with sub-options (e.g., `SET CHANGE_TRACKING (AUTO_CLEANUP = ON)`) +- Enum-based option (e.g., `SET RECOVERY FULL`) + +**→ Route to:** [database_option.guidelines.instructions.md](../../instructions/database_option.guidelines.instructions.md) + +--- + +## Step 3: Grammar Rule Development + +For grammar changes (Types B, C, D, E, G), follow this workflow: + +### 3.1 Identify Target Grammar File + +**First, determine the latest parser version:** +Check `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` for the highest TSql version enum value (currently TSql170). + +**Then select the appropriate grammar file:** + +#### For SQL Server (on-premises): +- SQL 2014+: TSql120.g +- SQL 2016+: TSql130.g +- SQL 2017+: TSql140.g +- SQL 2019+: TSql150.g +- SQL 2022+: TSql160.g +- SQL 2025+: TSql170.g + +#### For Azure SQL Database, Fabric, VNext: +- Use the **latest parser version** (e.g., TSql170.g) +- Check `SqlVersionFlags.cs` to confirm the highest version + +#### For Fabric DW: +- Use **TSqlFabricDW.g** (separate parser with Fabric-specific syntax) + +### 3.2 Grammar Development Patterns +**Reference:** [grammar.guidelines.instructions.md](../../instructions/grammar.guidelines.instructions.md) + +Key patterns: +- Use `this.FragmentFactory.CreateFragment()` for AST nodes +- Use syntactic predicates `(LA(1) == Token)` for lookahead +- Avoid modifying shared grammar rules (create specialized versions instead) +- Include proper script generation in `ScriptGenerator` + +### 3.3 AST Updates +If adding new AST nodes: +1. Edit `SqlScriptDom/Parser/TSql/Ast.xml` +2. Rebuild to regenerate visitor classes +3. Implement script generation in `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator` + +--- + +## Step 4: Testing + +**Reference:** [testing.guidelines.instructions.md](../../instructions/testing.guidelines.instructions.md) + +### 4.1 Create Test Files +1. **Input Script**: `Test/SqlDom/TestScripts/YourFeature.sql` + - Include all syntax variations + - Test edge cases, parameters, expressions + +2. **Baseline**: `Test/SqlDom/Baselines/YourFeature.sql` + - Expected pretty-printed output after parse → script gen → reparse + +### 4.2 Add Test Method + +#### For SQL Server versions (TSql120-170): +In `Test/SqlDom/OnlySyntaxTests.cs`: + +```csharp +[TestMethod] +public void YourFeatureTest() +{ + ParserTest("YourFeature.sql"); +} +``` + +#### For Fabric DW: +Add to the `OnlyFabricDWTestInfos` array in `Test/SqlDom/OnlyFabricDWSyntaxTests.cs`: + +```csharp +new ParserTestFabricDW("YourFeatureFabricDW.sql", + nErrors80: X, nErrors90: Y, nErrors100: Z, + nErrors110: A, nErrors120: B, nErrors130: C, + nErrors140: D, nErrors150: E, nErrors160: F, nErrors170: G), +``` +*(Set expected error counts for each parser version)* + +**Simplified patterns available** - see testing guidelines for: +- `ParserTestAllowingErrors` - for scripts with expected parse errors +- `ParserTestOutput` constructors - for custom output verification +- Error message verification - exact match or fragment-based + +### 4.3 Run Tests +```bash +# Build to regenerate parser +dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug + +# Run specific test +dotnet test --filter "FullyQualifiedName~YourFeatureTest" -c Debug + +# ALWAYS run full suite before committing +dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug +``` + +--- + +## Step 5: Debugging and Troubleshooting + +**Reference:** [debugging_workflow.guidelines.instructions.md](../../instructions/debugging_workflow.guidelines.instructions.md) + +Common issues: +- **Tests fail after grammar changes**: Likely modified a shared rule - create specialized version +- **Script generation mismatch**: Update `ScriptGenerator` for your AST nodes +- **Version errors**: Check validation code in `TSql80ParserBaseInternal.cs` + +--- + +## Step 6: Implementation Checklist + +Before marking the feature complete: + +- [ ] Grammar rules added/modified in correct `TSql.g` or `TSqlFabricDW.g` file +- [ ] AST nodes defined in `Ast.xml` (if new nodes needed) +- [ ] Script generation implemented for new AST nodes +- [ ] Validation rules updated (if version-gated) +- [ ] Test script created in `TestScripts/` (use appropriate suffix: `.sql` or `FabricDW.sql`) +- [ ] Baseline created in `Baselines/` or `BaselinesFabricDW/` +- [ ] Test method added to `OnlySyntaxTests.cs` or `OnlyFabricDWSyntaxTests.cs` +- [ ] All tests pass (including full test suite) +- [ ] No regressions in unrelated tests + +--- + +## Quick Reference: File Locations + +| Component | Path | +|-----------|------| +| Grammar files (SQL Server) | `SqlScriptDom/Parser/TSql/TSql*.g` | +| Grammar file (Fabric DW) | `SqlScriptDom/Parser/TSql/TSqlFabricDW.g` | +| Version detection | `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` | +| AST definition | `SqlScriptDom/Parser/TSql/Ast.xml` | +| Script generator | `SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator` | +| Validation code | `SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs` | +| Test scripts | `Test/SqlDom/TestScripts/` | +| Baselines | `Test/SqlDom/Baselines/` or `BaselinesFabricDW/` | +| Test classes | `Test/SqlDom/OnlySyntaxTests.cs` or `FabricDWSyntaxTests.cs` | + +--- + +## Agent Workflow + +When invoked, the agent should: + +1. **Determine the latest parser version** by reading `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` +2. **Interview the user** using the questions in Step 1 + - Ask about platform (SQL Server, Azure SQL DB, Fabric, Fabric DW, VNext) + - For Azure/Fabric/VNext → use latest parser version + - For Fabric DW → use TSqlFabricDW.g + - For SQL Server → ask for specific version +3. **Classify the feature type** using Step 2 criteria +4. **Load the appropriate instruction file** using `read_file` tool +5. **Guide through implementation** by referencing specific sections of the loaded instruction file +6. **Execute the development workflow**: + - Make grammar/validation changes + - Regenerate parser (build) + - Create test files + - Run tests + - Debug failures +7. **Verify completeness** using Step 6 checklist + +**Never duplicate content from instruction files** - always reference and quote specific sections. diff --git a/SqlScriptDom/GenerateFiles.props b/SqlScriptDom/GenerateFiles.props index b94a61f5..ea6f573b 100644 --- a/SqlScriptDom/GenerateFiles.props +++ b/SqlScriptDom/GenerateFiles.props @@ -13,6 +13,7 @@ + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index d10f1b87..0ea67317 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -155,6 +155,7 @@ internal static class CodeGenerationSupporter internal const string AutoClose = "AUTO_CLOSE"; internal const string AutoCreateStatistics = "AUTO_CREATE_STATISTICS"; internal const string AutoDrop = "AUTO_DROP"; + internal const string AutomaticIndexCompaction = "AUTOMATIC_INDEX_COMPACTION"; internal const string AutogrowAllFiles = "AUTOGROW_ALL_FILES"; internal const string AutogrowSingleFile = "AUTOGROW_SINGLE_FILE"; internal const string Automatic = "AUTOMATIC"; diff --git a/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs b/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs index 84d3832f..0786065b 100644 --- a/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs +++ b/SqlScriptDom/Parser/TSql/DatabaseOptionKind.cs @@ -99,7 +99,12 @@ public enum DatabaseOptionKind ManualCutover = 69, PerformCutover = 70, - OptimizedLocking = 71 + OptimizedLocking = 71, + + // T-SQL 170 On/Off options + + // T-SQL 180 On/Off options + AutomaticIndexCompaction = 72 } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs b/SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs index 696b6cf7..b071c36f 100644 --- a/SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs +++ b/SqlScriptDom/Parser/TSql/OnOffSimpleDbOptionsHelper.cs @@ -64,7 +64,9 @@ private OnOffSimpleDbOptionsHelper() AddOptionMapping(DatabaseOptionKind.Ledger, CodeGenerationSupporter.Ledger, SqlVersionFlags.TSql160AndAbove); // 170 options - // TODO: add any new 170 options here + + // 180 options + AddOptionMapping(DatabaseOptionKind.AutomaticIndexCompaction, CodeGenerationSupporter.AutomaticIndexCompaction, SqlVersionFlags.TSql180AndAbove); } @@ -83,6 +85,7 @@ internal bool RequiresEqualsSign(DatabaseOptionKind optionKind) case DatabaseOptionKind.NestedTriggers: case DatabaseOptionKind.TransformNoiseWords: case DatabaseOptionKind.Ledger: + case DatabaseOptionKind.AutomaticIndexCompaction: return true; default: return false; diff --git a/SqlScriptDom/Parser/TSql/OptionsHelper.cs b/SqlScriptDom/Parser/TSql/OptionsHelper.cs index 7262ab68..a14a9e5b 100644 --- a/SqlScriptDom/Parser/TSql/OptionsHelper.cs +++ b/SqlScriptDom/Parser/TSql/OptionsHelper.cs @@ -128,6 +128,8 @@ internal SqlVersionFlags MapSqlVersionToSqlVersionFlags(SqlVersion sqlVersion) return SqlVersionFlags.TSql160; case SqlVersion.Sql170: return SqlVersionFlags.TSql170; + case SqlVersion.Sql180: + return SqlVersionFlags.TSql180; case SqlVersion.SqlFabricDW: return SqlVersionFlags.TSqlFabricDW; default: diff --git a/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs b/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs index 23bb379f..60496e30 100644 --- a/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs +++ b/SqlScriptDom/Parser/TSql/SqlVersionFlags.cs @@ -24,19 +24,21 @@ internal enum SqlVersionFlags TSql150 = 0x80, TSql160 = 0x100, TSql170 = 0x200, - TSqlFabricDW = 0x400, + TSqlFabricDW = 0x400, + TSql180 = 0x800, - TSqlAll = TSql80 | TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql90AndAbove = TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql100AndAbove = TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql110AndAbove = TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql120AndAbove = TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql130AndAbove = TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql140AndAbove = TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql150AndAbove = TSql150 | TSql160 | TSqlFabricDW | TSql170, - TSql160AndAbove = TSql160 | TSqlFabricDW | TSql170, - TSql170AndAbove = TSql170, - TSqlFabricDWAndAbove = TSql160 | TSqlFabricDW | TSql170, + TSqlAll = TSql80 | TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql90AndAbove = TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql100AndAbove = TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql110AndAbove = TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql120AndAbove = TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql130AndAbove = TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql140AndAbove = TSql140 | TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql150AndAbove = TSql150 | TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql160AndAbove = TSql160 | TSqlFabricDW | TSql170 | TSql180, + TSql170AndAbove = TSql170 | TSql180, + TSql180AndAbove = TSql180, + TSqlFabricDWAndAbove = TSql160 | TSqlFabricDW | TSql170 | TSql180, TSqlUnder110 = TSql80 | TSql90 | TSql100, TSqlUnder120 = TSql80 | TSql90 | TSql100 | TSql110, TSqlUnder130 = TSql80 | TSql90 | TSql100 | TSql110 | TSql120, @@ -44,5 +46,6 @@ internal enum SqlVersionFlags TSqlUnder150 = TSql80 | TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140, TSqlUnder160 = TSql80 | TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150, TSqlUnder170 = TSql80 | TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSqlFabricDW, + TSqlUnder180 = TSql80 | TSql90 | TSql100 | TSql110 | TSql120 | TSql130 | TSql140 | TSql150 | TSql160 | TSql170 | TSqlFabricDW, } } \ No newline at end of file diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g new file mode 100644 index 00000000..19e66add --- /dev/null +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -0,0 +1,35473 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +// sacaglar: Handling position information for ASTs +// The properties and AddX (X is the type of the parameter, e.g., AddStatement) +// update the position information of the AST. In the rare case when +// we are setting a bool, int, or string etc. we have to call UpdateTokenInfo +// with the token (because we are not passing the property a token, we are just +// passing a bool, int etc. +// Also for token that we don't track of like Comma, Semicolon etc. we have to +// call the same function. Alternatively the properties(StartOffset, FragmentLength) +// on Fragment.cs can be used for this purpose. + +options { + language = "CSharp"; + namespace = "Microsoft.SqlServer.TransactSql.ScriptDom"; +} + +{ + using System.Diagnostics; + using System.Globalization; + using System.Collections.Generic; +} + +class TSql180ParserInternal extends Parser("TSql180ParserBaseInternal"); +options { + k = 2; + defaultErrorHandler=false; + classHeaderPrefix = "internal partial"; + importVocab = TSql; +} + +{ + public TSql180ParserInternal(bool initialQuotedIdentifiersOn) + : base(initialQuotedIdentifiersOn) + { + initialize(); + } +} + +// Figure out a way to refactor exception handling +entryPointChildObjectName returns [ChildObjectName vResult = null] + : + vResult=childObjectNameWithThreePrefixes + EOF + ; + +entryPointSchemaObjectName returns [SchemaObjectName vResult = null] + : + vResult=schemaObjectFourPartName + EOF + ; + +entryPointScalarDataType returns [DataTypeReference vResult = null] + : + vResult = scalarDataType + EOF + ; + +entryPointExpression returns [ScalarExpression vResult = null] + : + vResult = expression + EOF + ; + +entryPointBooleanExpression returns [BooleanExpression vResult = null] + : + vResult = booleanExpression + EOF + ; + +entryPointStatementList returns [StatementList vResult = null] +{ + bool vParseErrorOccurred = false; +} + : + vResult = statementList[ref vParseErrorOccurred] + { + if (vParseErrorOccurred) + vResult = null; + } + EOF + ; + +entryPointSubqueryExpressionWithOptionalCTE returns [SelectStatement vResult = null] +{ + SelectFunctionReturnType vRetType; +} + : + vRetType = functionReturnClauseRelational + { + vResult = vRetType.SelectStatement; + } + EOF + ; + +entryPointIPv4Address returns [IPv4 vResult = null] + : + vResult = ipAddressV4 + EOF + ; + +entryPointConstantOrIdentifier returns [TSqlFragment vResult = null] + : + vResult = possibleNegativeConstantOrIdentifier + EOF + ; + +entryPointConstantOrIdentifierWithDefault returns [TSqlFragment vResult = null] + : + vResult = possibleNegativeConstantOrIdentifierWithDefault + EOF + ; + +script returns [TSqlScript vResult = this.FragmentFactory.CreateFragment()] +{ + TSqlBatch vCurrentBatch; + + // Script always includes all of the tokens... + if (vResult.ScriptTokenStream != null && vResult.ScriptTokenStream.Count > 0) + { + vResult.UpdateTokenInfo(0,vResult.ScriptTokenStream.Count-1); + } +} + : vCurrentBatch = batch + { + if (vCurrentBatch != null) + AddAndUpdateTokenInfo(vResult, vResult.Batches, vCurrentBatch); + } + ( + Go + { + ResetQuotedIdentifiersSettingToInitial(); + ThrowPartialAstIfPhaseOne(null); + } + vCurrentBatch = batch + { + if (vCurrentBatch != null) + AddAndUpdateTokenInfo(vResult, vResult.Batches, vCurrentBatch); + } + + )* + + tEof:EOF + { + UpdateTokenInfo(vResult,tEof); + } + ; + +// TODO, sacaglar: Tracking issue, bug# 584772 +batch returns [TSqlBatch vResult = null] +{ + TSqlStatement vStatement; +} + : (tSemi:Semicolon)* + ( + ( + Create (((Or Alter)? ( Proc | Procedure | Trigger | View | Function)) | ( Default | Rule | Schema | {NextTokenMatches(CodeGenerationSupporter.Federation)}? | {NextTokenMatches(CodeGenerationSupporter.Materialized)}? )) + | + Alter ( Proc | Procedure | Trigger | View | Function | {NextTokenMatches(CodeGenerationSupporter.Federation)}? | {NextTokenMatches(CodeGenerationSupporter.Materialized)}? ) + | + Use {NextTokenMatches(CodeGenerationSupporter.Federation) && LA(2) == Identifier}? + )=> + ( + vStatement=lastStatementOptSemi + { + if (vStatement != null) + { + if (vResult == null) + { + vResult = this.FragmentFactory.CreateFragment(); + } + AddAndUpdateTokenInfo(vResult, vResult.Statements, vStatement); + } + } + ) + | + (vStatement = optSimpleExecute + { + if (vStatement != null) // Can be empty + { + ThrowPartialAstIfPhaseOne(vStatement); + + if (vResult == null) + vResult = this.FragmentFactory.CreateFragment(); + + AddAndUpdateTokenInfo(vResult, vResult.Statements, vStatement); + } + } + (vStatement=statementOptSemi + { + if (vStatement != null) // statement can be null if there was a parse error. + { + if (vResult == null) + vResult = this.FragmentFactory.CreateFragment(); + + AddAndUpdateTokenInfo(vResult, vResult.Statements, vStatement); + } + } + )* + ) + ) + ; + exception + catch[TSqlParseErrorException exception] + { + if (!exception.DoNotLog) + { + AddParseError(exception.ParseError); + } + RecoverAtBatchLevel(); + } + catch[antlr.NoViableAltException exception] + { + ParseError error = GetFaultTolerantUnexpectedTokenError( + exception.token, exception, _tokenSource.LastToken.Offset); + AddParseError(error); + RecoverAtBatchLevel(); + } + catch[antlr.MismatchedTokenException exception] + { + ParseError error = GetFaultTolerantUnexpectedTokenError( + exception.token, exception, _tokenSource.LastToken.Offset); + AddParseError(error); + RecoverAtBatchLevel(); + } + catch[antlr.RecognitionException] + { + ParseError error = GetUnexpectedTokenError(); + AddParseError(error); + RecoverAtBatchLevel(); + } + catch[antlr.TokenStreamRecognitionException exception] + { + // This exception should be handled when we are creating TSqlTokenStream... + ParseError error = ProcessTokenStreamRecognitionException(exception, _tokenSource.LastToken.Offset); + AddParseError(error); + RecoverAtBatchLevel(); + } + catch[antlr.ANTLRException exception] + { + CreateInternalError("batch", exception); + } + +statementOptSemi returns [TSqlStatement vResult = null] + : vResult=statement optSemicolons[vResult] + ; + +lastStatementOptSemi returns [TSqlStatement vResult = null] + : vResult=lastStatement optSemicolons[vResult] + ; + +optSemicolons[TSqlStatement vParent] +{ + int nSemicolons = 0; +} + : ( + // Greedy behavior is good enough, we ignore the semicolons + options {greedy = true; } : + tSemi:Semicolon + { + ++nSemicolons; + if (vParent != null) // vResult can be null if there was a parse error. + UpdateTokenInfo(vParent,tSemi); + } + )* + ; + + +///////////////////////////////////////////////// +// Copy Command +///////////////////////////////////////////////// +copyStatement returns [CopyStatement vResult = FragmentFactory.CreateFragment()] +{ + SchemaObjectName vTo; + StringLiteral vFrom; +} + : + tCopy:Identifier + { + Match(tCopy, CodeGenerationSupporter.CopyCommand); + } + tInto: Into + vTo = schemaObjectThreePartName + { + UpdateTokenInfo(vResult,tCopy); + vResult.Into = vTo; + } + (copyColumnList[vResult])? + From vFrom = nonEmptyString /* No need to verify null as it's already nonempty */ + { + ExternalFileOption.CheckXMLValidity(vFrom, CodeGenerationSupporter.From); + AddAndUpdateTokenInfo(vResult, vResult.From, vFrom); + } + (Comma vFrom = nonEmptyString + { + ExternalFileOption.CheckXMLValidity(vFrom, CodeGenerationSupporter.From); + AddAndUpdateTokenInfo(vResult, vResult.From, vFrom); + } + )* + (copyWithClause[vResult])? + (optimizerHints[vResult, vResult.OptimizerHints])? +; + +copyColumnList [CopyStatement vParent] +{ + CopyOption copyOption = FragmentFactory.CreateFragment(); + ListTypeCopyOption vColumnOptions = FragmentFactory.CreateFragment();; + CopyColumnOption vColumnOption; + Int32 columnCount = 0; +} +: + tLParen: LeftParenthesis + { + copyOption.Kind = CopyOptionKind.ColumnOptions; + } + vColumnOption = copyColumnOption[ref columnCount, tLParen] + { + AddAndUpdateTokenInfo(vColumnOptions, vColumnOptions.Options, vColumnOption); + } + (Comma vColumnOption = copyColumnOption[ref columnCount, tLParen] + { + AddAndUpdateTokenInfo(vColumnOptions, vColumnOptions.Options, vColumnOption); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vParent,tRParen); + copyOption.Value = vColumnOptions; + AddAndUpdateTokenInfo(vParent, vParent.Options, copyOption); + } +; + +copyColumnOption [ref Int32 columnCount, IToken tToken] returns [CopyColumnOption vResult = FragmentFactory.CreateFragment()] +{ + Identifier vColumnName; + ScalarExpression vDefaultColumnValue = null; + bool vDefaultSpecified = false; + IntegerLiteral vFieldNumber = null; +} + : + vColumnName = identifier + { + CheckAndIncrementColumnCount(ref columnCount, tToken); + } + (tDefault:Default vDefaultColumnValue = defaultValueLiteral + { + vDefaultSpecified = true; + })? + (vFieldNumber = integer)? + { + CopyListOptionsHelper.Instance.AssignCopyColumnOptions(vResult, vColumnName, vDefaultColumnValue, vDefaultSpecified, vFieldNumber, columnCount); + } +; + +copyWithClause [CopyStatement vParent] +{ + CopyOption vOption; + Int32 encountered = 0; +} + : With LeftParenthesis vOption = copyOption[ref encountered] + { + AddAndUpdateTokenInfo(vParent, vParent.Options, vOption); + } + (Comma vOption = copyOption[ref encountered] + { + AddAndUpdateTokenInfo(vParent, vParent.Options, vOption); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vParent,tRParen); + } +; + +copyOption [ref Int32 encountered] returns [CopyOption vResult = FragmentFactory.CreateFragment()] +{ + CopyStatementOptionBase vValue = null; +} + : + ( + tOption:Identifier + { + vResult.Kind = CopyIdentifierOrValueOptionsHelper.Instance.ParseOption(tOption); + CheckCopyOptionDuplication(ref encountered, vResult.Kind, tOption); + } + | tIdentityInsert:IdentityInsert + { + vResult.Kind = CopyOptionKind.Identity_Insert; + CheckCopyOptionDuplication(ref encountered, vResult.Kind, tIdentityInsert); + } + | tCredential:Credential + { + vResult.Kind = CopyOptionKind.Credential; + CheckCopyOptionDuplication(ref encountered, vResult.Kind, tCredential); + } + ) + EqualsSign + ( + vValue = singleValueTypeCopyOption + { + CopyIdentifierOrValueOptionsHelper.Instance.AssignValueToCopyOption(vResult, (SingleValueTypeCopyOption) vValue); + } + | + vValue = copyCredentialOption + { + if ((vResult.Kind != CopyOptionKind.Credential || vResult.Kind != CopyOptionKind.ErrorFileCredential) && + CopyIdentifierOrValueOptionsHelper.Instance.ValidateCopyCredential((CopyCredentialOption)vValue)) + { + vResult.Value = (CopyCredentialOption) vValue; + } + else + { + ThrowIncorrectSyntaxErrorException(vValue); + } + } + ) +; + +singleValueTypeCopyOption returns [SingleValueTypeCopyOption vResult = FragmentFactory.CreateFragment()] +{ + Identifier vValue; + Literal vLiteral; +} + : + vValue=identifier + { + vResult.SingleValue = IdentifierOrValueExpression(vValue); + } + | vLiteral = integer + { + vResult.SingleValue = IdentifierOrValueExpression(vLiteral); + } + | vLiteral = stringLiteral + { + vResult.SingleValue = IdentifierOrValueExpression(vLiteral); + } +; + +copyCredentialOption returns [CopyCredentialOption vResult = FragmentFactory.CreateFragment()] +{ + StringLiteral vIdentityValue; + StringLiteral vSecretValue; +} + : + LeftParenthesis + Identity EqualsSign vIdentityValue = stringLiteral + { + vResult.Identity = vIdentityValue; + } + (Comma tSecret:Identifier EqualsSign vSecretValue = stringLiteral + { + Match(tSecret, CodeGenerationSupporter.Secret); + CopyIdentifierOrValueOptionsHelper.Instance.ValidateSecret(vSecretValue); + vResult.Secret = (StringLiteral) vSecretValue; + })? + RightParenthesis +; + + +///////////////////////////////////////////////// +// Rename table statement +///////////////////////////////////////////////// + +/* Syntax: +RENAME OBJECT [::] [Database].[Schema].OldTable TO NewTable +*/ + +renameEntityStatement returns [RenameEntityStatement vResult = this.FragmentFactory.CreateFragment()] +{ + SchemaObjectName vSchemaObjectName; + Identifier vRenamedEntityType; + Identifier vNewName; +} + :tRename:Identifier vRenamedEntityType = securityStatementPermission + { + Match(tRename, CodeGenerationSupporter.Rename); + vResult.RenameEntityType = ParseSecurityObjectKind(vRenamedEntityType); + if(!(vResult.RenameEntityType == SecurityObjectKind.Object)) + { + // RenameEntityStatement::Translate() throws an unexpected exception if the entity type is not + // "object". Since other object kinds are not supported in this statement, we throw + // a syntax error. + throw GetUnexpectedTokenErrorException(vRenamedEntityType); + } + } + + ( + DoubleColon + { + vResult.SeparatorType = SeparatorType.DoubleColon; + } + )? + + vSchemaObjectName = schemaObjectThreePartName + { + vResult.OldName = vSchemaObjectName; + } + To + ( + vNewName = identifier + { + vResult.NewName = vNewName; + } + ) + + { + UpdateTokenInfo(vResult, tRename); + } + ; + +///////////////////////////////////////////////// +// CREATE TABLE AS SELECT STATEMENT +///////////////////////////////////////////////// + +ctasCreateTableStatement [CreateTableStatement vParent] +{ + SelectStatement vSelectStatement; +} + : + (columnNameList[vParent, vParent.CtasColumns])? + ( + options {greedy = true; } : + withTableOptions[vParent] + ) + As + vSelectStatement = selectStatement[SubDmlFlags.None] + { + vParent.SelectStatement = vSelectStatement; + } + { + CheckCtasStatementHasDistributionOption(vParent); + } + ; + +///////////////////////////////////////////////// +// CREATE EXTERNAL TABLE AS SELECT STATEMENT +///////////////////////////////////////////////// +ctasCreateExternalTableStatement [CreateExternalTableStatement vParent] +{ + SelectStatement vSelectStatement; +} + : + ( + options { greedy = true; } : + withExternalTableOptions[vParent] + ) + As + vSelectStatement = selectStatement[SubDmlFlags.None] + { + vParent.SelectStatement = vSelectStatement; + } + { + CheckExternalTableCtasStatementHasNotRejectedRowLocationOption(vParent); + } + ; + +// This rule conflicts with identifierStatements (both can start with Identifier) +// We should update predicates here and in identifierStatements at the same time +optSimpleExecute returns [ExecuteStatement vResult = null] +{ + ExecutableProcedureReference vExecProc; + ExecuteSpecification vExecuteSpecification; +} + : {!NextTokenMatches(CodeGenerationSupporter.Disable) && !NextTokenMatches(CodeGenerationSupporter.Enable) && + !NextTokenMatches(CodeGenerationSupporter.Move) && !NextTokenMatches(CodeGenerationSupporter.Get) && + !NextTokenMatches(CodeGenerationSupporter.Receive) && !NextTokenMatches(CodeGenerationSupporter.Send) && + !NextTokenMatches(CodeGenerationSupporter.Throw) && !NextTokenMatches(CodeGenerationSupporter.Rename)}? + (vExecProc = execProc + { + vResult = FragmentFactory.CreateFragment(); + vExecuteSpecification = FragmentFactory.CreateFragment(); + vExecuteSpecification.ExecutableEntity = vExecProc; + vResult.ExecuteSpecification=vExecuteSpecification; + } + optSemicolons[vResult] + ) + | /* empty */ + ; + +statement returns [TSqlStatement vResult = null] +{ + // The next tokens offset is cached to help error + // recovery, so when error occurs if the next token is + // Create or Alter, and its offset is the same as + // vNextTokenOffset that means, this rule already + // tried to parsed and failed, so we should skip over. + // The case where it works is: + // select * from create table t1(c1 int) + int nextTokenLine = LT(1).getLine(); + int nextTokenColumn = LT(1).getColumn(); +} + : vResult=createTableStatement + | vResult=alterTableStatement + | vResult=createIndexStatement + | vResult=copyStatement + | vResult=declareStatements + | vResult=setStatements + | vResult=beginStatements + | vResult=breakStatement + | vResult=continueStatement + | vResult=ifStatement + | vResult=whileStatement + | vResult=labelStatement + | vResult=backupStatements + | vResult=restoreStatements + | vResult=gotoStatement + | vResult=saveTransactionStatement + | vResult=rollbackTransactionStatement + | vResult=commitTransactionStatement + | vResult=createStatisticsStatement + | vResult=updateStatisticsStatement + | vResult=alterDatabaseStatements + | vResult=executeStatement + | vResult=withCommonTableExpressionsAndXmlNamespacesStatements + | vResult=raiseErrorStatement + | vResult=alter2005Statements + | vResult=create2005Statements + | vResult=createDatabaseStatements + | vResult=addStatements + | vResult=identifierStatements + | vResult=printStatement + | vResult=waitForStatement + | vResult=readTextStatement + | vResult=updateTextStatement + | vResult=writeTextStatement + | vResult=lineNoStatement + | vResult=useStatement + | vResult=killStatements + | vResult=bulkInsertStatement + | vResult=insertBulkStatement + | vResult=checkpointStatement + | vResult=reconfigureStatement + | vResult=shutdownStatement + | vResult=setUserStatement + | vResult=truncateTableStatement + | vResult=grantStatement90 + | vResult=denyStatement90 + | vResult=revokeStatement90 + | vResult=returnStatement + | vResult=openStatements + | vResult=closeStatements + | vResult=deallocateCursorStatement + | vResult=fetchCursorStatement + | vResult=dropStatements + | vResult=dbccStatement + | vResult=revertStatement + | vResult=executeAsStatement + | vResult=endConversationStatement + ; + exception + catch[TSqlParseErrorException exception] + { + if (!exception.DoNotLog) + { + AddParseError(exception.ParseError); + } + RecoverAtStatementLevel(nextTokenLine, nextTokenColumn); + } + catch[antlr.NoViableAltException exception] + { + ParseError error = GetFaultTolerantUnexpectedTokenError( + exception.token, exception, _tokenSource.LastToken.Offset); + AddParseError(error); + RecoverAtStatementLevel(nextTokenLine, nextTokenColumn); + } + catch[antlr.MismatchedTokenException exception] + { + ParseError error = GetFaultTolerantUnexpectedTokenError( + exception.token, exception, _tokenSource.LastToken.Offset); + AddParseError(error); + RecoverAtStatementLevel(nextTokenLine, nextTokenColumn); + } + catch[antlr.RecognitionException] + { + ParseError error = GetUnexpectedTokenError(); + AddParseError(error); + RecoverAtStatementLevel(nextTokenLine, nextTokenColumn); + } + catch[antlr.TokenStreamRecognitionException exception] + { + // This exception should be handled when we are creating TSqlTokenStream... + ParseError error = ProcessTokenStreamRecognitionException(exception, _tokenSource.LastToken.Offset); + AddParseError(error); + RecoverAtStatementLevel(nextTokenLine, nextTokenColumn); + } + catch[antlr.ANTLRException exception] + { + CreateInternalError("statement", exception); + } + +withCommonTableExpressionsAndXmlNamespacesStatements returns [StatementWithCtesAndXmlNamespaces vResult = null] +{ + WithCtesAndXmlNamespaces vWithCommonTableExpressionsAndXmlNamespaces = null; +} + : + ( + vWithCommonTableExpressionsAndXmlNamespaces=withCommonTableExpressionsAndXmlNamespaces + )? + ( + vResult=select[SubDmlFlags.SelectNotForInsert] + { + // check for invalid combination of CHANGE_TRACKING_CONTEXT and Select statement + if ((vWithCommonTableExpressionsAndXmlNamespaces != null) && (vWithCommonTableExpressionsAndXmlNamespaces.ChangeTrackingContext != null)) + ThrowParseErrorException("SQL46072", vWithCommonTableExpressionsAndXmlNamespaces.ChangeTrackingContext, TSqlParserResource.SQL46072Message); + } + | + vResult=deleteStatement[SubDmlFlags.None] + | + vResult=insertStatement[SubDmlFlags.None] + | + vResult=updateStatement[SubDmlFlags.None] + | + vResult=mergeStatement[SubDmlFlags.None] + ) + { + vResult.WithCtesAndXmlNamespaces = vWithCommonTableExpressionsAndXmlNamespaces; + } + ; + +lastStatement returns [TSqlStatement vResult = null] + : vResult=createProcedureStatement + | vResult=alterProcedureStatement + | vResult=createTriggerStatement + | vResult=alterTriggerStatement + | vResult=createDefaultStatement + | vResult=createRuleStatement + | vResult=createViewStatement + | vResult=alterViewStatement + | vResult=createFunctionStatement + | vResult=alterFunctionStatement + | vResult=createSchemaStatement + | vResult=createIdentifierStatement + | vResult=alterIdentifierStatement + | vResult=useFederationStatement + | vResult=createOrAlterStatements + ; + +createIdentifierStatement returns [TSqlStatement vResult] + : tCreate:Create + ( + {NextTokenMatches(CodeGenerationSupporter.Materialized)}? + vResult=createMaterializedViewStatement + | + {NextTokenMatches(CodeGenerationSupporter.Federation)}? + vResult=createFederationStatement + ) + { + UpdateTokenInfo(vResult,tCreate); + } + ; + +alterIdentifierStatement returns [TSqlStatement vResult] + : tAlter:Alter + ( + {NextTokenMatches(CodeGenerationSupporter.Materialized)}? + vResult=alterMaterializedViewStatement + | + {NextTokenMatches(CodeGenerationSupporter.Federation)}? + vResult=alterFederationStatement + ) + { + UpdateTokenInfo(vResult,tAlter); + } + ; + +createOrAlterStatements returns [TSqlStatement vResult] + : tCreate:Create Or Alter + ( + vResult = createOrAlterFunctionStatement + | vResult = createOrAlterProcedureStatement + | vResult = createOrAlterTriggerStatement + | vResult = createOrAlterViewStatement + ) + { + UpdateTokenInfo(vResult,tCreate); + } + ; + +// This rule conflicts with optSimpleExecute (both can start with Identifier) +// We should update predicates here and in optSimpleExecute at the same time +identifierStatements returns [TSqlStatement vResult] + : {NextTokenMatches(CodeGenerationSupporter.Disable)}? + vResult=disableTriggerStatement + | {NextTokenMatches(CodeGenerationSupporter.Enable)}? + vResult=enableTriggerStatement + | {NextTokenMatches(CodeGenerationSupporter.Move)}? + vResult = moveConversationStatement + | {NextTokenMatches(CodeGenerationSupporter.Get)}? + vResult = getConversationGroupStatement + | {NextTokenMatches(CodeGenerationSupporter.Receive)}? + vResult = receiveStatement + | {NextTokenMatches(CodeGenerationSupporter.Send)}? + vResult = sendStatement + | {NextTokenMatches(CodeGenerationSupporter.Throw)}? + vResult = throwStatement + | {NextTokenMatches(CodeGenerationSupporter.Rename)}? + vResult = renameEntityStatement + ; + + +disableTriggerStatement returns [EnableDisableTriggerStatement vResult = this.FragmentFactory.CreateFragment()] + : + tDisable:Identifier + { + Match(tDisable, CodeGenerationSupporter.Disable); + UpdateTokenInfo(vResult,tDisable); + vResult.TriggerEnforcement = TriggerEnforcement.Disable; + } + enableDisableTriggerBody[vResult] + ; + +enableTriggerStatement returns [EnableDisableTriggerStatement vResult = this.FragmentFactory.CreateFragment()] + : + tEnable:Identifier + { + Match(tEnable, CodeGenerationSupporter.Enable); + UpdateTokenInfo(vResult,tEnable); + vResult.TriggerEnforcement = TriggerEnforcement.Enable; + } + enableDisableTriggerBody[vResult] + ; + +enableDisableTriggerBody[EnableDisableTriggerStatement vParent] +{ + SchemaObjectName vSchemaObjectName; + TriggerObject vTriggerObject; +} + : + Trigger + ( + vSchemaObjectName=schemaObjectThreePartName + { + AddAndUpdateTokenInfo(vParent, vParent.TriggerNames,vSchemaObjectName); + } + ( + Comma vSchemaObjectName=schemaObjectThreePartName + { + AddAndUpdateTokenInfo(vParent, vParent.TriggerNames,vSchemaObjectName); + } + )* + | + All + { + vParent.All = true; + } + ) + On vTriggerObject=triggerObject + { + vParent.TriggerObject = vTriggerObject; + } + ; + +create2005Statements returns [TSqlStatement vResult = null] + : tCreate:Create + ( + {NextTokenMatches(CodeGenerationSupporter.Aggregate)}? + vResult=createAggregateStatement + | + {NextTokenMatches(CodeGenerationSupporter.Application)}? + vResult=createApplicationRoleStatement + | + {NextTokenMatches(CodeGenerationSupporter.Assembly)}? + vResult=createAssemblyStatement + | + {NextTokenMatches(CodeGenerationSupporter.Asymmetric)}? + vResult=createAsymmetricKeyStatement + | + {NextTokenMatches(CodeGenerationSupporter.Availability)}? + vResult=createAvailabilityGroupStatement + | + {NextTokenMatches(CodeGenerationSupporter.Broker)}? + vResult=createBrokerPriorityStatement + | + {NextTokenMatches(CodeGenerationSupporter.Certificate)}? + vResult=createCertificateStatement + | + {NextTokenMatches(CodeGenerationSupporter.Column)}? + vResult=createColumnStatements + | + {NextTokenMatches(CodeGenerationSupporter.ColumnStore)}? + vResult=createColumnStoreIndexStatement[null, null] + | + {NextTokenMatches(CodeGenerationSupporter.Json)}? + vResult=createJsonIndexStatement[null, null] + | + {NextTokenMatches(CodeGenerationSupporter.Vector)}? + vResult=createVectorIndexStatement[null, null] + | + {NextTokenMatches(CodeGenerationSupporter.Contract)}? + vResult=createContractStatement + | + {NextTokenMatches(CodeGenerationSupporter.Credential)}? + vResult=createCredentialStatement + | + {NextTokenMatches(CodeGenerationSupporter.Cryptographic)}? + vResult=createCryptographicProviderStatement + | + {NextTokenMatches(CodeGenerationSupporter.Endpoint)}? + vResult=createEndpointStatement + | + {NextTokenMatches(CodeGenerationSupporter.Event)}? + vResult=createEventStatement // NOTIFICATION or SESSION + | + {NextTokenMatches(CodeGenerationSupporter.External)}? + vResult=createExternalStatements // EXTERNAL DATA SOURCE, FILE FORMAT, STREAM, TABLE, RESOURCE POOL, LIBRARY, LANGUAGE, MODEL + | + {NextTokenMatches(CodeGenerationSupporter.Fulltext)}? + vResult=createFulltextStatement // Index or CATALOG + | + vResult=createPrimaryXmlIndexStatement + | + {NextTokenMatches(CodeGenerationSupporter.Selective)}? + vResult=createSelectiveXmlIndexStatement + | + {NextTokenMatches(CodeGenerationSupporter.Xml)}? + vResult=createXmlStatements // Index or Schema + | + {NextTokenMatches(CodeGenerationSupporter.Login)}? + vResult=createLoginStatement + | + {NextTokenMatches(CodeGenerationSupporter.Message)}? + vResult=createMessageTypeStatement + | + {NextTokenMatches(CodeGenerationSupporter.Master)}? + vResult=createMasterKeyStatement + | + {NextTokenMatches(CodeGenerationSupporter.Partition)}? + vResult=createPartitionStatement // SCHEME or Function + | + {NextTokenMatches(CodeGenerationSupporter.Queue)}? + vResult=createQueueStatement + | + {NextTokenMatches(CodeGenerationSupporter.Remote)}? + vResult=createRemoteServiceBindingStatement + | + {NextTokenMatches(CodeGenerationSupporter.Resource)}? + vResult=createResourcePoolStatement + | + {NextTokenMatches(CodeGenerationSupporter.Role)}? + vResult=createRoleStatement + | + {NextTokenMatches(CodeGenerationSupporter.Route)}? + vResult=createRouteStatement + | + {NextTokenMatches(CodeGenerationSupporter.Search)}? + vResult=createSearchPropertyListStatement + | + {NextTokenMatches(CodeGenerationSupporter.Service)}? + vResult=createServiceStatement + | + {NextTokenMatches(CodeGenerationSupporter.Spatial)}? + vResult=createSpatialIndexStatement + | + {NextTokenMatches(CodeGenerationSupporter.Symmetric)}? + vResult=createSymmetricKeyStatement + | + {NextTokenMatches(CodeGenerationSupporter.Synonym)}? + vResult=createSynonymStatement + | + {NextTokenMatches(CodeGenerationSupporter.Type)}? + vResult=createTypeStatement + | + {NextTokenMatches(CodeGenerationSupporter.Server)}? + vResult=createServerStatements //AUDIT or ROLE + | + {NextTokenMatches(CodeGenerationSupporter.Workload)}? + vResult=createWorkloadStatements + | + {NextTokenMatches(CodeGenerationSupporter.Sequence)}? + vResult=createSequenceStatement + | + {NextTokenMatches(CodeGenerationSupporter.Security)}? + vResult=createSecurityPolicyStatement + | + vResult=createUserStatement + ) + { + UpdateTokenInfo(vResult,tCreate); + ThrowPartialAstIfPhaseOne(vResult); + } + ; + exception + catch[PhaseOnePartialAstException exception] + { + UpdateTokenInfo(exception.Statement, tCreate); + throw; + } + +createAggregateStatement returns [CreateAggregateStatement vResult = FragmentFactory.CreateFragment()] +{ + SchemaObjectName vSchemaObjectName; + ProcedureParameter vParameter; + AssemblyName vAssemblyName; + DataTypeReference vDataType; +} + : tAggregate:Identifier vSchemaObjectName=schemaObjectThreePartName + { + Match(tAggregate, CodeGenerationSupporter.Aggregate); + CheckTwoPartNameForSchemaObjectName(vSchemaObjectName, CodeGenerationSupporter.Aggregate); + vResult.Name = vSchemaObjectName; + ThrowPartialAstIfPhaseOne(vResult); + } + LeftParenthesis vParameter = aggregateParameter + { + AddAndUpdateTokenInfo(vResult, vResult.Parameters, vParameter); + } + (Comma vParameter = aggregateParameter + { + AddAndUpdateTokenInfo(vResult, vResult.Parameters, vParameter); + } + )* + RightParenthesis + tReturns:Identifier vDataType = scalarDataType + { + Match(tReturns,CodeGenerationSupporter.Returns); + vResult.ReturnType = vDataType; + } + External vAssemblyName = assemblyName + { + vResult.AssemblyName = vAssemblyName; + } + ; + +aggregateParameter returns [ProcedureParameter vResult = FragmentFactory.CreateFragment()] +{ + Identifier vParamName; + DataTypeReference vDataType; + NullableConstraintDefinition vNullableConstraintDefinition; +} + : vParamName = identifierVariable (As)? vDataType = scalarDataType + { + vResult.VariableName = vParamName; + vResult.DataType = vDataType; + } + ( + vNullableConstraintDefinition = nullableConstraint + { + vResult.Nullable=vNullableConstraintDefinition; + } + )? + ; + +createApplicationRoleStatement returns [CreateApplicationRoleStatement vResult = this.FragmentFactory.CreateFragment()] + : + applicationRoleStatement[vResult, true] + ; + +createAssemblyStatement returns [CreateAssemblyStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + AssemblyOption vOption; +} + : tAssembly:Identifier vIdentifier=identifier + { + Match(tAssembly, CodeGenerationSupporter.Assembly); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + From expressionList[vResult, vResult.Parameters] + ( + // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + With tPermissionSet:Identifier EqualsSign + vOption=assemblyPermissionSetOption[tPermissionSet] + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + )? + ; + +createExternalLibraryStatement returns [CreateExternalLibraryStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + ExternalLibraryFileOption vFileOption; + StringLiteral vLanguage; +} + : tLibrary:Identifier vIdentifier=identifier + { + Match(tLibrary, CodeGenerationSupporter.Library); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + From vFileOption=createExternalLibraryFileOption + { + vResult.ExternalLibraryFiles.Add(vFileOption); + } + (Comma vFileOption = createExternalLibraryFileOption + { + vResult.ExternalLibraryFiles.Add(vFileOption); + } + )* + With LeftParenthesis tLanguage:Identifier EqualsSign vLanguage=nonEmptyString + { + Match(tLanguage, CodeGenerationSupporter.Language); + vResult.Language = vLanguage; + } + RightParenthesis + ; + +alterExternalLibraryStatement returns [AlterExternalLibraryStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + ExternalLibraryFileOption vFileOption; + StringLiteral vLanguage; +} + : tLibrary:Identifier vIdentifier=identifier + { + Match(tLibrary, CodeGenerationSupporter.Library); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + Set vFileOption=alterExternalLibraryFileOption + { + vResult.ExternalLibraryFiles.Add(vFileOption); + } + With LeftParenthesis tLanguage:Identifier EqualsSign vLanguage=nonEmptyString + { + Match(tLanguage, CodeGenerationSupporter.Language); + vResult.Language = vLanguage; + } + RightParenthesis + ; + +dropExternalLibraryStatement returns [DropExternalLibraryStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : tLibrary:Identifier vIdentifier=identifier + { + Match(tLibrary, CodeGenerationSupporter.Library); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + ; + +binaryOrString returns [ValueExpression vResult] + : + vResult=binary + | + vResult=stringLiteral + ; + +createExternalLibraryFileOption returns [ExternalLibraryFileOption vResult = FragmentFactory.CreateFragment()] +{ + ScalarExpression vContent; + Identifier vPlatform; +} + : LeftParenthesis tContent:Identifier EqualsSign vContent=binaryOrString + { + Match(tContent, CodeGenerationSupporter.Content); + vResult.Content = vContent; + } + (Comma tPlatform:Identifier EqualsSign vPlatform=identifier + { + Match(tPlatform, CodeGenerationSupporter.Platform); + vResult.Platform = vPlatform; + } + )* + RightParenthesis + ; + +alterExternalLibraryFileOption returns [ExternalLibraryFileOption vResult = FragmentFactory.CreateFragment()] +{ + ScalarExpression vContent; + Identifier vPlatform; +} + : LeftParenthesis tContent:Identifier EqualsSign vContent=binaryOrString + { + Match(tContent, CodeGenerationSupporter.Content); + vResult.Content = vContent; + } + (Comma tPlatform:Identifier EqualsSign vPlatform=identifier + { + Match(tPlatform, CodeGenerationSupporter.Platform); + vResult.Platform = vPlatform; + } + )* + RightParenthesis + ; + +createExternalLanguageStatement returns [CreateExternalLanguageStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + ExternalLanguageFileOption vFileOption; +} + : tLanguage:Identifier vIdentifier=identifier + { + Match(tLanguage, CodeGenerationSupporter.Language); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + From vFileOption=externalLanguageFileOption + { + vResult.ExternalLanguageFiles.Add(vFileOption); + } + (Comma vFileOption = externalLanguageFileOption + { + vResult.ExternalLanguageFiles.Add(vFileOption); + } + )* + ; + +externalLanguageFileOption returns [ExternalLanguageFileOption vResult = FragmentFactory.CreateFragment()] +{ + ScalarExpression vContent; + StringLiteral vFileName; + Identifier vPlatform; + StringLiteral vParameters; + StringLiteral vEnvironmentVariables; +} + : LeftParenthesis tContent:Identifier EqualsSign vContent=binaryOrString + { + Match(tContent, CodeGenerationSupporter.Content); + vResult.Content = vContent; + } + Comma tFileName:Identifier EqualsSign vFileName=nonEmptyString + { + Match(tFileName, CodeGenerationSupporter.File_Name); + vResult.FileName = vFileName; + } + ( + tComma:Comma + ( + {NextTokenMatches(CodeGenerationSupporter.Platform)}? + ( + tPlatform:Identifier EqualsSign vPlatform=identifier + { + Match(tPlatform, CodeGenerationSupporter.Platform); + vResult.Platform = vPlatform; + } + ) + | + {NextTokenMatches(CodeGenerationSupporter.Parameters)}? + ( + tParameters:Identifier EqualsSign vParameters=nonEmptyString + { + Match(tParameters, CodeGenerationSupporter.Parameters); + vResult.Parameters = vParameters; + } + ) + | + {NextTokenMatches(CodeGenerationSupporter.EnvironmentVariables)}? + ( + tEnvironmentVariables:Identifier EqualsSign vEnvironmentVariables=nonEmptyString + { + Match(tEnvironmentVariables, CodeGenerationSupporter.EnvironmentVariables); + vResult.EnvironmentVariables = vEnvironmentVariables; + } + ) + ) + )* + + RightParenthesis + ; + +alterExternalLanguageStatement returns [AlterExternalLanguageStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + ExternalLanguageFileOption vFileOption; + Identifier vPlatform; +} + : tLanguage:Identifier vIdentifier=identifier + { + Match(tLanguage, CodeGenerationSupporter.Language); + vResult.Name = vIdentifier; + vResult.Operation=new Identifier(); + ThrowPartialAstIfPhaseOne(vResult); + } + ( + authorizationOpt[vResult] + ( + {NextTokenMatches(CodeGenerationSupporter.Set)}? + ( + Set vFileOption=externalLanguageFileOption + { + vResult.ExternalLanguageFiles.Add(vFileOption); + vResult.Operation.Value = CodeGenerationSupporter.Set; + } + ) + | + {NextTokenMatches(CodeGenerationSupporter.Add)}? + ( + Add vFileOption=externalLanguageFileOption + { + vResult.ExternalLanguageFiles.Add(vFileOption); + vResult.Operation.Value = CodeGenerationSupporter.Add; + } + ) + | + {NextTokenMatches(CodeGenerationSupporter.Remove)}? + ( + tRemove:Identifier tPlatform:Identifier vPlatform=identifier + { + Match(tRemove, CodeGenerationSupporter.Remove); + vResult.Platform = vPlatform; + vResult.Operation.Value = CodeGenerationSupporter.Remove; + } + ) + ) + ) + + ; + +dropExternalLanguageStatement returns [DropExternalLanguageStatement vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : tLanguage:Identifier vIdentifier=identifier + { + Match(tLanguage, CodeGenerationSupporter.Language); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + ; + +createAsymmetricKeyStatement returns [CreateAsymmetricKeyStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + Literal vPassword; +} + : tAsymmetric:Identifier Key vIdentifier=identifier + { + Match(tAsymmetric, CodeGenerationSupporter.Asymmetric); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + createAsymmetricKeyParams[vResult] + ( + // Greedy due to linear approximation introduced after the rule securityStatementPermission + options {greedy = true; } : + vPassword = encryptClause + { + vResult.Password = vPassword; + } + )? + ; + +createAsymmetricKeyParams[CreateAsymmetricKeyStatement vParent] +{ + EncryptionSource vSource; +} + : From vSource = asymKeySource + { + vParent.KeySource=vSource; + } + | With asymKeySpec[vParent] + ; + +asymKeySource returns [EncryptionSource vResult] + : + vResult = fileEncryptionSource + | {NextTokenMatches(CodeGenerationSupporter.Assembly)}? + vResult = assemblyEncryptionSource + | vResult = providerEncryptionSource + ; + +assemblyEncryptionSource returns [AssemblyEncryptionSource vResult=FragmentFactory.CreateFragment()] +{ + Identifier vAssembly; +} + : tAssembly:Identifier vAssembly = identifier + { + Match(tAssembly, CodeGenerationSupporter.Assembly); + vResult.Assembly = vAssembly; + } + ; + +providerEncryptionSource returns [ProviderEncryptionSource vResult = FragmentFactory.CreateFragment()] +{ + Identifier vProviderName; +} + : tProvider:Identifier vProviderName = identifier + { + Match(tProvider, CodeGenerationSupporter.Provider); + vResult.Name = vProviderName; + } + providerKeySourceOptions[vResult.KeyOptions, vResult] + ; + +fileEncryptionSource returns [FileEncryptionSource vResult = FragmentFactory.CreateFragment()] +{ + Literal vFile; +} + : (tExecutable:Identifier + { + Match(tExecutable, CodeGenerationSupporter.Executable); + vResult.IsExecutable = true; + } + )? + File EqualsSign vFile = stringLiteral + { + vResult.File = vFile; + } + ; + +asymKeySpec [CreateAsymmetricKeyStatement vParent] + : tAlgorithm:Identifier EqualsSign tRealAlg:Identifier + { + Match(tAlgorithm,CodeGenerationSupporter.Algorithm); + vParent.EncryptionAlgorithm = EncryptionAlgorithmsHelper.Instance.ParseOption(tRealAlg); + UpdateTokenInfo(vParent,tRealAlg); + } + ; + +createCertificateStatement returns [CreateCertificateStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : tCertificate:Identifier vIdentifier=identifier + { + Match(tCertificate, CodeGenerationSupporter.Certificate); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + createCertificateParams[vResult] + ( + // Greedy due to linear approximation introduced after the rule securityStatementPermission + options {greedy = true; } : + createCertificateActivityFlag[vResult] + )? + ; + +createCertificateParams [CreateCertificateStatement vParent] +{ + Literal vPassword; + CertificateOption vOption; + CertificateOptionKinds encounteredOptions = CertificateOptionKinds.None; +} + : From certificateSource[vParent] + | ( + (vPassword = encryptClause + { + vParent.EncryptionPassword = vPassword; + } + )? + With vOption = certificateOption[encounteredOptions] + { + encounteredOptions = encounteredOptions | vOption.Kind; + AddAndUpdateTokenInfo(vParent, vParent.CertificateOptions,vOption); + } + (Comma vOption = certificateOption[encounteredOptions] + { + encounteredOptions = encounteredOptions | vOption.Kind; + AddAndUpdateTokenInfo(vParent, vParent.CertificateOptions,vOption); + } + )* + ) + ; + +createCertificateActivityFlag [CertificateStatementBase vParent] +{ + OptionState vOptionState; +} + : tActive:Identifier For tBeginDialog:Identifier EqualsSign vOptionState = optionOnOff[vParent] + { + Match(tActive,CodeGenerationSupporter.Active); + Match(tBeginDialog,CodeGenerationSupporter.BeginDialog); + vParent.ActiveForBeginDialog = vOptionState; + } + ; + +certificateOption [CertificateOptionKinds encountered]returns [CertificateOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tOption:Identifier EqualsSign vValue = stringLiteral + { + vResult.Kind = CertificateOptionKindsHelper.Instance.ParseOption(tOption); + vResult.Value = vValue; + CheckCertificateOptionDupication(encountered,vResult.Kind,tOption); + } + ; + +certificateSource [CreateCertificateStatement vParent] +{ + EncryptionSource vCertificateSource; +} + : + ( + vCertificateSource=fileEncryptionSource + ( + // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + With privateKeySpec[vParent] + )? + | + vCertificateSource = assemblyEncryptionSource + ) + { + vParent.CertificateSource = vCertificateSource; + } + ; + +encryptClause returns [Literal vResult] + : tEncryption:Identifier By tPassword:Identifier EqualsSign vResult = stringLiteral + { + Match(tEncryption,CodeGenerationSupporter.Encryption); + Match(tPassword,CodeGenerationSupporter.Password); + } + ; + +privateKeySpec [CertificateStatementBase vParent] + : tPrivate:Identifier Key LeftParenthesis certificatePrivateKeySpec[vParent] (Comma certificatePrivateKeySpec[vParent])* tRParen:RightParenthesis + { + Match(tPrivate,CodeGenerationSupporter.Private); + UpdateTokenInfo(vParent,tRParen); + } + ; + +certificatePrivateKeySpec [CertificateStatementBase vParent] +{ + Literal vFilePath; +} + : passwordChangeOption[vParent] + | tFile:File EqualsSign vFilePath = stringLiteral + { + if (vParent.PrivateKeyPath != null) + throw GetUnexpectedTokenErrorException(tFile); + else + vParent.PrivateKeyPath = vFilePath; + } + ; + +passwordChangeOption [IPasswordChangeOption vParent] +{ + Literal vPassword; +} + : tEncryptionDecryption:Identifier By tPassword:Identifier EqualsSign vPassword = stringLiteral + { + if (TryMatch(tEncryptionDecryption,CodeGenerationSupporter.Encryption)) + { + if (vParent.EncryptionPassword != null) + throw GetUnexpectedTokenErrorException(tEncryptionDecryption); + else + vParent.EncryptionPassword = vPassword; + } + else + { + Match(tEncryptionDecryption,CodeGenerationSupporter.Decryption); + if (vParent.DecryptionPassword != null) + throw GetUnexpectedTokenErrorException(tEncryptionDecryption); + else + vParent.DecryptionPassword = vPassword; + } + } + ; + + +createContractStatement returns [CreateContractStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + ContractMessage vMessage; +} + : tContract:Identifier vIdentifier=identifier + { + Match(tContract, CodeGenerationSupporter.Contract); + vResult.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vResult); + } + authorizationOpt[vResult] + LeftParenthesis vMessage = contractMessage + { + AddAndUpdateTokenInfo(vResult, vResult.Messages,vMessage); + } + (Comma vMessage = contractMessage + { + AddAndUpdateTokenInfo(vResult, vResult.Messages,vMessage); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult,tRParen); + } + ; + +contractMessage returns [ContractMessage vResult = FragmentFactory.CreateFragment()] +{ + Identifier vMessageName; +} + : vMessageName = identifier tSent:Identifier By + { + Match(tSent,CodeGenerationSupporter.Sent); + vResult.Name = vMessageName; + } + ( tAny:Any + { + vResult.SentBy = MessageSender.Any; + UpdateTokenInfo(vResult,tAny); + } + | tInitiatorTarget:Identifier + { + if (TryMatch(tInitiatorTarget,CodeGenerationSupporter.Initiator)) + vResult.SentBy = MessageSender.Initiator; + else + { + Match(tInitiatorTarget,CodeGenerationSupporter.Target); + vResult.SentBy = MessageSender.Target; + } + UpdateTokenInfo(vResult,tInitiatorTarget); + } + ) + ; + +createDatabaseScopedCredentialStatement returns [CreateCredentialStatement vResult = FragmentFactory.CreateFragment()] + : tScoped:Identifier + { + Match(tScoped, CodeGenerationSupporter.Scoped); + vResult.IsDatabaseScoped = true; + } + + credentialStatementBody[vResult] + + ; + +createCredentialStatement returns [CreateCredentialStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vCryptographicProviderName; + vResult.IsDatabaseScoped = false; +} + : credentialStatementBody[vResult] + ( + For tCryptographic:Identifier tProvider:Identifier vCryptographicProviderName=identifier + { + Match(tCryptographic, CodeGenerationSupporter.Cryptographic); + Match(tProvider, CodeGenerationSupporter.Provider); + vResult.CryptographicProviderName = vCryptographicProviderName; + } + )? + ; + +credentialStatementBody [CredentialStatement vParent] +{ + Identifier vIdentifier; + Literal vLiteral; +} + : tCredential:Identifier vIdentifier=identifier + { + Match(tCredential, CodeGenerationSupporter.Credential); + vParent.Name = vIdentifier; + ThrowPartialAstIfPhaseOne(vParent); + } + With Identity EqualsSign vLiteral = stringLiteral + { + vParent.Identity = vLiteral; + } + (Comma tSecret:Identifier EqualsSign vLiteral = stringLiteral + { + Match(tSecret,CodeGenerationSupporter.Secret); + vParent.Secret = vLiteral; + } + )? + ; + +createServerStatements returns [TSqlStatement vResult] + : tServer:Identifier + { + Match(tServer, CodeGenerationSupporter.Server); + } + ( + {NextTokenMatches(CodeGenerationSupporter.Audit)}? + vResult=createServerAuditStatements + | + {NextTokenMatches(CodeGenerationSupporter.Role)}? + vResult=createServerRoleStatement + ) + ; + +createServerAuditStatements returns [TSqlStatement vResult] + : tAudit:Identifier + { + Match(tAudit, CodeGenerationSupporter.Audit); + } + ( + vResult = createServerAuditSpecificationStatement + | + vResult = createServerAuditStatement + ) + ; + +createServerAuditStatement returns [CreateServerAuditStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vAuditName; + AuditTarget vTarget; + BooleanExpression vFilterPredicate; +} + : vAuditName = identifier + { + vResult.AuditName = vAuditName; + ThrowPartialAstIfPhaseOne(vResult); + } + vTarget = auditTargetClause[true] + { + vResult.AuditTarget = vTarget; + } + ( // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + auditCreateWithClause[vResult] + )? + ( + Where vFilterPredicate=eventBooleanExpression + { + vResult.PredicateExpression = vFilterPredicate; + } + )? + ; + +auditTargetClause [bool pathRequired] returns [AuditTarget vResult = FragmentFactory.CreateFragment()] +{ + AuditTargetOption vOption; + bool pathOptionEncountered = false; +} + : tTo:To + { + UpdateTokenInfo(vResult,tTo); + } + ( + ( + tFile:File LeftParenthesis vOption = auditFileOption + { + vResult.TargetKind = AuditTargetKind.File; + AddAndUpdateTokenInfo(vResult, vResult.TargetOptions, vOption); + + pathOptionEncountered |= (vOption.OptionKind==AuditTargetOptionKind.FilePath); + } + ( + Comma vOption = auditFileOption + { + AddAndUpdateTokenInfo(vResult, vResult.TargetOptions, vOption); + + pathOptionEncountered |= vOption.OptionKind==AuditTargetOptionKind.FilePath; + } + )* + | + tUrl:Identifier LeftParenthesis vOption = auditUrlOption + { + Match(tUrl, CodeGenerationSupporter.Url); + vResult.TargetKind = AuditTargetKind.Url; + AddAndUpdateTokenInfo(vResult, vResult.TargetOptions, vOption); + + pathOptionEncountered |= (vOption.OptionKind==AuditTargetOptionKind.Path); + } + ( + Comma vOption = auditUrlOption + { + AddAndUpdateTokenInfo(vResult, vResult.TargetOptions, vOption); + + pathOptionEncountered |= vOption.OptionKind==AuditTargetOptionKind.Path; + } + )? + ) + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult,tRParen); + if (pathRequired && !pathOptionEncountered) + { + if(tFile != null) + { + ThrowParseErrorException("SQL46056", tFile, TSqlParserResource.SQL46056Message); + } + else + { + ThrowParseErrorException("SQL46126", tUrl, TSqlParserResource.SQL46126Message); + } + } + } + | + tApplicationLogSecurityLogExternalMonitor:Identifier + { + if (TryMatch(tApplicationLogSecurityLogExternalMonitor, CodeGenerationSupporter.ApplicationLog)) + { + vResult.TargetKind = AuditTargetKind.ApplicationLog; + } + else if (TryMatch(tApplicationLogSecurityLogExternalMonitor, CodeGenerationSupporter.SecurityLog)) + { + vResult.TargetKind = AuditTargetKind.SecurityLog; + } + else + { + Match(tApplicationLogSecurityLogExternalMonitor, CodeGenerationSupporter.ExternalMonitor); + vResult.TargetKind = AuditTargetKind.ExternalMonitor; + } + UpdateTokenInfo(vResult,tApplicationLogSecurityLogExternalMonitor); + } + ) + ; + +// Corresponds to audit_file_option_element in SQL yacc grammar +auditFileOption returns [AuditTargetOption vResult = null] + : + {NextTokenMatches(CodeGenerationSupporter.MaxSize)}? + vResult = maxSizeAuditFileOption + | + {NextTokenMatches(CodeGenerationSupporter.MaxRolloverFiles)}? + vResult = maxRolloverFilesAuditFileOption + | + {NextTokenMatches(CodeGenerationSupporter.ReserveDiskSpace)}? + vResult = reserveDiskSpaceAuditFileOption + | + {NextTokenMatches(CodeGenerationSupporter.MaxFiles)}? + vResult = maxFilesAuditFileOption + | + vResult = pathAuditFileOption + ; + +auditUrlOption returns [AuditTargetOption vResult = null] + : + {NextTokenMatches(CodeGenerationSupporter.RetentionDays)}? + vResult = retentionDaysAuditUrlOption + | + vResult = pathAuditFileOption + ; + +maxSizeAuditFileOption returns [MaxSizeAuditTargetOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vSize; +} + : tOption:Identifier EqualsSign + { + Match(tOption, CodeGenerationSupporter.MaxSize); + vResult.OptionKind=AuditTargetOptionKind.MaxSize; + UpdateTokenInfo(vResult, tOption); + } + ( + vSize = integer tUnit:Identifier + { + vResult.Size = vSize; + + if (TryMatch(tUnit, CodeGenerationSupporter.GB)) + { + vResult.Unit = MemoryUnit.GB; + ThrowIfTooLargeAuditFileSize(vSize, 10); + } + else if (TryMatch(tUnit, CodeGenerationSupporter.TB)) + { + vResult.Unit = MemoryUnit.TB; + ThrowIfTooLargeAuditFileSize(vSize, 20); + } + else + { + Match(tUnit, CodeGenerationSupporter.MB); + vResult.Unit = MemoryUnit.MB; + ThrowIfTooLargeAuditFileSize(vSize, 0); + } + + UpdateTokenInfo(vResult, tUnit); + } + | + tUnlimited:Identifier + { + Match(tUnlimited, CodeGenerationSupporter.Unlimited); + vResult.IsUnlimited = true; + vResult.Size = null; + vResult.Unit = MemoryUnit.Unspecified; + } + ) + ; + +retentionDaysAuditUrlOption returns [RetentionDaysAuditTargetOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vDays; +} + : tRetentionDays:Identifier EqualsSign + { + Match(tRetentionDays, CodeGenerationSupporter.RetentionDays); + vResult.OptionKind=AuditTargetOptionKind.RetentionDays; + UpdateTokenInfo(vResult, tRetentionDays); + } + ( + vDays = integer + { + vResult.Days = vDays; + } + ) + ; + +maxRolloverFilesAuditFileOption returns [MaxRolloverFilesAuditTargetOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tOption:Identifier EqualsSign + { + Match(tOption, CodeGenerationSupporter.MaxRolloverFiles); + vResult.OptionKind=AuditTargetOptionKind.MaxRolloverFiles; + UpdateTokenInfo(vResult, tOption); + } + ( + vValue = integer + { + vResult.Value = vValue; + } + | + tUnlimited:Identifier + { + Match(tUnlimited, CodeGenerationSupporter.Unlimited); + vResult.IsUnlimited = true; + UpdateTokenInfo(vResult, tUnlimited); + } + ) + ; + +maxFilesAuditFileOption returns [LiteralAuditTargetOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tOption:Identifier EqualsSign vValue = integer + { + Match(tOption, CodeGenerationSupporter.MaxFiles); + vResult.OptionKind=AuditTargetOptionKind.MaxFiles; + UpdateTokenInfo(vResult, tOption); + vResult.Value = vValue; + } + ; + +reserveDiskSpaceAuditFileOption returns [OnOffAuditTargetOption vResult = FragmentFactory.CreateFragment()] +{ + OptionState vValue; +} + : tOption:Identifier EqualsSign vValue = optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.ReserveDiskSpace); + vResult.OptionKind=AuditTargetOptionKind.ReserveDiskSpace; + UpdateTokenInfo(vResult, tOption); + vResult.Value = vValue; + } + ; + +pathAuditFileOption returns [LiteralAuditTargetOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tOption:Identifier EqualsSign vValue = stringLiteral + { + if(TryMatch(tOption, CodeGenerationSupporter.FilePath)) + { + vResult.OptionKind=AuditTargetOptionKind.FilePath; + } + else + { + Match(tOption, CodeGenerationSupporter.Path); + vResult.OptionKind=AuditTargetOptionKind.Path; + } + UpdateTokenInfo(vResult, tOption); + vResult.Value = vValue; + } + ; + +auditCreateWithClause [ServerAuditStatement vParent] +{ + AuditOption vOption; +} + : With LeftParenthesis vOption = auditCreateOption + { + AddAndUpdateTokenInfo(vParent, vParent.Options, vOption); + } + (Comma vOption = auditCreateOption + { + AddAndUpdateTokenInfo(vParent, vParent.Options, vOption); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vParent, tRParen); + } + ; + +auditWithClause [ServerAuditStatement vParent] +{ + AuditOption vOption; +} + : With LeftParenthesis vOption = auditOption + { + AddAndUpdateTokenInfo(vParent, vParent.Options, vOption); + } + (Comma vOption = auditOption + { + AddAndUpdateTokenInfo(vParent, vParent.Options, vOption); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vParent, tRParen); + } + ; + +// Corresponds to audit_create_option_element in SQL yacc +auditCreateOption returns [AuditOption vResult] + : + tOption:Identifier EqualsSign + ( + vResult = queueDelayAuditOption[tOption] + | + vResult = onFailureAuditOption[tOption] + | + vResult = auditGuidAuditOption[tOption] + | + vResult = operatorAuditOption[tOption] + ) + ; + +// Corresponds to audit_option_element in SQL yacc +auditOption returns [AuditOption vResult] + : + tOption:Identifier EqualsSign + ( + vResult = queueDelayAuditOption[tOption] + | + vResult = onFailureAuditOption[tOption] + | + {TryMatch(tOption, CodeGenerationSupporter.OperatorAudit)}? + vResult = operatorAuditOption[tOption] + | + {TryMatch(tOption, CodeGenerationSupporter.State)}? + vResult = stateAuditOption[tOption] + ) + ; + +queueDelayAuditOption [IToken tOption] returns [QueueDelayAuditOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : vValue = integer + { + Match(tOption, CodeGenerationSupporter.QueueDelay); + vResult.OptionKind=AuditOptionKind.QueueDelay; + UpdateTokenInfo(vResult,tOption); + vResult.Delay = vValue; + } + ; + +onFailureAuditOption [IToken tOption] returns [OnFailureAuditOption vResult = FragmentFactory.CreateFragment()] + : + { + Match(tOption, CodeGenerationSupporter.OnFailure); + UpdateTokenInfo(vResult,tOption); + vResult.OptionKind=AuditOptionKind.OnFailure; + } + ( + tContinue:Continue + { + UpdateTokenInfo(vResult,tContinue); + vResult.OnFailureAction = AuditFailureActionType.Continue; + } + | + tShutdown:Shutdown + { + UpdateTokenInfo(vResult,tShutdown); + vResult.OnFailureAction = AuditFailureActionType.Shutdown; + } + | + tIdentifier:Identifier + { + Match(tIdentifier, CodeGenerationSupporter.FailOperation); + UpdateTokenInfo(vResult, tIdentifier); + vResult.OnFailureAction = AuditFailureActionType.FailOperation; + } + ) + ; + +auditGuidAuditOption [IToken tOption] returns [AuditGuidAuditOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : vValue = stringLiteral + { + Match(tOption, CodeGenerationSupporter.AuditGuid); + ThrowIfWrongGuidFormat(vValue); + vResult.OptionKind=AuditOptionKind.AuditGuid; + UpdateTokenInfo(vResult,tOption); + vResult.Guid = vValue; + } + ; + +operatorAuditOption [IToken tOption] returns [OperatorAuditOption vResult = FragmentFactory.CreateFragment()] +{ + OptionState vValue; +} + : vValue = optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.OperatorAudit); + vResult.OptionKind=AuditOptionKind.OperatorAudit; + UpdateTokenInfo(vResult,tOption); + vResult.Value = vValue; + } + ; + +stateAuditOption [IToken tOption] returns [StateAuditOption vResult = FragmentFactory.CreateFragment()] +{ + OptionState vValue; +} + : vValue = optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.State); + vResult.OptionKind=AuditOptionKind.State; + UpdateTokenInfo(vResult,tOption); + vResult.Value = vValue; + } + ; + +createServerAuditSpecificationStatement returns [CreateServerAuditSpecificationStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vAuditSpecName; + AuditSpecificationPart vPart; +} + : tSpecification:Identifier vAuditSpecName = identifier + { + Match(tSpecification, CodeGenerationSupporter.Specification); + vResult.SpecificationName = vAuditSpecName; + ThrowPartialAstIfPhaseOne(vResult); + } + auditSpecificationForClause[vResult] + ( // Conflicts with Add SIGNATURE (but it actually shouldn't, k=2 should be enough) + (Add LeftParenthesis) => + vPart = createAuditSpecificationDetail + { + AddAndUpdateTokenInfo(vResult, vResult.Parts, vPart); + } + (Comma vPart = createAuditSpecificationDetail + { + AddAndUpdateTokenInfo(vResult, vResult.Parts, vPart); + } + )* + )? + auditSpecificationStateOpt[vResult] + ; + +alterServerStatements returns [TSqlStatement vResult] + : + tServer:Identifier + { + Match(tServer, CodeGenerationSupporter.Server); + } + ( + {NextTokenMatches(CodeGenerationSupporter.Audit)}? + vResult = alterServerAuditStatements + | + {NextTokenMatches(CodeGenerationSupporter.Configuration)}? + vResult = alterServerConfigurationStatement + | + {NextTokenMatches(CodeGenerationSupporter.Role)}? + vResult = alterServerRoleStatement + ) + ; + +alterServerAuditStatements returns [TSqlStatement vResult] + : tAudit:Identifier + { + Match(tAudit, CodeGenerationSupporter.Audit); + } + ( + {NextTokenMatches(CodeGenerationSupporter.Specification)}? + vResult = alterServerAuditSpecificationStatement + | + vResult = alterServerAuditStatement + ) + ; + +alterServerAuditSpecificationStatement returns [AlterServerAuditSpecificationStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vAuditSpecName; + AuditSpecificationPart vPart; +} + : tSpecification:Identifier vAuditSpecName = identifier + { + Match(tSpecification, CodeGenerationSupporter.Specification); + vResult.SpecificationName = vAuditSpecName; + ThrowPartialAstIfPhaseOne(vResult); + } + (auditSpecificationForClause[vResult])? + ( // Conflicts with Add SIGNATURE and Drop statements + ((Add|Drop) LeftParenthesis) => + vPart = auditSpecificationDetail + { + AddAndUpdateTokenInfo(vResult, vResult.Parts, vPart); + } + (Comma vPart = auditSpecificationDetail + { + AddAndUpdateTokenInfo(vResult, vResult.Parts, vPart); + } + )* + )? + auditSpecificationStateOpt[vResult] + ; + +alterServerAuditStatement returns [AlterServerAuditStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vAuditName; + Identifier vNewName; + AuditTarget vTarget = null; + BooleanExpression vFilterPredicate = null; +} + : vAuditName = identifier + { + vResult.AuditName = vAuditName; + ThrowPartialAstIfPhaseOne(vResult); + } + ( + {NextTokenMatches(CodeGenerationSupporter.Modify)}? + tModify:Identifier tName:Identifier EqualsSign vNewName = identifier + { + Match(tModify, CodeGenerationSupporter.Modify); + Match(tName, CodeGenerationSupporter.Name); + vResult.NewName = vNewName; + } + | + ( + vTarget = auditTargetClause[false] + { + vResult.AuditTarget = vTarget; + } + )? + ( // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + auditWithClause[vResult] + )? + ( + Where vFilterPredicate=eventBooleanExpression + { + vResult.PredicateExpression = vFilterPredicate; + } + )? + { + if(vTarget == null && (vResult.Options == null || vResult.Options.Count == 0) && vFilterPredicate == null) + { + ThrowIncorrectSyntaxErrorException(vAuditName); + } + } + | + tRemove:Identifier tWhere:Where + { + Match(tRemove, CodeGenerationSupporter.Remove); + UpdateTokenInfo(vResult, tWhere); + vResult.RemoveWhere=true; + } + ) + ; + +alterServerConfigurationStatement returns [TSqlStatement vResult] + : + tConfiguration:Identifier Set + { + Match(tConfiguration, CodeGenerationSupporter.Configuration); + } + ( + {NextTokenMatches(CodeGenerationSupporter.Process)}? + vResult = alterServerConfigurationSetProcessAffinityStatement + | + {NextTokenMatches(CodeGenerationSupporter.Buffer)}? + vResult = alterServerConfigurationSetBufferPoolExtensionStatement + | + {NextTokenMatches(CodeGenerationSupporter.Diagnostics)}? + vResult = alterServerConfigurationSetDiagnosticsLogStatement + | + {NextTokenMatches(CodeGenerationSupporter.Failover)}? + vResult = alterServerConfigurationSetFailoverClusterPropertyStatement + | + {NextTokenMatches(CodeGenerationSupporter.Hadr)}? + vResult = alterServerConfigurationSetHadrClusterStatement + | + {NextTokenMatches(CodeGenerationSupporter.SoftNuma)}? + vResult = alterServerConfigurationSetSoftNumaStatement + | + {NextTokenMatches(CodeGenerationSupporter.External)}? + vResult = alterServerConfigurationSetExternalAuthenticationStatement + ) + ; + + +alterServerConfigurationSetExternalAuthenticationStatement returns [AlterServerConfigurationSetExternalAuthenticationStatement vResult = FragmentFactory.CreateFragment()] +{ + AlterServerConfigurationExternalAuthenticationOption vOption; +} + : tExternal:External tAuthentication:Identifier + { + Match(tExternal, CodeGenerationSupporter.External); + Match(tAuthentication, CodeGenerationSupporter.Authentication); + } + vOption=alterServerConfigurationExternalAuthenticationContainerOption + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + ; + +alterServerConfigurationExternalAuthenticationContainerOption returns [AlterServerConfigurationExternalAuthenticationContainerOption vResult = FragmentFactory.CreateFragment()] +{ + OnOffOptionValue vOptionValue; + AlterServerConfigurationExternalAuthenticationOption vAlterServerConfigurationExternalAuthenticationOption; +} + : vOptionValue=onOffOptionValue + { + vResult.OptionValue = vOptionValue; + vResult.OptionKind = AlterServerConfigurationExternalAuthenticationOptionKind.OnOff; + } + ( + { + // Additional options are only allowed when external authentication is set to ON + if (vOptionValue.OptionState != OptionState.On) + ThrowIncorrectSyntaxErrorException(vOptionValue); + } + LeftParenthesis + (vAlterServerConfigurationExternalAuthenticationOption=alterServerConfigurationExternalAuthenticationOption + { + AddAndUpdateTokenInfo(vResult, vResult.Suboptions, vAlterServerConfigurationExternalAuthenticationOption); + }) + RightParenthesis + | + { + // Empty rule: setting external authorization to OFF is the only allowed + if (vOptionValue.OptionState != OptionState.Off) + ThrowIncorrectSyntaxErrorException(vOptionValue); + } + ) + ; + +alterServerConfigurationExternalAuthenticationOption returns [AlterServerConfigurationExternalAuthenticationOption vResult] + : {NextTokenMatches(CodeGenerationSupporter.UseIdentity)}? + vResult = alterServerConfigurationExternalAuthenticationUseIdentityOption + | + {NextTokenMatches(CodeGenerationSupporter.CredentialName)}? + vResult = alterServerConfigurationExternalAuthenticationCredentialNameOption + ; + +alterServerConfigurationExternalAuthenticationCredentialNameOption returns [AlterServerConfigurationExternalAuthenticationOption vResult = FragmentFactory.CreateFragment()] +{ + LiteralOptionValue vCredentialName; +} + : tCredentialName:Identifier EqualsSign vCredentialName=stringLiteralOptionValue + { + Match(tCredentialName, CodeGenerationSupporter.CredentialName); + vResult.OptionKind = AlterServerConfigurationExternalAuthenticationOptionHelper.Instance.ParseOption(tCredentialName); + vResult.OptionValue = vCredentialName; + } + ; + +alterServerConfigurationExternalAuthenticationUseIdentityOption returns [AlterServerConfigurationExternalAuthenticationOption vResult = FragmentFactory.CreateFragment()] +{ +} + : tUseIdentity:Identifier + { + Match(tUseIdentity, CodeGenerationSupporter.UseIdentity); + vResult.OptionKind = AlterServerConfigurationExternalAuthenticationOptionHelper.Instance.ParseOption(tUseIdentity); + } + ; + +alterServerConfigurationSetSoftNumaStatement returns [AlterServerConfigurationSetSoftNumaStatement vResult = FragmentFactory.CreateFragment()] +{ + AlterServerConfigurationSoftNumaOption vOption; +} + : tSoftNuma:Identifier + { + Match(tSoftNuma, CodeGenerationSupporter.SoftNuma); + } + vOption=alterServerConfigurationSoftNumaOption + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + ; + +alterServerConfigurationSoftNumaOption returns [AlterServerConfigurationSoftNumaOption vResult = FragmentFactory.CreateFragment()] +{ + OnOffOptionValue vOptionValue; +} + : vOptionValue=onOffOptionValue + { + vResult.OptionKind = AlterServerConfigurationSoftNumaOptionKind.OnOff; + vResult.OptionValue = vOptionValue; + } + + ; + +alterServerConfigurationSetBufferPoolExtensionStatement returns [AlterServerConfigurationSetBufferPoolExtensionStatement vResult = FragmentFactory.CreateFragment()] +{ + AlterServerConfigurationBufferPoolExtensionOption vOption; +} + : tBuffer:Identifier tPool:Identifier tExtension:Identifier + { + Match(tBuffer, CodeGenerationSupporter.Buffer); + Match(tPool, CodeGenerationSupporter.Pool); + Match(tExtension, CodeGenerationSupporter.Extension); + } + vOption=alterServerConfigurationBufferPoolExtensionContainerOption + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + ; + +alterServerConfigurationBufferPoolExtensionContainerOption returns [AlterServerConfigurationBufferPoolExtensionContainerOption vResult = FragmentFactory.CreateFragment()] +{ + OnOffOptionValue vOptionValue; + AlterServerConfigurationBufferPoolExtensionOption vFileNameSuboption; + AlterServerConfigurationBufferPoolExtensionOption vSizeSuboption; +} + : vOptionValue=onOffOptionValue + { + vResult.OptionValue = vOptionValue; + vResult.OptionKind = AlterServerConfigurationBufferPoolExtensionOptionKind.OnOff; + } + ( + { + // Additional options are only allowed when buffer pool extension is set to ON + if (vOptionValue.OptionState != OptionState.On) + ThrowIncorrectSyntaxErrorException(vOptionValue); + } + tLParen:LeftParenthesis vFileNameSuboption=alterServerConfigurationBufferPoolExtensionFileNameOption + { + UpdateTokenInfo(vResult, tLParen); + AddAndUpdateTokenInfo(vResult, vResult.Suboptions, vFileNameSuboption); + } + tComma:Comma vSizeSuboption=alterServerConfigurationBufferPoolExtensionSizeOption tRParen:RightParenthesis + { + AddAndUpdateTokenInfo(vResult, vResult.Suboptions, vSizeSuboption); + UpdateTokenInfo(vResult, tRParen); + } + | + { + // Empty rule: setting buffer pool extension to OFF is the only allowed + if (vOptionValue.OptionState != OptionState.Off) + ThrowIncorrectSyntaxErrorException(vOptionValue); + } + ) + ; + +alterServerConfigurationBufferPoolExtensionFileNameOption returns [AlterServerConfigurationBufferPoolExtensionOption vResult = FragmentFactory.CreateFragment()] +{ + LiteralOptionValue vFileName; +} + : tFileName:Identifier EqualsSign vFileName=stringLiteralOptionValue + { + Match(tFileName, CodeGenerationSupporter.FileName); + vResult.OptionKind = AlterServerConfigurationBufferPoolExtensionOptionHelper.Instance.ParseOption(tFileName); + vResult.OptionValue = vFileName; + } + ; + +alterServerConfigurationBufferPoolExtensionSizeOption returns [AlterServerConfigurationBufferPoolExtensionSizeOption vResult = FragmentFactory.CreateFragment()] +{ + LiteralOptionValue vSize; + MemoryUnit vMemUnit; +} + : tSize:Identifier EqualsSign vSize=integerLiteralOptionValue vMemUnit=memUnit[vResult] + { + Match(tSize, CodeGenerationSupporter.Size); + + if (vMemUnit != MemoryUnit.KB && vMemUnit != MemoryUnit.MB && vMemUnit != MemoryUnit.GB) + ThrowIncorrectSyntaxErrorException(vSize); + + vResult.OptionKind = AlterServerConfigurationBufferPoolExtensionOptionHelper.Instance.ParseOption(tSize); + vResult.OptionValue = vSize; + vResult.SizeUnit = vMemUnit; + } + ; + +alterServerConfigurationSetDiagnosticsLogStatement returns [AlterServerConfigurationSetDiagnosticsLogStatement vResult = FragmentFactory.CreateFragment()] +{ + AlterServerConfigurationDiagnosticsLogOption vOption; +} + : tDiagnostics:Identifier tLog:Identifier + { + Match(tDiagnostics, CodeGenerationSupporter.Diagnostics); + Match(tLog, CodeGenerationSupporter.Log); + } + vOption=alterServerConfigurationDiagnosticsLogOption + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + ; + +alterServerConfigurationDiagnosticsLogOption returns [AlterServerConfigurationDiagnosticsLogOption vResult = FragmentFactory.CreateFragment()] +{ + OptionValue vOptionValue; +} + : vOptionValue=onOffOptionValue + { + vResult.OptionKind = AlterServerConfigurationDiagnosticsLogOptionKind.OnOff; + vResult.OptionValue = vOptionValue; + } + | + {NextTokenMatches(CodeGenerationSupporter.MaxUnderscoreSize)}? + vResult=alterServerConfigurationDiagnosticsLogMaxSizeOption + | + tLogOption:Identifier EqualsSign + { + vResult.OptionKind = AlterServerConfigurationDiagnosticsLogOptionHelper.Instance.ParseOption(tLogOption); + } + ( + {vResult.OptionKind == AlterServerConfigurationDiagnosticsLogOptionKind.Path}? + vOptionValue=stringOrDefaultLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + | + {vResult.OptionKind == AlterServerConfigurationDiagnosticsLogOptionKind.MaxFiles}? + vOptionValue=integerOrDefaultLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + ) + ; + +alterServerConfigurationDiagnosticsLogMaxSizeOption returns [AlterServerConfigurationDiagnosticsLogMaxSizeOption vResult = FragmentFactory.CreateFragment()] +{ + OptionValue vOptionValue; +} + : tMaxSize:Identifier EqualsSign + { + vResult.OptionKind = AlterServerConfigurationDiagnosticsLogOptionHelper.Instance.ParseOption(tMaxSize); + if (vResult.OptionKind != AlterServerConfigurationDiagnosticsLogOptionKind.MaxSize) + ThrowIncorrectSyntaxErrorException(tMaxSize); + } + ( + vOptionValue=integerLiteralOptionValue tMB:Identifier + { + Match(tMB, CodeGenerationSupporter.MB); + vResult.OptionValue = vOptionValue; + vResult.SizeUnit = MemoryUnit.MB; + UpdateTokenInfo(vResult, tMB); + } + | + vOptionValue=defaultLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + ) + ; + +alterServerConfigurationSetFailoverClusterPropertyStatement returns [AlterServerConfigurationSetFailoverClusterPropertyStatement vResult = FragmentFactory.CreateFragment()] +{ + AlterServerConfigurationFailoverClusterPropertyOption vOption; +} + : tFailover:Identifier tCluster:Identifier tProperty:Identifier + { + Match(tFailover, CodeGenerationSupporter.Failover); + Match(tCluster, CodeGenerationSupporter.Cluster); + Match(tProperty, CodeGenerationSupporter.Property); + } + vOption=alterServerConfigurationFailoverClusterPropertyOption + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + ; + +alterServerConfigurationFailoverClusterPropertyOption returns [AlterServerConfigurationFailoverClusterPropertyOption vResult = FragmentFactory.CreateFragment()] +{ + OptionValue vOptionValue; +} + : tProperty:Identifier EqualsSign + { + vResult.OptionKind = AlterServerConfigurationFailoverClusterPropertyOptionHelper.Instance.ParseOption(tProperty); + } + ( + {vResult.OptionKind == AlterServerConfigurationFailoverClusterPropertyOptionKind.SqlDumperDumpFlags}? + vOptionValue=binaryOrDefaultLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + | + {vResult.OptionKind == AlterServerConfigurationFailoverClusterPropertyOptionKind.SqlDumperDumpPath}? + vOptionValue=stringOrDefaultLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + | + vOptionValue=integerOrDefaultLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + ) + ; + +alterServerConfigurationSetHadrClusterStatement returns [AlterServerConfigurationSetHadrClusterStatement vResult = FragmentFactory.CreateFragment()] +{ + AlterServerConfigurationHadrClusterOption vOption; +} + : tHadr:Identifier tCluster:Identifier + { + Match(tHadr, CodeGenerationSupporter.Hadr); + Match(tCluster, CodeGenerationSupporter.Cluster); + } + vOption=alterServerConfigurationHadrClusterOption + { + AddAndUpdateTokenInfo(vResult, vResult.Options, vOption); + } + ; + +alterServerConfigurationHadrClusterOption returns [AlterServerConfigurationHadrClusterOption vResult = FragmentFactory.CreateFragment()] +{ + OptionValue vOptionValue; +} + : tOptionKind:Identifier EqualsSign + { + vResult.OptionKind = AlterServerConfigurationHadrClusterOptionHelper.Instance.ParseOption(tOptionKind); + } + ( + vOptionValue=stringLiteralOptionValue + { + vResult.OptionValue = vOptionValue; + } + | + tLocal:Identifier + { + Match(tLocal, CodeGenerationSupporter.Local); + vResult.IsLocal = true; + UpdateTokenInfo(vResult, tLocal); + } + ) + ; + +alterServerConfigurationSetProcessAffinityStatement returns [AlterServerConfigurationStatement vResult = FragmentFactory.CreateFragment()] + : tProcess:Identifier tAffinity:Identifier + { + Match(tProcess, CodeGenerationSupporter.Process); + Match(tAffinity, CodeGenerationSupporter.Affinity); + } + tCpuOrNumanode:Identifier EqualsSign + ( + affinityRangeList[vResult] + { + if (TryMatch(tCpuOrNumanode, CodeGenerationSupporter.Cpu)) + { + vResult.ProcessAffinity = ProcessAffinityType.Cpu; + } + else + { + Match(tCpuOrNumanode, CodeGenerationSupporter.NumaNode); + vResult.ProcessAffinity = ProcessAffinityType.NumaNode; + } + } + | + tAuto:Identifier + { + // AUTO implies CPU affinity + Match(tCpuOrNumanode, CodeGenerationSupporter.Cpu); + Match(tAuto, CodeGenerationSupporter.Auto); + + vResult.ProcessAffinity = ProcessAffinityType.CpuAuto; + + UpdateTokenInfo(vResult, tAuto); + } + ) + ; + +affinityRangeList [AlterServerConfigurationStatement vParent] +{ + ProcessAffinityRange vAffinityRange; +} + : vAffinityRange = affinityRange + { + AddAndUpdateTokenInfo(vParent, vParent.ProcessAffinityRanges, vAffinityRange); + } + (Comma vAffinityRange = affinityRange + { + AddAndUpdateTokenInfo(vParent, vParent.ProcessAffinityRanges, vAffinityRange); + } + )* + ; + +affinityRange returns [ProcessAffinityRange vResult = FragmentFactory.CreateFragment()] +{ + Literal vBoundary; +} + : vBoundary = integer + { + vResult.From = vBoundary; + } + (To vBoundary = integer + { + vResult.To = vBoundary; + } + )? + ; + +////////////////////////////////////////////////////////////////////// +// Alter Database +////////////////////////////////////////////////////////////////////// +alterDatabaseStatements returns [TSqlStatement vResult = null] + : tAlter:Alter Database + ( + // Conflicts with alterDatabase alternative below + {NextTokenMatches(CodeGenerationSupporter.Audit) && NextTokenMatches(CodeGenerationSupporter.Specification, 2)}? + vResult = alterDatabaseAuditSpecification[tAlter] + | + {NextTokenMatches(CodeGenerationSupporter.Scoped) && NextTokenMatches(CodeGenerationSupporter.Credential, 2)}? + vResult = alterDatabaseScopedCredentialStatement[tAlter] + | + {NextTokenMatches(CodeGenerationSupporter.Scoped) && NextTokenMatches(CodeGenerationSupporter.Configuration, 2)}? + vResult = alterDatabaseScopedConfigurationStatement[tAlter] + | + vResult = alterDatabase[tAlter] + | + vResult = alterDatabaseEncryptionKey[tAlter] + ) + ; + +alterDatabaseScopedConfigurationStatement[IToken tAlter] returns [AlterDatabaseScopedConfigurationStatement vResult] +{ + bool vSecondary = false; +} + : + tScoped:Identifier tConfiguration:Identifier + { + Match(tScoped, CodeGenerationSupporter.Scoped); + Match(tConfiguration, CodeGenerationSupporter.Configuration); + } + (For tSecondary:Identifier + { + vSecondary = true; + } + )? + ( + vResult = alterDatabaseScopedConfigSet[vSecondary] + | + vResult = alterDatabaseScopedConfigClear + ) + { + if (vSecondary) + { + vResult.Secondary = true; + UpdateTokenInfo(vResult,tSecondary); + } + UpdateTokenInfo(vResult,tAlter); + } + ; + +alterDatabaseScopedConfigClear returns [AlterDatabaseScopedConfigurationClearStatement vResult = FragmentFactory.CreateFragment()] +{ + DatabaseConfigurationClearOption vOption; +} + : + tClear:Identifier + { + Match(tClear, CodeGenerationSupporter.Clear); + UpdateTokenInfo(vResult, tClear); + } + vOption = databaseConfigurationClearOption + { + vResult.Option = vOption; + } + ; + +databaseConfigurationClearOption returns [DatabaseConfigurationClearOption vResult = FragmentFactory.CreateFragment()] +{ + BinaryLiteral vLiteral; +} + : + tOption:Identifier + { + vResult.OptionKind = DatabaseConfigClearOptionKindHelper.Instance.ParseOption(tOption, SqlVersionFlags.TSql170); + UpdateTokenInfo(vResult, tOption); + } + ( + vLiteral = binary + { + vResult.PlanHandle = vLiteral; + } + )? + ; + +alterDatabaseScopedConfigSet[bool forSecondary] returns [AlterDatabaseScopedConfigurationSetStatement vResult = FragmentFactory.CreateFragment()] +{ + DatabaseConfigurationSetOption vOption; +} + : + Set + ( + {NextTokenMatches(CodeGenerationSupporter.MaxDop)}? + vOption = alterDatabaseScopedMaxDopOption[forSecondary] + | + {NextTokenMatches(CodeGenerationSupporter.QueryOptimizerHotFixes) || NextTokenMatches(CodeGenerationSupporter.ParameterSniffing) || + NextTokenMatches(CodeGenerationSupporter.LegacyCardinalityEstimation)}? + vOption = alterDatabaseScopedOnOffPrimaryOption[forSecondary] + | + vOption = alterDatabaseScopedGenericOption[forSecondary] + ) + { + vResult.Option = vOption; + } + ; + +alterDatabaseScopedMaxDopOption[bool forSecondary] returns [MaxDopConfigurationOption vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : + tMaxDop:Identifier EqualsSign + { + vResult.OptionKind = DatabaseConfigSetOptionKindHelper.Instance.ParseOption(tMaxDop, SqlVersionFlags.TSql170); + UpdateTokenInfo(vResult, tMaxDop); + } + ( + vValue = integer + { + vResult.Value = vValue; + } + | + {NextTokenMatches(CodeGenerationSupporter.Primary)}? + tPrimary:Primary + { + if (!forSecondary) + { + ThrowParseErrorException("SQL46115", vResult, TSqlParserResource.SQL46115Message); + } + vResult.Primary = true; + UpdateTokenInfo(vResult, tPrimary); + } + ) + ; + +alterDatabaseScopedOnOffPrimaryOption[bool forSecondary] returns [OnOffPrimaryConfigurationOption vResult = FragmentFactory.CreateFragment()] +{ + DatabaseConfigurationOptionState vOptionState; +} + : + tOption:Identifier + { + vResult.OptionKind = DatabaseConfigSetOptionKindHelper.Instance.ParseOption(tOption, SqlVersionFlags.TSql170); + UpdateTokenInfo(vResult, tOption); + } + EqualsSign + ( + vOptionState = databaseConfigurationOptionOnOffPrimary[vResult] + { + if(!forSecondary && vOptionState == DatabaseConfigurationOptionState.Primary) + { + ThrowParseErrorException("SQL46115", vResult, TSqlParserResource.SQL46115Message); + } + } + ) + { + vResult.OptionState = vOptionState; + } + ; + +alterDatabaseScopedGenericOption[bool forSecondary] returns [GenericConfigurationOption vResult = FragmentFactory.CreateFragment()] +{ + Identifier vOptionName; + Identifier vValueOnOff; + IdentifierOrScalarExpression vValue; + IToken token = LT(1); +} + : + vOptionName = identifier + { + vResult.GenericOptionKind = vOptionName; + } + EqualsSign + ( + {NextTokenMatches(CodeGenerationSupporter.Primary)}? + tPrimary:Primary + { + vValue = CreateIdentifierOrScalarExpressionFromIdentifier(CreateIdentifierFromToken(tPrimary)); + UpdateTokenInfo(vValue, token); + if (!forSecondary) + { + ThrowParseErrorException("SQL46115", vValue, TSqlParserResource.SQL46115Message); + } + vResult.GenericOptionState = vValue; + } + | + vValue = stringOrSignedIntegerOrIdentifier + { + vResult.GenericOptionState = vValue; + } + | + vValueOnOff = onOff + { + vResult.GenericOptionState = CreateIdentifierOrScalarExpressionFromIdentifier(vValueOnOff);; + } + ) + ; + +alterDatabase [IToken tAlter] returns [AlterDatabaseStatement vResult = null] +{ + Identifier vIdentifier = null; + bool vUseCurrent = false; +} + : ( + vIdentifier=identifier + | + vIdentifier=sqlCommandIdentifier + | + tCurrent:Current + { + vUseCurrent=true; + } + ) + ( vResult = alterDbAdd + | {NextTokenMatches(CodeGenerationSupporter.Remove)}? + vResult = alterDbRemove + | {NextTokenMatches(CodeGenerationSupporter.Modify)}? + vResult = alterDbModify + | vResult = alterDbSet + | vResult = alterDbCollate + | vResult = alterDbRebuild // Undocumented - for PSS only + | vResult = alterDbPerformCutover + ) + { + if(vUseCurrent) + { + vResult.UseCurrent = true; + UpdateTokenInfo(vResult,tCurrent); + } + else + { + vResult.DatabaseName = vIdentifier; + } + UpdateTokenInfo(vResult,tAlter); + ThrowPartialAstIfPhaseOne(vResult); + } + ; + exception + catch[PhaseOnePartialAstException exception] + { + UpdateTokenInfo(exception.Statement,tAlter); + (exception.Statement as AlterDatabaseStatement).DatabaseName = vIdentifier; + throw; + } + +alterDbCollate returns [AlterDatabaseCollateStatement vResult = FragmentFactory.CreateFragment()] + : collation[vResult] + ; + +alterDbRebuild returns [AlterDatabaseRebuildLogStatement vResult = FragmentFactory.CreateFragment()] +{ + FileDeclaration vFileDeclaration; +} + : tRebuild:Identifier tLog:Identifier + { + Match(tRebuild, CodeGenerationSupporter.Rebuild); + Match(tLog, CodeGenerationSupporter.Log); + UpdateTokenInfo(vResult,tLog); + ThrowPartialAstIfPhaseOne(vResult); + } + (On vFileDeclaration = fileDecl[false] + { + vResult.FileDeclaration = vFileDeclaration; + } + )? + ; + +alterDbAdd returns [AlterDatabaseStatement vResult = null] + : Add + ( + vResult = alterDbAddFile + | + vResult = alterDbAddFilegroup + ) + ; + +// Add File / Add LOG File +alterDbAddFile returns [AlterDatabaseAddFileStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : (tLog:Identifier + { + Match(tLog,CodeGenerationSupporter.Log); + vResult.IsLog = true; + } + )? + File + { + ThrowPartialAstIfPhaseOne(vResult); + } + fileDeclBodyList[vResult, vResult.FileDeclarations] + (vIdentifier = toFilegroup + { + vResult.FileGroup = vIdentifier; + } + )? + ; + +// Add FILEGROUP +alterDbAddFilegroup returns [AlterDatabaseAddFileGroupStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : tFilegroup:Identifier vIdentifier=identifier + { + Match(tFilegroup, CodeGenerationSupporter.Filegroup); + vResult.FileGroup = vIdentifier; + } + (Contains tFileStreamOrMemoryOptimizedData:Identifier + { + if (TryMatch(tFileStreamOrMemoryOptimizedData, CodeGenerationSupporter.FileStream)) + { + vResult.ContainsFileStream = true;; + } + else + { + Match(tFileStreamOrMemoryOptimizedData, CodeGenerationSupporter.MemoryOptimizedData); + vResult.ContainsMemoryOptimizedData = true; + } + UpdateTokenInfo(vResult, tFileStreamOrMemoryOptimizedData); + } + )? + ; + +alterDbRemove returns [AlterDatabaseStatement vResult = null] +{ + Identifier vIdentifier; +} + : tRemove:Identifier + { + Match(tRemove,CodeGenerationSupporter.Remove); + } + (File vIdentifier = identifier + { + AlterDatabaseRemoveFileStatement removeFile = FragmentFactory.CreateFragment(); + removeFile.File = vIdentifier; + vResult = removeFile; + } + | + tFileGroup:Identifier vIdentifier = identifier + { + // REMOVE FILEGROUP + Match(tFileGroup,CodeGenerationSupporter.Filegroup); + AlterDatabaseRemoveFileGroupStatement vRemoveFilegroup = FragmentFactory.CreateFragment(); + vRemoveFilegroup.FileGroup = vIdentifier; + vResult = vRemoveFilegroup; + } + ) + ; + +alterDbModify returns [AlterDatabaseStatement vResult = null] +{ + Identifier vIdentifier; +} + : tModify:Identifier + { + Match(tModify,CodeGenerationSupporter.Modify); + } + ( + {NextTokenMatches(CodeGenerationSupporter.Name)}? + (tName:Identifier EqualsSign vIdentifier = identifier + { + // MODIFY NAME = + Match(tName,CodeGenerationSupporter.Name); + AlterDatabaseModifyNameStatement modifyDbName = FragmentFactory.CreateFragment(); + modifyDbName.NewDatabaseName = vIdentifier; + vResult = modifyDbName; + } + ) + | + (tFileGroup2:Identifier + { + Match(tFileGroup2,CodeGenerationSupporter.Filegroup); + } + vResult = alterDbModifyFilegroup + ) + | vResult = alterDbModifyFile + | vResult = alterDbModifyAzureOptions + ) + ; + +alterDbModifyAzureOptions returns [AlterDatabaseSetStatement vResult = FragmentFactory.CreateFragment()] + : + azureOptions[vResult, vResult.Options] + ( + With tManualCutover:Identifier + { + Match(tManualCutover, CodeGenerationSupporter.ManualCutover); + vResult.WithManualCutover = true; + UpdateTokenInfo(vResult, tManualCutover); + } + )? + ; + +// MODIFY File syntax +alterDbModifyFile returns [AlterDatabaseModifyFileStatement vResult = FragmentFactory.CreateFragment()] +{ + FileDeclaration vFileDecl; +} + : File + { + ThrowPartialAstIfPhaseOne(vResult); + } + vFileDecl = fileDecl[true] + { + vResult.FileDeclaration = vFileDecl; + } + ; + +alterDbModifyFilegroup returns [AlterDatabaseModifyFileGroupStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier, vIdentifier2; + AlterDatabaseTermination vTermination; +} + : vIdentifier = identifier + { + vResult.FileGroup = vIdentifier; + } + ( + (tName2:Identifier EqualsSign vIdentifier2 = identifier + { + // MODIFY FILEGROUP NAME = + Match(tName2,CodeGenerationSupporter.Name); + vResult.NewFileGroupName = vIdentifier2; + ThrowPartialAstIfPhaseOne(vResult); + } + ) + | tDefault:Default + { + // MODIFY FILEGROUP Default + vResult.MakeDefault = true; + UpdateTokenInfo(vResult,tDefault); + } + | + (tUpdatabilityOption:Identifier + { + // MODIFY FILEGROUP SqlFabricDW = 10, + + /// + /// Sql 18.0 mode. + /// + Sql180 = 11, } } diff --git a/Test/SqlDom/Baselines180/AutomaticIndexCompactionTests180.sql b/Test/SqlDom/Baselines180/AutomaticIndexCompactionTests180.sql new file mode 100644 index 00000000..f16b8b49 --- /dev/null +++ b/Test/SqlDom/Baselines180/AutomaticIndexCompactionTests180.sql @@ -0,0 +1,5 @@ +ALTER DATABASE db + SET AUTOMATIC_INDEX_COMPACTION = ON; + +ALTER DATABASE db + SET AUTOMATIC_INDEX_COMPACTION = OFF; \ No newline at end of file diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index f987f4a7..aca9deec 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -1,4 +1,4 @@ -using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.VisualStudio.TestTools.UnitTesting; using SqlStudio.Tests.AssemblyTools.TestCategory; using System; diff --git a/Test/SqlDom/Only180SyntaxTests.cs b/Test/SqlDom/Only180SyntaxTests.cs new file mode 100644 index 00000000..6fdad70b --- /dev/null +++ b/Test/SqlDom/Only180SyntaxTests.cs @@ -0,0 +1,92 @@ +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using System; +using System.Collections.Generic; +using System.IO; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + public partial class SqlDomTests + { + // Note: These filenames are case sensitive, make sure they match the checked-in file exactly + private static readonly ParserTest[] Only180TestInfos = + { + new ParserTest180("AutomaticIndexCompactionTests180.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2) + }; + + private static readonly ParserTest[] SqlAzure180_TestInfos = + { + // Add parser tests that have Azure-specific syntax constructs + // (those that have versioning visitor implemented) + // + }; + + /// + /// This test runs only the graph syntax tests. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void GraphTSql180SyntaxParserTest() + { + TSql180Parser parser = new TSql180Parser(true); + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + foreach (ParserTest ti in GraphTestsOnly) + { + ParserTest.ParseAndVerify(parser, scriptGen, ti._scriptFilename, ti._result180); + } + + // Parsing both for Azure and standalone flavors - explicitly set + // enum value to 'All' + // + parser = new TSql180Parser(true, SqlEngineType.All); + scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + scriptGen.Options.SqlEngineType = SqlEngineType.All; + foreach (ParserTest ti in GraphTestsOnly) + { + ParserTest.ParseAndVerify(parser, scriptGen, ti._scriptFilename, ti._result180); + } + + // Explicitly ask for 'standalone' and parse + // + parser = new TSql180Parser(true, SqlEngineType.Standalone); + scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + scriptGen.Options.SqlEngineType = SqlEngineType.Standalone; + foreach (ParserTest ti in GraphTestsOnly) + { + ParserTest.ParseAndVerify(parser, scriptGen, ti._scriptFilename, ti._result180); + } + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TSql180SyntaxTests() + { + TSql180Parser parser = new TSql180Parser(true); + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + foreach (ParserTest ti in Only180TestInfos) + { + ParserTest.ParseAndVerify(parser, scriptGen, ti._scriptFilename, ti._result180); + } + } + + /// + /// This test runs SQL Azure syntax tests - explicit check for Azure + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TSql180AzureOnlySyntaxTests() + { + TSql180Parser parser = new TSql180Parser(true, SqlEngineType.SqlAzure); + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql180); + scriptGen.Options.SqlEngineType = SqlEngineType.SqlAzure; + foreach (ParserTest ti in SqlAzure180_TestInfos) + { + ParserTest.ParseAndVerify(parser, scriptGen, ti._scriptFilename, ti._result180); + } + } + } +} diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index a2eaab85..8898e811 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -9,22 +9,22 @@ public partial class SqlDomTests // Note: These filenames are case sensitive, make sure they match the checked-in file exactly private static readonly ParserTest[] OnlyFabricDWTestInfos = { - new ParserTestFabricDW("CloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), - new ParserTestFabricDW("CreateAlterExternalDataSourceTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("CreateAlterTableClusterByTestsFabricDW.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 6), - new ParserTestFabricDW("CreateExternalTableStatementTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("CreateProcedureCloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4), - new ParserTestFabricDW("IdentityColumnTestsFabricDW.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("NestedCTETestsFabricDW.sql", nErrors80: 1, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2), - new ParserTestFabricDW("ScalarFunctionTestsFabricDW.sql", nErrors80: 3, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiAnalyzeSentimentTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiClassifyTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiExtractTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiFixGrammarTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0), - new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0) + new ParserTestFabricDW("CloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4, nErrors180: 4), + new ParserTestFabricDW("CreateAlterExternalDataSourceTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("CreateAlterTableClusterByTestsFabricDW.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 6, nErrors180: 6), + new ParserTestFabricDW("CreateExternalTableStatementTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("CreateProcedureCloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4, nErrors180: 4), + new ParserTestFabricDW("IdentityColumnTestsFabricDW.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("NestedCTETestsFabricDW.sql", nErrors80: 1, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2, nErrors180: 2), + new ParserTestFabricDW("ScalarFunctionTestsFabricDW.sql", nErrors80: 3, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiAnalyzeSentimentTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiClassifyTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiExtractTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiFixGrammarTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), }; [TestMethod] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 636c5260..54e2322b 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -7877,5 +7877,179 @@ public void OffsetWithFetchApproxError() "SELECT * FROM MyTable ORDER BY id OFFSET 10 ROWS FETCH APPROX NEXT 5 ROWS ONLY;", new ParserErrorInfo(34, "SQL46145")); } + + /// + /// Negative tests for VECTOR_SEARCH syntax with TSql180Parser. + /// Mirrors VectorSearchErrorTest170 but validates against the 180 parser + /// which has TOP_N as optional and supports WITH (FORCE_ANN_ONLY). + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void VectorSearchErrorTest180() + { + // Missing required parameters: TABLE + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH()", + new ParserErrorInfo(28, "SQL46010", ")")); + + // Missing required parameters: COLUMN + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1)", + new ParserErrorInfo(40, "SQL46010", ")")); + + // Missing required parameters: SIMILAR_TO + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1)", + new ParserErrorInfo(55, "SQL46010", ")")); + + // Missing required parameters: METRIC + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector)", + new ParserErrorInfo(82, "SQL46010", ")")); + + // TOP_N is OPTIONAL in TSql180 - no error when omitted (SQL Server 2025+) + // VECTOR_SEARCH without TOP_N is valid; no test case for missing TOP_N here. + + // Invalid order: COLUMN before TABLE + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(COLUMN = col1, TABLE = tbl1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(28, "SQL46010", "COLUMN")); + + // Invalid order: SIMILAR_TO before COLUMN + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, SIMILAR_TO = query_vector, COLUMN = col1, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(42, "SQL46010", "SIMILAR_TO")); + + // Invalid order: METRIC before SIMILAR_TO + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, METRIC = 'dot', SIMILAR_TO = query_vector, TOP_N = 5)", + new ParserErrorInfo(57, "SQL46005", "SIMILAR_TO", "METRIC")); + + // Invalid value: TABLE = 'tbl1' (should be identifier, not string) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = 'tbl1', COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(36, "SQL46010", "'tbl1'")); + + // Invalid value: TABLE = 123 (should be identifier, not integer) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = 123, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(36, "SQL46010", "123")); + + // Invalid value: COLUMN = 'col1' (should be identifier, not string) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = 'col1', SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(51, "SQL46010", "'col1'")); + + // Invalid value: COLUMN = 123 (should be identifier, not integer) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = 123, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(51, "SQL46010", "123")); + + // Invalid value: METRIC = dot (should be string literal) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = dot, TOP_N = 5)", + new ParserErrorInfo(93, "SQL46010", "dot")); + + // Invalid value: METRIC = 'invalid_value' (should be either 'cosine', 'dot', or 'euclidean') + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'invalid_value', TOP_N = 5)", + new ParserErrorInfo(93, "SQL46010", "'invalid_value'")); + + // Invalid value: TOP_N = '5' (should be integer, not string) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = '5')", + new ParserErrorInfo(108, "SQL46010", "'5'")); + + // Invalid value: TOP_N = -5 (should be positive integer) + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = -5)", + new ParserErrorInfo(108, "SQL46010", "-")); + + // Missing value after equals for TABLE + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = , COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(36, "SQL46010", ",")); + + // Missing value after equals for COLUMN + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = , SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(51, "SQL46010", ",")); + + // Missing value after equals for SIMILAR_TO + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = , METRIC = 'dot', TOP_N = 5)", + new ParserErrorInfo(70, "SQL46010", ",")); + + // Missing value after equals for METRIC + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = , TOP_N = 5)", + new ParserErrorInfo(93, "SQL46010", ",")); + + // Extra parameter after TOP_N + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5, EXTRA_PARAM = 'value')", + new ParserErrorInfo(109, "SQL46010", ",")); + + // Extra comma at end + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = tbl1, COLUMN = col1, SIMILAR_TO = query_vector, METRIC = 'dot', TOP_N = 5,)", + new ParserErrorInfo(109, "SQL46010", ",")); + + // Function call with constant input, not keyword params + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH('tbl1', 'col1', 'query_vector', 'dot', 5)", + new ParserErrorInfo(28, "SQL46010", "'tbl1'")); + + // Subquery not allowed in SIMILAR_TO parameter + ParserTestUtils.ErrorTest180( + "SELECT * FROM VECTOR_SEARCH(TABLE = graphnode, COLUMN = embedding, SIMILAR_TO = (SELECT TOP 1 embedding FROM GTQuery), METRIC = 'euclidean', TOP_N = 20) AS ann", + new ParserErrorInfo(80, "SQL46098")); + } + + /// + /// Negative test for OFFSET with FETCH APPROXIMATE - SQL46145 error (TSql180) + /// OFFSET clause cannot be used with FETCH APPROXIMATE (introduced in SQL Server 2025) + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void OffsetWithFetchApproximateError180() + { + // OFFSET + FETCH APPROXIMATE is invalid + ParserTestUtils.ErrorTest180( + "SELECT * FROM MyTable ORDER BY id OFFSET 5 ROWS FETCH APPROXIMATE NEXT 10 ROWS ONLY;", + new ParserErrorInfo(34, "SQL46145")); + } + + /// + /// Negative test for OFFSET with FETCH APPROX (abbreviated) - SQL46145 error (TSql180) + /// Verifies that abbreviated APPROX keyword also triggers validation + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void OffsetWithFetchApproxError180() + { + // OFFSET + FETCH APPROX (abbreviated) is invalid + ParserTestUtils.ErrorTest180( + "SELECT * FROM MyTable ORDER BY id OFFSET 10 ROWS FETCH APPROX NEXT 5 ROWS ONLY;", + new ParserErrorInfo(34, "SQL46145")); + } + + /// + /// Negative test for combining TIES with APPROXIMATE - syntax error (TSql180) + /// APPROXIMATE and TIES are mutually exclusive (introduced in SQL Server 2025) + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TopWithTiesAndApproximateError180() + { + // Cannot use both TIES and APPROXIMATE together + ParserTestUtils.ErrorTest180( + "SELECT TOP 10 WITH TIES WITH APPROXIMATE * FROM MyTable ORDER BY id;", + new ParserErrorInfo(24, "SQL46010", "WITH")); + } } } diff --git a/Test/SqlDom/ParserTest.cs b/Test/SqlDom/ParserTest.cs index a58c170b..8a144785 100644 --- a/Test/SqlDom/ParserTest.cs +++ b/Test/SqlDom/ParserTest.cs @@ -27,6 +27,7 @@ internal class ParserTest public readonly ParserTestOutput _result150; public readonly ParserTestOutput _result160; public readonly ParserTestOutput _result170; + public readonly ParserTestOutput _result180; public readonly ParserTestOutput _resultFabricDW; public ParserTest( @@ -34,7 +35,7 @@ public ParserTest( ParserTestOutput result80, ParserTestOutput result90, ParserTestOutput result100, ParserTestOutput result110, ParserTestOutput result120, ParserTestOutput result130, ParserTestOutput result140, ParserTestOutput result150, ParserTestOutput result160, - ParserTestOutput result170, ParserTestOutput resultFabricDW) + ParserTestOutput result170, ParserTestOutput result180, ParserTestOutput resultFabricDW) { _scriptFilename = scriptFilename; _result80 = result80; @@ -47,6 +48,7 @@ public ParserTest( _result150 = result150; _result160 = result160; _result170 = result170; + _result180 = result180; _resultFabricDW = resultFabricDW; } @@ -55,13 +57,13 @@ public ParserTest( ParserTestOutput result80, ParserTestOutput result90, ParserTestOutput result100, ParserTestOutput result110, ParserTestOutput result120, ParserTestOutput result130, ParserTestOutput result140, ParserTestOutput result150, ParserTestOutput result160, - ParserTestOutput result170) + ParserTestOutput result170, ParserTestOutput result180) : this( scriptFilename, result80, result90, result100, result110, result120, result130, result140, result150, result160, - result170, result170) + result170, result180, result180) { } @@ -75,7 +77,7 @@ public ParserTest( result80, result90, result100, result110, result120, result130, result140, result150, result160, - result160) + result160, result160) { } @@ -446,7 +448,7 @@ public ParserTest170(string scriptFilename, int? nErrors80 = null, int? nErrors9 new ParserTestOutput(nErrors80), new ParserTestOutput(nErrors90), new ParserTestOutput(nErrors100), new ParserTestOutput(nErrors110), new ParserTestOutput(nErrors120), new ParserTestOutput(nErrors130), new ParserTestOutput(nErrors140), new ParserTestOutput(nErrors150), new ParserTestOutput(nErrors160), - new ParserTestOutput("Baselines170")) + new ParserTestOutput("Baselines170"), new ParserTestOutput("Baselines170")) { } public ParserTest170(string scriptFilename, ParserTestOutput output80, ParserTestOutput output90, ParserTestOutput output100, @@ -459,7 +461,7 @@ public ParserTest170(string scriptFilename, ParserTestOutput output80, ParserTes output140, output150, output160, - new ParserTestOutput("Baselines170")) + new ParserTestOutput("Baselines170"), new ParserTestOutput("Baselines170")) { } public ParserTest170(string scriptFilename, params ParserErrorInfo[] errors80And90And100And110And120and130and140and150and160) @@ -471,24 +473,62 @@ public ParserTest170(string scriptFilename, params ParserErrorInfo[] errors80And new ParserTestOutput(errors80And90And100And110And120and130and140and150and160), new ParserTestOutput(errors80And90And100And110And120and130and140and150and160), new ParserTestOutput(errors80And90And100And110And120and130and140and150and160), - new ParserTestOutput("Baselines170")) + new ParserTestOutput("Baselines170"), new ParserTestOutput("Baselines170")) + { } + } + + internal class ParserTest180 : ParserTest + { + public ParserTest180(string scriptFilename, int? nErrors80 = null, int? nErrors90 = null, int? nErrors100 = null, int? nErrors110 = null, int? nErrors120 = null, int? nErrors130 = null, int? nErrors140 = null, int? nErrors150 = null, int? nErrors160 = null, int? nErrors170 = null) + : base( + scriptFilename, + new ParserTestOutput(nErrors80), new ParserTestOutput(nErrors90), new ParserTestOutput(nErrors100), + new ParserTestOutput(nErrors110), new ParserTestOutput(nErrors120), new ParserTestOutput(nErrors130), + new ParserTestOutput(nErrors140), new ParserTestOutput(nErrors150), new ParserTestOutput(nErrors160), + new ParserTestOutput(nErrors170), new ParserTestOutput("Baselines180")) + { } + + public ParserTest180(string scriptFilename, ParserTestOutput output80, ParserTestOutput output90, ParserTestOutput output100, + ParserTestOutput output110, ParserTestOutput output120, ParserTestOutput output130, ParserTestOutput output140, ParserTestOutput output150, ParserTestOutput output160, ParserTestOutput output170) + : base( + scriptFilename, + output80, output90, output100, + output110, output120, + output130, + output140, + output150, + output160, + output170, + new ParserTestOutput("Baselines180")) + { } + + public ParserTest180(string scriptFilename, params ParserErrorInfo[] errors80And90And100And110And120and130and140and150and160and170and180) + : base( + scriptFilename, + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput("Baselines180")) { } } internal class ParserTestFabricDW : ParserTest { - public ParserTestFabricDW(string scriptFilename, int nErrors80, int nErrors90, int nErrors100, int nErrors110, int nErrors120, int nErrors130, int nErrors140, int nErrors150, int nErrors160, int nErrors170) + public ParserTestFabricDW(string scriptFilename, int nErrors80, int nErrors90, int nErrors100, int nErrors110, int nErrors120, int nErrors130, int nErrors140, int nErrors150, int nErrors160, int nErrors170, int nErrors180) : base( scriptFilename, new ParserTestOutput(nErrors80), new ParserTestOutput(nErrors90), new ParserTestOutput(nErrors100), new ParserTestOutput(nErrors110), new ParserTestOutput(nErrors120), new ParserTestOutput(nErrors130), new ParserTestOutput(nErrors140), new ParserTestOutput(nErrors150), new ParserTestOutput(nErrors160), - new ParserTestOutput(nErrors170), new ParserTestOutput("BaselinesFabricDW")) + new ParserTestOutput(nErrors170), new ParserTestOutput(nErrors180), new ParserTestOutput("BaselinesFabricDW")) { } public ParserTestFabricDW(string scriptFilename, ParserTestOutput output80, ParserTestOutput output90, ParserTestOutput output100, ParserTestOutput output110, ParserTestOutput output120, ParserTestOutput output130, ParserTestOutput output140, ParserTestOutput output150, ParserTestOutput output160, - ParserTestOutput output170) + ParserTestOutput output170, ParserTestOutput output180) : base( scriptFilename, output80, output90, output100, @@ -498,22 +538,23 @@ public ParserTestFabricDW(string scriptFilename, ParserTestOutput output80, Pars output150, output160, output170, + output180, new ParserTestOutput("BaselinesFabricDW")) { } - public ParserTestFabricDW(string scriptFilename, params ParserErrorInfo[] errors80And90And100And110And120and130and140and150and160and170) + public ParserTestFabricDW(string scriptFilename, params ParserErrorInfo[] errors80And90And100And110And120and130and140and150and160and170and180) : base( scriptFilename, - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), - new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), + new ParserTestOutput(errors80And90And100And110And120and130and140and150and160and170and180), new ParserTestOutput("BaselinesFabricDW")) { } } @@ -541,3 +582,4 @@ public ParserTest80And90And100(string scriptFilename, params ParserErrorInfo[] e } } + diff --git a/Test/SqlDom/TSqlParserTest.cs b/Test/SqlDom/TSqlParserTest.cs index ef6575ed..1d7abcd1 100644 --- a/Test/SqlDom/TSqlParserTest.cs +++ b/Test/SqlDom/TSqlParserTest.cs @@ -36,6 +36,7 @@ public void VerifySqlVersionToParserMapping() { SqlVersion.Sql150, typeof(TSql150Parser) }, { SqlVersion.Sql160, typeof(TSql160Parser) }, { SqlVersion.Sql170, typeof(TSql170Parser) }, + { SqlVersion.Sql180, typeof(TSql180Parser) }, { SqlVersion.SqlFabricDW, typeof(TSqlFabricDWParser) } }; diff --git a/Test/SqlDom/TestScripts/AutomaticIndexCompactionTests180.sql b/Test/SqlDom/TestScripts/AutomaticIndexCompactionTests180.sql new file mode 100644 index 00000000..e812ab76 --- /dev/null +++ b/Test/SqlDom/TestScripts/AutomaticIndexCompactionTests180.sql @@ -0,0 +1,9 @@ +-- Test cases for AUTOMATIC_INDEX_COMPACTION database option + +-- Simple ON state +ALTER DATABASE db + SET AUTOMATIC_INDEX_COMPACTION = ON; + +-- Simple OFF state +ALTER DATABASE db + SET AUTOMATIC_INDEX_COMPACTION = OFF; diff --git a/Test/SqlDom/TestUtilities.cs b/Test/SqlDom/TestUtilities.cs index 9d3ef18c..6d2ce902 100644 --- a/Test/SqlDom/TestUtilities.cs +++ b/Test/SqlDom/TestUtilities.cs @@ -32,6 +32,7 @@ public static void ExecuteTestForAllParsers(Action test, bool quoted new TSql150Parser(quotedIdentifiers), new TSql160Parser(quotedIdentifiers), new TSql170Parser(quotedIdentifiers), + new TSql180Parser(quotedIdentifiers), new TSqlFabricDWParser(quotedIdentifiers)); } @@ -69,6 +70,8 @@ internal static SqlScriptGenerator CreateScriptGen(SqlVersion sqlVersion) return new Sql160ScriptGenerator(options); case SqlVersion.Sql170: return new Sql170ScriptGenerator(options); + case SqlVersion.Sql180: + return new Sql180ScriptGenerator(options); case SqlVersion.SqlFabricDW: return new SqlFabricDWScriptGenerator(options); default: @@ -272,6 +275,14 @@ internal static void ErrorTest170(string testScript, params ParserErrorInfo[] ex ErrorTest(parser170, testScript, expectedErrors); } + internal static void ErrorTest180(string testScript, params ParserErrorInfo[] expectedErrors) + { + const bool quotedIdentifiers = true; + + TSql180Parser parser180 = new TSql180Parser(quotedIdentifiers); + ErrorTest(parser180, testScript, expectedErrors); + } + internal static void ErrorTestFabricDW(string testScript, params ParserErrorInfo[] expectedErrors) { const bool quotedIdentifiers = true; @@ -454,3 +465,4 @@ public static IList ParseTokensFromResource(TSqlParser parser, } } } + diff --git a/Test/SqlDom/UTSqlScriptDom.csproj b/Test/SqlDom/UTSqlScriptDom.csproj index 6b54bb51..c4ade393 100644 --- a/Test/SqlDom/UTSqlScriptDom.csproj +++ b/Test/SqlDom/UTSqlScriptDom.csproj @@ -29,6 +29,7 @@ + diff --git a/global.json b/global.json index f64b7fb9..d65b2d53 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.418", + "version": "8.0.419", "rollForward": "latestMajor" }, "msbuild-sdks": { diff --git a/release-notes/180/180.6.0.md b/release-notes/180/180.6.0.md new file mode 100644 index 00000000..a7a4db42 --- /dev/null +++ b/release-notes/180/180.6.0.md @@ -0,0 +1,26 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.6.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies + +#### .NET Framework +#### .NET Core + +### New Features +* Adds a new 180 parser. + +### Fixed + +### Changes +* None + +### Known Issues +* None \ No newline at end of file From 999ab543823ab21d1aef854083fe623bff8c6a74 Mon Sep 17 00:00:00 2001 From: Aasim Khan Date: Tue, 21 Apr 2026 10:56:23 -0700 Subject: [PATCH 25/45] Refactor T-SQL syntax verification guide and add agent documentation (#200) - Updated the T-SQL syntax verification guide in `.github/prompts/verify-and-test-tsql-syntax.prompt.md` to streamline instructions and emphasize the use of the canonical skill. - Introduced `AGENTS.md` to provide an overview of agent skills and instruction files, ensuring clarity on usage and versioning. - Created `CLAUDE.md` to establish `AGENTS.md` as the canonical instruction source for Claude workflows, reinforcing the importance of following shared guidelines. --- .../skills/add-feature/SKILL.md | 20 +- .../verify-and-test-tsql-syntax/SKILL.md | 115 +++ .../new-feature-implementation.prompt.md | 528 +------------ .../verify-and-test-tsql-syntax.prompt.md | 700 +----------------- AGENTS.md | 32 + CLAUDE.md | 7 + 6 files changed, 194 insertions(+), 1208 deletions(-) rename {.github => .agents}/skills/add-feature/SKILL.md (94%) create mode 100644 .agents/skills/verify-and-test-tsql-syntax/SKILL.md create mode 100644 AGENTS.md create mode 100644 CLAUDE.md diff --git a/.github/skills/add-feature/SKILL.md b/.agents/skills/add-feature/SKILL.md similarity index 94% rename from .github/skills/add-feature/SKILL.md rename to .agents/skills/add-feature/SKILL.md index ce63becb..2873e72c 100644 --- a/.github/skills/add-feature/SKILL.md +++ b/.agents/skills/add-feature/SKILL.md @@ -10,9 +10,9 @@ platforms: "SQL Server, Azure SQL DB, Fabric, Fabric DW, VNext" This skill helps add new T-SQL features to the ScriptDOM parser by: 1. **Interviewing** you about the feature and target platform (SQL Server, Azure SQL DB, Fabric, Fabric DW, VNext) -2. **Determining the latest parser version** from `SqlVersionFlags.cs` (currently TSql170) +2. **Determining the latest parser version** from `SqlVersionFlags.cs` 3. **Routing** you to the appropriate parser: - - SQL Server → version-specific parser (TSql120-170) + - SQL Server → version-specific parser (TSql120-180) - Azure SQL DB/Fabric/VNext → latest parser version - Fabric DW → separate TSqlFabricDW parser 4. **Classifying** the change type (grammar, validation, function, data type, etc.) @@ -33,7 +33,7 @@ Ask the user these questions to understand the feature: - **Azure SQL Database** (uses latest parser version) - **Fabric** (uses latest parser version) - **Fabric DW** (uses separate TSqlFabricDW parser) - - **VNext** (future version, uses latest parser version) + - **VNext** (future version, uses latest parser version unless repo instructions say otherwise) 3. **If SQL Server, which version introduced this feature?** - SQL Server 2014 (TSql120) @@ -42,7 +42,8 @@ Ask the user these questions to understand the feature: - SQL Server 2019 (TSql150) - SQL Server 2022 (TSql160) - SQL Server 2025 (TSql170) - - *(Skip if Azure SQL DB, Fabric, or VNext - these use latest version)* + - SQL Server vNext (TSql180) + - *(Skip if Azure SQL DB, Fabric, or VNext - these use TSql180 by default)* 4. **Do you have example T-SQL syntax or Microsoft documentation links?** - This helps verify the exact syntax requirements @@ -124,7 +125,7 @@ For grammar changes (Types B, C, D, E, G), follow this workflow: ### 3.1 Identify Target Grammar File **First, determine the latest parser version:** -Check `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` for the highest TSql version enum value (currently TSql170). +Check `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` for the highest TSql version enum value. **Then select the appropriate grammar file:** @@ -135,9 +136,10 @@ Check `SqlScriptDom/Parser/TSql/SqlVersionFlags.cs` for the highest TSql version - SQL 2019+: TSql150.g - SQL 2022+: TSql160.g - SQL 2025+: TSql170.g +- SQL Server vNext: TSql180.g #### For Azure SQL Database, Fabric, VNext: -- Use the **latest parser version** (e.g., TSql170.g) +- Use the **latest parser version** (currently TSql180.g) - Check `SqlVersionFlags.cs` to confirm the highest version #### For Fabric DW: @@ -174,7 +176,7 @@ If adding new AST nodes: ### 4.2 Add Test Method -#### For SQL Server versions (TSql120-170): +#### For SQL Server versions (TSql120-180): In `Test/SqlDom/OnlySyntaxTests.cs`: ```csharp @@ -191,8 +193,8 @@ Add to the `OnlyFabricDWTestInfos` array in `Test/SqlDom/OnlyFabricDWSyntaxTests ```csharp new ParserTestFabricDW("YourFeatureFabricDW.sql", nErrors80: X, nErrors90: Y, nErrors100: Z, - nErrors110: A, nErrors120: B, nErrors130: C, - nErrors140: D, nErrors150: E, nErrors160: F, nErrors170: G), + nErrors110: A, nErrors120: B, nErrors130: C, + nErrors140: D, nErrors150: E, nErrors160: F, nErrors170: G, nErrors180: H), ``` *(Set expected error counts for each parser version)* diff --git a/.agents/skills/verify-and-test-tsql-syntax/SKILL.md b/.agents/skills/verify-and-test-tsql-syntax/SKILL.md new file mode 100644 index 00000000..fed8121f --- /dev/null +++ b/.agents/skills/verify-and-test-tsql-syntax/SKILL.md @@ -0,0 +1,115 @@ +--- +name: verify-and-test-tsql-syntax +description: Verify whether an exact T-SQL script is already supported by SqlScriptDOM, then add or update the correct parser tests and baselines. Use when a user asks if syntax already works, or when adding regression coverage for a specific script. +argument-hint: "Exact T-SQL script or syntax to verify" +user-invocable: true +--- + +## Overview + +This skill determines whether a specific T-SQL script is already supported and then guides the follow-up testing work. + +Use it for: +- verifying whether a script already parses +- confirming which parser version should support the syntax +- adding or updating regression coverage in the existing ScriptDOM test framework + +Do not use it for broad feature design. If the verification shows missing parser support, route the implementation work to the appropriate repo instruction: +- [bug_fixing.guidelines.instructions.md](../../../.github/instructions/bug_fixing.guidelines.instructions.md) +- [grammar_validation.guidelines.instructions.md](../../../.github/instructions/grammar_validation.guidelines.instructions.md) +- [parser.guidelines.instructions.md](../../../.github/instructions/parser.guidelines.instructions.md) +- [testing.guidelines.instructions.md](../../../.github/instructions/testing.guidelines.instructions.md) + +## Core Rules + +- Always verify the exact T-SQL text first, character for character. +- For first-pass verification, add a debug unit test method to an existing test file such as `Only180SyntaxTests.cs` when the syntax targets vNext or the latest parser. +- Do not create standalone console apps, ad hoc parsers, or extra test projects. +- After verification, add proper test coverage through `TestScripts`, baselines, and the existing syntax test classes. +- Remove any temporary debug-only test methods once the result is confirmed. + +## Workflow + +### 1. Gather the minimum inputs + +Ask for: +- the exact T-SQL script to verify +- the SQL Server version or parser version expected to support it +- the current behavior and the expected behavior + +If the user has not supplied the exact script yet, stop and request it before continuing. + +### 2. Verify the exact script first + +Add a temporary debug unit test method to the appropriate existing test class and test the exact script as provided. + +Use this sequence: + +```bash +dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug +dotnet test --filter "DebugExactScriptTest" Test/SqlDom/UTSqlScriptDom.csproj -c Debug +``` + +Verification expectations: +- If parsing succeeds, move directly to comprehensive test coverage. +- If parsing fails, capture the exact parse errors and classify the failure. + +### 3. Classify the gap if verification fails + +Use the failure mode to route the next step: +- Grammar issue: parser does not recognize the syntax at all. +- Validation issue: syntax parses but is rejected as unsupported or invalid in context. +- Predicate recognition issue: identifier-based predicate fails in parentheses. + +When similar syntax already works in another context, prefer validation analysis before changing grammar. + +### 4. Add comprehensive coverage + +After verification, create or update the proper permanent tests using the existing framework: + +- Add the input script under `Test/SqlDom/TestScripts/`. +- Add the matching baseline under `Test/SqlDom/Baselines/`. +- Add the `ParserTest` entry or permanent test method in the correct `OnlySyntaxTests.cs` file. +- Preserve the exact user syntax in the test script before adding broader coverage. + +Determine the parser version using the repo mapping: +- SQL Server 2014 -> TSql120 +- SQL Server 2016 -> TSql130 +- SQL Server 2017 -> TSql140 +- SQL Server 2019 -> TSql150 +- SQL Server 2022 -> TSql160 +- SQL Server 2025 -> TSql170 +- SQL Server vNext/latest -> TSql180 + +### 5. Validate the testing slice + +Run validation in this order: + +```bash +dotnet test --filter "FullyQualifiedName~YourFeatureTest" Test/SqlDom/UTSqlScriptDom.csproj -c Debug +dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug +``` + +If the targeted test fails because of a baseline mismatch: +- use the generated output from the failure log to update the baseline +- rerun the same targeted test +- only then run the full suite + +## File Targets + +Use these repo paths when doing the work: +- Grammar files: `SqlScriptDom/Parser/TSql/TSql*.g` +- AST definition: `SqlScriptDom/Parser/TSql/Ast.xml` +- Validation code: `SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs` +- Test scripts: `Test/SqlDom/TestScripts/` +- Baselines: `Test/SqlDom/Baselines/` +- Syntax tests: `Test/SqlDom/OnlySyntaxTests.cs` + +## Completion Checklist + +- [ ] Verified the exact script first in an existing test file +- [ ] Classified the result as already supported or missing support +- [ ] Added or updated permanent test coverage in the standard test framework +- [ ] Preserved the exact user syntax in the new test script +- [ ] Ran targeted validation for the touched test slice +- [ ] Ran the full `UTSqlScriptDom` suite before finishing \ No newline at end of file diff --git a/.github/prompts/new-feature-implementation.prompt.md b/.github/prompts/new-feature-implementation.prompt.md index dd87fc90..69941ec7 100644 --- a/.github/prompts/new-feature-implementation.prompt.md +++ b/.github/prompts/new-feature-implementation.prompt.md @@ -1,518 +1,20 @@ -# New SQL Server Feature Implementation Guide - -This prompt will identify the type of SQL Server feature you want to add to SqlScriptDOM and **automatically implement it** using the appropriate guideline. After feature type identification, it will execute the complete implementation workflow. - -## Feature Type Identification - -Please answer the following questions to determine the best implementation approach: - -### 1. What type of SQL Server feature are you implementing? - -**A) Data Type** - A new SQL Server data type (e.g., VECTOR, GEOMETRY, GEOGRAPHY) -- Example: `DECLARE @embedding AS VECTOR(1536, FLOAT32)` -- Example: `CREATE TABLE tbl (geo_data GEOGRAPHY)` -- **Key indicators**: New type with custom parameters, specialized syntax for type definitions - -**B) Index Type** - A specialized index type with unique syntax (e.g., JSON INDEX, VECTOR INDEX) -- Example: `CREATE JSON INDEX IX_JSON ON table (column) FOR ('$.path1', '$.path2')` -- Example: `CREATE VECTOR INDEX IX_VECTOR ON table (column) WITH (METRIC = 'cosine')` -- **Key indicators**: CREATE [TYPE] INDEX syntax, type-specific clauses or options - -**C) System Function** - A new T-SQL built-in function (e.g., JSON_OBJECT, JSON_ARRAY) -- Example: `SELECT JSON_OBJECT('key1': 'value1', 'key2': 'value2')` -- Example: `RETURN JSON_ARRAY('item1', 'item2', 'item3')` -- **Key indicators**: Function calls in expressions, may need RETURN statement support - -**D) Grammar/Syntax Enhancement** - New operators, statements, or syntax modifications -- Example: Adding new WHERE clause predicates like `REGEXP_LIKE` -- Example: New statement types or operators -- **Key indicators**: Parser doesn't recognize syntax, needs AST updates - -**E) Validation Fix** - Existing syntax fails validation but should work per SQL Server docs -- Example: ALTER TABLE RESUMABLE option works in ALTER INDEX but not ALTER TABLE -- **Key indicators**: "Option 'X' is not valid..." errors, similar syntax works elsewhere - -**F) Parser Predicate Issue** - Identifier-based predicates fail with parentheses -- Example: `WHERE REGEXP_LIKE(...)` works but `WHERE (REGEXP_LIKE(...))` fails -- **Key indicators**: Syntax errors near closing parenthesis with identifier predicates - -### 2. SQL Server Feature Details - -**Feature Name**: _______________ -**SQL Server Version**: _______________ -**Example Syntax**: -```sql --- Provide 2-3 examples of the syntax you want to support -``` - -**Current Behavior**: _______________ -**Expected Behavior**: _______________ - -### 3. Feature Characteristics - -Check all that apply to your feature: - -- [ ] Requires completely new AST node classes -- [ ] Extends existing AST nodes with new members -- [ ] Needs new grammar rules in .g files -- [ ] Requires new keywords/constants -- [ ] Needs specialized script generation logic -- [ ] Has version-specific behavior (SQL Server 2014+, 2022+, etc.) -- [ ] Includes optional syntax elements or clauses -- [ ] Supports collections/lists of parameters -- [ ] Requires new validation logic -- [ ] Needs new index options or statement options - -## AUTO-IMPLEMENTATION TRIGGER - -**To begin automatic implementation, provide your feature details in this exact format:** - -``` -Feature Name: [Your feature name] -SQL Server Version: [SQL Server version] -Exact T-SQL Syntax: -```sql -[Copy the EXACT T-SQL syntax from the user's request here] -``` -Feature Type: [Will be determined from analysis below] -``` - -**The system will then automatically identify the feature type and begin implementation.** - -## Implementation Guidance - -Based on your feature type identification below, the system will automatically execute the appropriate implementation workflow: - -### → Data Type (Answer A) -**Auto-Executes**: [New Data Types Guidelines](../instructions/new_data_types.guidelines.instructions.md) - -**Automatic implementation includes**: -- Creating new `DataTypeReference` AST classes -- Adding specialized parsing rules for custom type syntax -- Implementing parameter handling (dimensions, base types, etc.) -- Script generation for type definitions -- Version-specific type support -- Comprehensive testing across all SQL contexts - -**Best for**: VECTOR, custom CLR types, spatial types, hierarchical types - -### → Index Type (Answer B) -**Auto-Executes**: [New Index Types Guidelines](../instructions/new_index_types.guidelines.instructions.md) - -**Automatic implementation includes**: -- Creating new `IndexStatement` AST classes -- Implementing type-specific index syntax parsing -- Adding specialized clauses (FOR, WITH type-specific options) -- Index option registration and validation -- Script generation for index statements -- Integration with existing index framework - -**Best for**: JSON INDEX, VECTOR INDEX, SPATIAL INDEX, custom index types - -### → System Function (Answer C) -**Auto-Executes**: [Function Guidelines](../instructions/function.guidelines.instructions.md) - -**Automatic implementation includes**: -- Function AST design for new T-SQL functions -- Grammar rules with syntactic predicates for RETURN statement support -- ANTLR v2 lookahead limitations and solutions -- Script generation for function calls -- Comprehensive testing in all expression contexts - -**Best for**: JSON_OBJECT, JSON_ARRAY, AI functions, mathematical functions - -### → Grammar/Syntax Enhancement (Answer D) -**Auto-Executes**: [Bug Fixing Guidelines](../instructions/bug_fixing.guidelines.instructions.md) - -**Automatic implementation includes**: -- Grammar rule modifications and AST updates -- Script generation implementation -- Testing framework integration -- Extending literals to expressions pattern -- Version compatibility considerations - -**Best for**: New operators, statement types, expression enhancements - -### → Validation Fix (Answer E) -**Auto-Executes**: [Validation Fix Guidelines](../instructions/validation_fix.guidelines.instructions.md) - -**Automatic implementation includes**: -- Version-gated validation fixes -- SQL Server version compatibility checks -- Context-specific validation rules -- Testing validation behavior across versions -- No grammar changes needed - -**Best for**: Feature works in one context but not another, version support issues - -### → Parser Predicate Issue (Answer F) -**Auto-Executes**: [Parser Guidelines](../instructions/parser.guidelines.instructions.md) - -**Automatic implementation includes**: -- Identifier-based predicate recognition fixes -- `IsNextRuleBooleanParenthesis()` function updates -- Syntactic vs semantic predicate handling -- Parentheses support in boolean contexts - -**Best for**: Functions work without parentheses but fail with them - -## Grammar Extension Patterns - -For users implementing Grammar/Syntax Enhancement (Option D), here are common patterns: - -### Pattern 1: Extending Literals to Expressions - -#### When to Use -When existing grammar rules only accept literal values but need to support dynamic expressions like parameters, variables, or computed values. - -#### Example Problem -Functions or constructs that currently accept only: -- `IntegerLiteral` (e.g., `TOP_N = 10`) -- `StringLiteral` (e.g., `VALUE = 'literal'`) - -But need to support: -- Parameters: `@parameter` -- Variables: `@variable` -- Column references: `table.column` -- Outer references: `outerref.column` -- Function calls: `FUNCTION(args)` -- Computed expressions: `value + 1` - -#### ⚠️ Critical Warning: Avoid Modifying Shared Grammar Rules - -**DO NOT** modify existing shared grammar rules like `identifierColumnReferenceExpression` that are used throughout the codebase. This can cause unintended side effects and break other functionality. - -**Instead**, create specialized rules for your specific context. - -#### Solution Template - -**Step 1: Update AST Definition (`Ast.xml`)** -```xml - - - - - -``` - -**Step 2: Create Context-Specific Grammar Rule (`TSql*.g`)** -```antlr -// Create a specialized rule for your context -yourContextColumnReferenceExpression returns [ColumnReferenceExpression vResult = this.FragmentFactory.CreateFragment()] -{ - MultiPartIdentifier vMultiPartIdentifier; -} - : - vMultiPartIdentifier=multiPartIdentifier[2] // Allows table.column syntax - { - vResult.ColumnType = ColumnType.Regular; - vResult.MultiPartIdentifier = vMultiPartIdentifier; - } - ; - -// Use the specialized rule in your custom grammar -yourContextParameterRule returns [ScalarExpression vResult] - : vResult=signedInteger - | vResult=variable - | vResult=yourContextColumnReferenceExpression // Context-specific rule - | vResult=expression // Allows computed expressions - ; -``` - -**Step 3: Verify Script Generator** -Most script generators using `GenerateNameEqualsValue()` or similar methods work automatically with `ScalarExpression`. No changes typically needed. - -#### Real-World Example: VECTOR_SEARCH TOP_N - -**Problem**: `VECTOR_SEARCH` TOP_N parameter only accepted integer literals. - -**❌ Wrong Approach**: Modify `identifierColumnReferenceExpression` to use `multiPartIdentifier[2]` -- **Result**: Broke `CreateIndexStatementErrorTest` because other grammar rules started accepting invalid syntax - -**✅ Correct Approach**: Create `vectorSearchColumnReferenceExpression` specialized for VECTOR_SEARCH -- **Result**: VECTOR_SEARCH supports multi-part identifiers without affecting other functionality - -**Final Implementation**: -```antlr -signedIntegerOrVariableOrColumnReference returns [ScalarExpression vResult] - : vResult=signedInteger - | vResult=variable - | vResult=vectorSearchColumnReferenceExpression // VECTOR_SEARCH-specific rule - ; - -vectorSearchColumnReferenceExpression returns [ColumnReferenceExpression vResult = ...] - : - vMultiPartIdentifier=multiPartIdentifier[2] // Allows table.column syntax - { - vResult.ColumnType = ColumnType.Regular; - vResult.MultiPartIdentifier = vMultiPartIdentifier; - } - ; -``` - -**Result**: Now supports dynamic TOP_N values: -```sql --- Parameters -VECTOR_SEARCH(..., TOP_N = @k) AS ann - --- Outer references -VECTOR_SEARCH(..., TOP_N = outerref.max_results) AS ann -``` - -### Pattern 2: Adding New Enum Members - -#### When to Use -When adding new operators, keywords, or options to existing constructs. - -#### Solution Template - -**Step 1: Update Enum in AST (`Ast.xml`)** -```xml - - - - - -``` - -**Step 2: Update Grammar Rule (`TSql*.g`)** -```antlr -// Add new token matching -| tNewValue:Identifier -{ - Match(tNewValue, CodeGenerationSupporter.NewValue); - vResult.EnumProperty = ExistingEnumType.NewValue; -} -``` - -**Step 3: Update Script Generator** -```csharp -// Add mapping in appropriate generator file -private static readonly Dictionary _enumGenerators = - new Dictionary() -{ - { EnumType.ExistingValue1, CodeGenerationSupporter.ExistingValue1 }, - { EnumType.ExistingValue2, CodeGenerationSupporter.ExistingValue2 }, - { EnumType.NewValue, CodeGenerationSupporter.NewValue }, // Add this -}; -``` - -### Pattern 3: Adding New Function or Statement - -#### When to Use -When adding completely new T-SQL functions or statements. - -#### Solution Template - -**Step 1: Define AST Node (`Ast.xml`)** -```xml - - - - -``` - -**Step 2: Add Grammar Rule (`TSql*.g`)** -```antlr -newFunctionCall returns [NewFunctionCall vResult = FragmentFactory.CreateFragment()] -{ - ScalarExpression vParam1; - StringLiteral vParam2; -} - : - tFunction:Identifier LeftParenthesis - { - Match(tFunction, CodeGenerationSupporter.NewFunction); - UpdateTokenInfo(vResult, tFunction); - } - vParam1 = expression - { - vResult.Parameter1 = vParam1; - } - Comma vParam2 = stringLiteral - { - vResult.Parameter2 = vParam2; - } - RightParenthesis - ; -``` - -**Step 3: Integrate with Existing Rules** -Add the new rule to appropriate places in the grammar (e.g., `functionCall`, `primaryExpression`, etc.). - -**Step 4: Create Script Generator** -```csharp -public override void ExplicitVisit(NewFunctionCall node) -{ - GenerateIdentifier(CodeGenerationSupporter.NewFunction); - GenerateSymbol(TSqlTokenType.LeftParenthesis); - GenerateFragmentIfNotNull(node.Parameter1); - GenerateSymbol(TSqlTokenType.Comma); - GenerateFragmentIfNotNull(node.Parameter2); - GenerateSymbol(TSqlTokenType.RightParenthesis); -} -``` - -## Quick Decision Tree - -**Start here** → Does the syntax exist in SQL Server documentation? - -**No** → Use Grammar/Syntax Enhancement (D) - -**Yes** → Does SqlScriptDOM recognize the syntax? - -**No** → What type of syntax? -- Data type declaration → Data Type (A) -- CREATE [TYPE] INDEX → Index Type (B) -- Function call → System Function (C) -- Other syntax → Grammar/Syntax Enhancement (D) - -**Yes** → Does it parse without errors? - -**No** → Parser Predicate Issue (F) - -**Yes** → Does validation reject it incorrectly? - -**Yes** → Validation Fix (E) - -**No** → Review existing implementation or check for edge cases - -## Pre-Implementation Checklist - -Before starting implementation: - -- [ ] Verified feature exists in SQL Server documentation -- [ ] Identified target SQL Server version for the feature -- [ ] Confirmed feature doesn't already exist in SqlScriptDOM -- [ ] Collected comprehensive syntax examples from SQL Server docs -- [ ] Reviewed similar existing implementations in the codebase -- [ ] Selected appropriate guideline based on feature type - -## Testing Strategy - -Regardless of feature type, ensure you: - -- [ ] Create comprehensive test scripts covering all syntax variations -- [ ] Generate proper baseline files with expected formatted output -- [ ] Configure error counts for all SQL Server versions -- [ ] Run full test suite to prevent regressions -- [ ] Test edge cases, quoted identifiers, and schema qualification -- [ ] Verify round-trip parsing (parse → generate → parse) - -## Additional Resources - -- **Main Copilot Instructions**: [copilot-instructions.md](../copilot-instructions.md) -- **Testing Framework Guide**: [Testing Guidelines](../instructions/testing.guidelines.instructions.md) -- **Grammar Extension Patterns**: See Grammar Extension Patterns section above -- **Detailed Grammar Guidelines**: [Grammar Guidelines](../instructions/grammer.guidelines.instructions.md) - +--- +name: new-feature-implementation +description: Copilot wrapper for the canonical add-feature skill used to implement new SqlScriptDOM T-SQL features. +argument-hint: "Feature description or exact T-SQL syntax" +agent: agent --- -**Ready to implement?** Follow the guideline that matches your feature type above. Each guide provides step-by-step instructions, real-world examples, and comprehensive testing strategies. - -## Implementation Workflow - -**IMPORTANT**: After identifying your feature type above, this prompt will automatically begin implementation. Provide the following information to start: - -### Required Information -1. **Feature Name**: _______________ -2. **SQL Server Version**: _______________ -3. **Exact T-SQL Syntax Examples**: -```sql --- Provide the EXACT syntax you want to support (copy-paste from user request) --- Example: SELECT JSON_OBJECTAGG( t.c1 : t.c2 ) FROM (VALUES('key1', 'c'), ('key2', 'b'), ('key3','a')) AS t(c1, c2); -``` -4. **Feature Type** (from analysis above): A, B, C, D, E, or F - -### Automatic Implementation Process - -Once you provide the information above, this prompt will: - -#### Phase 1: Analysis and Verification (Always Done First) -1. **Verify current status** using the exact syntax provided -2. **Search existing codebase** for similar implementations -3. **Identify SQL Server version** and parser target -4. **Create implementation plan** with specific steps -5. **Show the plan** and get confirmation before proceeding - -#### Phase 2: Implementation (Executed Automatically) -Based on feature type identification: - -**For Grammar/Syntax Enhancement (Type D)**: -1. **Update AST definition** (`Ast.xml`) if new nodes needed -2. **Add grammar rules** in appropriate `TSql*.g` files -3. **Create script generators** for new AST nodes -4. **Build and validate** parser compilation -5. **Create comprehensive tests** with exact syntax provided -6. **Generate baseline files** from parser output -7. **Run full test suite** to ensure no regressions - -**For Validation Fix (Type E)**: -1. **Locate validation function** throwing the error -2. **Verify Microsoft documentation** for version support -3. **Apply version-gated validation** (not unconditional rejection) -4. **Create test cases** covering all scenarios -5. **Build and validate** the fix -6. **Run full test suite** to ensure correctness - -**For System Function (Type C)**: -1. **Define AST node structure** for the function -2. **Add grammar rules** with syntactic predicates for RETURN statement support -3. **Create script generator** for the function -4. **Build and test** grammar changes -5. **Create comprehensive test scripts** including RETURN statement usage -6. **Validate full test suite** for regressions - -**For Data Type (Type A)**: -1. **Define AST node** inheriting from `DataTypeReference` -2. **Create specialized parsing rule** for the data type -3. **Integrate with scalar data type rule** -4. **Add string constants** for keywords -5. **Create script generator** -6. **Build and comprehensive test** across all SQL contexts - -**For Index Type (Type B)**: -1. **Define AST node** inheriting from `IndexStatement` -2. **Create specialized parsing rule** for the index type -3. **Integrate with main index grammar** -4. **Add index options** if needed -5. **Create script generator** -6. **Build and comprehensive test** all syntax variations - -**For Parser Predicate Issue (Type F)**: -1. **Locate `IsNextRuleBooleanParenthesis()`** function -2. **Add identifier-based predicate detection** -3. **Build and test** the fix -4. **Create tests** covering parentheses scenarios -5. **Validate** existing functionality - -#### Phase 3: Validation and Documentation -1. **Run complete test suite** (`dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug`) -2. **Verify all tests pass** (expect 1,100+ tests to succeed) -3. **Document changes made** with before/after examples -4. **Provide usage examples** showing the new functionality - -### Starting Implementation - -To begin implementation, provide your feature details using this format: - -``` -Feature Name: [FUNCTION_NAME or FEATURE_NAME] -SQL Server Version: [SQL Server 20XX / TSqlXXX] -Exact T-SQL Syntax: -```sql -[EXACT_COPY_OF_SYNTAX_FROM_USER_REQUEST] -``` -Feature Type: [A/B/C/D/E/F based on analysis above] -``` +Use the [canonical add-feature skill](../../.agents/skills/add-feature/SKILL.md) as the source of truth for this workflow. -**The prompt will then automatically execute the appropriate implementation workflow and start making the necessary code changes.** +- Implement the requested SQL Server feature end to end. +- Start by asking the discovery questions defined in the shared skill. +- Classify the request into the correct feature type before editing code. +- Follow the matching file in `.github/instructions/` for implementation, tests, and validation. +- Treat `TSql180` as the current vNext/latest parser target. +- Use the exact T-SQL syntax supplied by the user when creating tests. -### Implementation Principles +This prompt is a Copilot convenience wrapper around the shared skill. Keep the detailed workflow in the skill, not here. -1. **Always test exact syntax first**: Use the exact T-SQL provided, not simplified versions -2. **Follow established patterns**: Reuse existing patterns from similar implementations -3. **Maintain backward compatibility**: Ensure existing functionality continues to work -4. **Comprehensive testing**: Test all syntax variations, edge cases, and error conditions -5. **Version compatibility**: Consider which SQL Server versions should support the feature -6. **Full regression testing**: Always run the complete test suite before completion \ No newline at end of file +Input: +${input:featureDescription:Describe the feature or paste the exact T-SQL syntax} \ No newline at end of file diff --git a/.github/prompts/verify-and-test-tsql-syntax.prompt.md b/.github/prompts/verify-and-test-tsql-syntax.prompt.md index 95fb51f6..c7db92f1 100644 --- a/.github/prompts/verify-and-test-tsql-syntax.prompt.md +++ b/.github/prompts/verify-and-test-tsql-syntax.prompt.md @@ -1,692 +1,20 @@ --- -title: How to Verify T-SQL Syntax Support and Add Tests -description: Step-by-step guide to check if a T-SQL syntax is already supported and how to add comprehensive test coverage -tags: [testing, verification, tsql, syntax, parser, baseline] +name: verify-and-test-tsql-syntax +description: Copilot wrapper for the canonical shared skill that verifies exact T-SQL syntax support and adds permanent regression coverage. +argument-hint: "Exact T-SQL script or syntax to verify" +agent: agent --- -# How to Verify T-SQL Syntax Support and Add Tests +Use the [canonical verify-and-test-tsql-syntax skill](../../.agents/skills/verify-and-test-tsql-syntax/SKILL.md) as the source of truth for this workflow. -This guide helps you determine if a T-SQL syntax is already supported by ScriptDOM and shows you how to add proper test coverage. +- Verify the exact T-SQL script first, character for character. +- Use an existing test file for any temporary debug verification. +- If the script already works, add comprehensive permanent tests and baselines. +- If it fails, classify the gap before implementing a fix. +- Treat `TSql180` as the current vNext/latest parser target when the syntax is for vNext or the latest parser. +- Remove temporary debug-only verification code before finishing. -## Step 0: Verify the Exact Script First +This prompt is a Copilot convenience wrapper around the shared skill. Keep the detailed workflow in the skill, not here. -**CRITICAL**: Before doing anything else, test the exact T-SQL script provided to confirm whether it works or fails. - -**IMPORTANT**: For initial verification, you MUST add a debug unit test method directly to an existing test file (like Only170SyntaxTests.cs). This is only for initial verification. Once you confirm the syntax status, you'll follow the proper testing workflow to add comprehensive test coverage. - -### Step 1: Add Debug Unit Test Method - -Add this debug test method to the appropriate test file (e.g., `Test/SqlDom/Only170SyntaxTests.cs`): - -```csharp -[TestMethod] -public void DebugExactScriptTest() -{ - // PUT THE EXACT T-SQL SCRIPT HERE - DO NOT CREATE SEPARATE FILES - string script = @"SELECT Id, - DATEADD(DAY, 1, GETDATE()) -FROM Table1"; - - Console.WriteLine($"Testing exact script: {script}"); - - // Test with the target parser version first (e.g., TSql170) - TSql170Parser parser170 = new TSql170Parser(true); - IList errors170; - - using (StringReader reader = new StringReader(script)) - { - TSqlFragment fragment = parser170.Parse(reader, out errors170); - - Console.WriteLine($"\n=== TSql170 Parser Results ==="); - if (errors170.Count == 0) - { - Console.WriteLine("✅ SUCCESS: Parsed without errors"); - - // Test script generation (round-trip) - Sql170ScriptGenerator generator = new Sql170ScriptGenerator(); - string generatedScript; - generator.GenerateScript(fragment, out generatedScript); - Console.WriteLine($"Generated: {generatedScript}"); - } - else - { - Console.WriteLine($"❌ FAILED: {errors170.Count} parse errors:"); - foreach (var error in errors170) - { - Console.WriteLine($" Line {error.Line}, Col {error.Column}: {error.Message}"); - } - } - } - - // Test with older parser version for comparison (e.g., TSql160) - TSql160Parser parser160 = new TSql160Parser(true); - IList errors160; - - using (StringReader reader = new StringReader(script)) - { - TSqlFragment fragment = parser160.Parse(reader, out errors160); - - Console.WriteLine($"\n=== TSql160 Parser Results ==="); - if (errors160.Count == 0) - { - Console.WriteLine("✅ SUCCESS: Parsed without errors"); - } - else - { - Console.WriteLine($"❌ FAILED: {errors160.Count} parse errors:"); - foreach (var error in errors160) - { - Console.WriteLine($" Line {error.Line}, Col {error.Column}: {error.Message}"); - } - } - } - - // Use Assert.Inconclusive to document current status without failing the test - if (errors170.Count > 0) - { - Assert.Inconclusive($"Script currently fails with {errors170.Count} errors. Needs implementation."); - } - else - { - Assert.Inconclusive("Script already works! Can proceed to add comprehensive test coverage."); - } -} -``` - -### Step 2: Build and Run the Debug Test -### Step 2: Build and Run the Debug Test - -```bash -# 1. Build the parser to ensure it's up to date -dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug - -# 2. Run the debug test to see current status -dotnet test --filter "DebugExactScriptTest" Test/SqlDom/UTSqlScriptDom.csproj -c Debug - -# 3. Check the test output for detailed results -# Look for the console output showing parsing results -``` - -### Interpret Results - -- **✅ SUCCESS**: Script works! You can skip to Step 6 to add comprehensive tests -- **❌ FAILURE**: Script fails. Continue with Steps 1-5 to implement the missing functionality - -**Important**: Always test the **exact script provided** character-for-character, including: -- Exact table/column names (e.g., `t.c1`, `t.c2`) -- Exact function syntax (e.g., `JSON_OBJECTAGG( t.c1 : t.c2 )`) -- Complete query context (FROM clause, subqueries, etc.) -- Exact whitespace and formatting as provided - -**Remember**: Only add unit test methods to existing test files. Do not create separate SQL files, program files, or any other external files. - -## Step 1: Determine the SQL Server Version - -First, identify which SQL Server version introduced the syntax you want to test. - -### SQL Server Version Mapping - -| SQL Server Version | Parser Version | Year | Common Name | -|-------------------|----------------|------|-------------| -| SQL Server 2000 | TSql80 | 2000 | SQL Server 2000 | -| SQL Server 2005 | TSql90 | 2005 | SQL Server 2005 | -| SQL Server 2008 | TSql100 | 2008 | SQL Server 2008 | -| SQL Server 2012 | TSql110 | 2012 | SQL Server 2012 | -| SQL Server 2014 | TSql120 | 2014 | SQL Server 2014 | -| SQL Server 2016 | TSql130 | 2016 | SQL Server 2016 | -| SQL Server 2017 | TSql140 | 2017 | SQL Server 2017 | -| SQL Server 2019 | TSql150 | 2019 | SQL Server 2019 | -| SQL Server 2022 | TSql160 | 2022 | SQL Server 2022 | -| SQL Server 2025 | TSql170 | 2025 | SQL Server 2025 | - -### How to Find the Version - -1. **Check Microsoft Documentation**: Look for "Applies to: SQL Server 20XX (XX.x)" -2. **Search Online**: Look for the feature announcement or blog posts -3. **Test in SSMS**: Connect to different SQL Server versions and try the syntax - -**Example**: -- `RESUMABLE = ON` for ALTER TABLE → SQL Server 2022 → **TSql160** -- `MAX_DURATION` for indexes → SQL Server 2014 → **TSql120** -- `VECTOR_SEARCH` function → SQL Server 2025 → **TSql170** - -## Step 2: Check if Syntax is Already Supported - -### Method 1: Search Test Scripts (Fastest) -```bash -# Search for the keyword in test scripts -grep -r "YOUR_KEYWORD" Test/SqlDom/TestScripts/ - -# Example: Check if RESUMABLE is tested for ALTER TABLE -grep -r "RESUMABLE" Test/SqlDom/TestScripts/*.sql - -# Search in specific version test files -grep -r "RESUMABLE" Test/SqlDom/TestScripts/*160.sql -``` - -### Method 2: Search Grammar Files -```bash -# Search in grammar files -grep -r "YOUR_KEYWORD" SqlScriptDom/Parser/TSql/*.g - -# Example: Check if RESUMABLE is in grammar -grep -r "Resumable" SqlScriptDom/Parser/TSql/TSql160.g -``` - -### Method 3: Search AST Definitions -```bash -# Search in AST XML -grep -r "YourFeatureName" SqlScriptDom/Parser/TSql/Ast.xml - -# Example: Check for VECTOR_SEARCH node -grep -r "VectorSearch" SqlScriptDom/Parser/TSql/Ast.xml -``` - -### Method 4: Try Parsing with Test Script -Create a unit test method to verify parsing: - -```csharp -// Add to appropriate test file (e.g., Test/SqlDom/Only170SyntaxTests.cs) -[TestMethod] -public void QuickTestExactSyntax() -{ - string script = @"ALTER TABLE t ADD CONSTRAINT pk PRIMARY KEY (id) WITH (RESUMABLE = ON);"; - - TSql170Parser parser = new TSql170Parser(true); - IList errors; - - using (StringReader reader = new StringReader(script)) - { - TSqlFragment fragment = parser.Parse(reader, out errors); - Console.WriteLine($"Errors: {errors.Count}"); - - // This will show you exactly which parser versions support the syntax - // and what error messages are generated if it fails - } - - Assert.Inconclusive($"Test completed with {errors.Count} errors"); -} -``` - -### Method 5: Test in Existing Test Framework -Add a temporary test method to verify quickly: - -```csharp -// Add to appropriate test file (e.g., Test/SqlDom/Only170SyntaxTests.cs) -[TestMethod] -public void TempTestExactScript() -{ - // Put ONLY your exact script here - do not create external files - string script = @"YOUR_EXACT_SCRIPT_HERE"; - - TSql170Parser parser = new TSql170Parser(true); - IList errors; - - using (StringReader reader = new StringReader(script)) - { - TSqlFragment fragment = parser.Parse(reader, out errors); - Console.WriteLine($"Parse result: {errors.Count} errors"); - foreach (var error in errors) - { - Console.WriteLine($"Error: {error.Message}"); - } - } - - Assert.Inconclusive("Temporary test - remove after verification"); -} -``` - -Then run the test: -```bash -dotnet test --filter "TempTestExactScript" -c Debug -``` - -Remember to remove this temporary test method after verification. - -## Step 3: Create a Test Script - -**CRITICAL**: Your test script MUST include the exact T-SQL statement provided. Don't modify, simplify, or generalize the syntax - test the precise statement given. - -### Test File Naming Convention -Follow the pattern from testing.guidelines.instructions.md: -- Format: `Tests.sql` -- Examples: `JsonFunctionTests160.sql`, `AlterTableResumableTests160.sql` -- Location: `Test/SqlDom/TestScripts/` -- Use version number corresponding to SQL Server version where feature was introduced - -### Test Script Requirements - -1. **Start with the exact script provided** - copy it exactly as given -2. **Add comprehensive coverage** as described in testing guidelines: - - Basic syntax variations - - Function in different contexts (SELECT, WHERE, RETURN statements) - - Edge cases (empty parameters, NULL handling, subqueries) - - Integration contexts (variables, parameters, computed expressions) -3. **Include context** - ensure the exact context (table aliases, subqueries) is tested -4. **Test RETURN statements** - Critical for functions, always test in ALTER FUNCTION RETURN statements - -### Test Script Template - -Follow the comprehensive coverage pattern from testing guidelines: - -```sql --- Test 1: EXACT SCRIPT PROVIDED (REQUIRED - COPY EXACTLY) --- PUT THE EXACT T-SQL STATEMENT HERE WITHOUT ANY MODIFICATIONS --- Example: SELECT JSON_OBJECTAGG( t.c1 : t.c2 ) FROM (VALUES('key1', 'c'), ('key2', 'b'), ('key3','a')) AS t(c1, c2); - --- Test 2: Basic function call (if applicable) -SELECT YOUR_FUNCTION('param1', 'param2'); - --- Test 3: Function in different contexts -SELECT col1, YOUR_FUNCTION('param') AS computed FROM table1; -WHERE YOUR_FUNCTION('param') > 0; - --- Test 4: CRITICAL - Function in RETURN statements (for functions) -ALTER FUNCTION TestYourFunction() -RETURNS NVARCHAR(MAX) -AS -BEGIN - RETURN (YOUR_FUNCTION('test_value')); -END; -GO - --- Test 5: With variables/parameters -SELECT YOUR_FUNCTION(@variable); -SELECT YOUR_FUNCTION(column_name); - --- Test 6: Edge cases -SELECT YOUR_FUNCTION(); -- Empty parameters (if valid) -SELECT YOUR_FUNCTION(NULL, 'test', 123); -- NULL handling -SELECT YOUR_FUNCTION((SELECT nested FROM table)); -- Subqueries -``` - -### Real-World Example: ALTER TABLE RESUMABLE - -**File**: `Test/SqlDom/TestScripts/AlterTableResumableTests160.sql` - -```sql --- Test 1: RESUMABLE with MAX_DURATION (minutes) -ALTER TABLE dbo.MyTable -ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) -WITH (RESUMABLE = ON, MAX_DURATION = 240 MINUTES); - --- Test 2: RESUMABLE = ON -ALTER TABLE dbo.MyTable -ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) -WITH (RESUMABLE = ON); - --- Test 3: RESUMABLE = OFF -ALTER TABLE dbo.MyTable -ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) -WITH (RESUMABLE = OFF); - --- Test 4: UNIQUE constraint with RESUMABLE -ALTER TABLE dbo.MyTable -ADD CONSTRAINT uq_test UNIQUE NONCLUSTERED (name) -WITH (RESUMABLE = ON); -``` - -## Step 4: Configure Test Entry - -Add test configuration to the appropriate `OnlySyntaxTests.cs` file as described in testing guidelines. - -### Test Configuration File Location -- Format: `Only{Version}SyntaxTests.cs` -- Example: `Only160SyntaxTests.cs` (for SQL Server 2022) -- Location: `Test/SqlDom/` -- Add to the `Only{Version}TestInfos` array - -### Test Configuration Template - -Use the simplified approach from testing guidelines: - -```csharp -// Option 1: Simplified - only specify error counts you care about -new ParserTest{Version}("YourFeatureTests{Version}.sql"), // All previous versions default to null (ignored), current version expects 0 errors - -// Option 2: Specify only some previous version error counts -new ParserTest{Version}("YourFeatureTests{Version}.sql", nErrors80: 1, nErrors90: 1), // Only SQL 2000/2005 expect errors - -// Option 3: Full specification (legacy compatibility) -new ParserTest{Version}("YourFeatureTests{Version}.sql", - nErrors80: 1, // SQL Server 2000 - expect error for new syntax - nErrors90: 1, // SQL Server 2005 - expect error for new syntax - nErrors100: 1, // SQL Server 2008 - expect error for new syntax - nErrors110: 1, // SQL Server 2012 - expect error for new syntax - nErrors120: 1, // SQL Server 2014 - expect error for new syntax - nErrors130: 1, // SQL Server 2016 - expect error for new syntax - nErrors140: 1, // SQL Server 2017 - expect error for new syntax - nErrors150: 1 // SQL Server 2019 - expect error for new syntax - // nErrors{Version}: 0 is implicit for current version - expect success -), -``` - -### How to Determine Error Counts - -**Rule**: Count the number of SQL statements that will fail in each version. - -**Example**: If your test file has 4 statements with the new feature: -- Versions that DON'T support it: `nErrors = 4` (all 4 statements fail) -- Version that DOES support it: `nErrors = 0` (all 4 statements pass, implicit default) - -### Real-World Example: ALTER TABLE RESUMABLE - -**File**: `Test/SqlDom/Only160SyntaxTests.cs` - -```csharp -new ParserTest160("AlterTableResumableTests160.sql", - nErrors80: 4, // SQL Server 2000: RESUMABLE not supported (4 errors) - nErrors90: 4, // SQL Server 2005: RESUMABLE not supported (4 errors) - nErrors100: 4, // SQL Server 2008: RESUMABLE not supported (4 errors) - nErrors110: 4, // SQL Server 2012: RESUMABLE not supported (4 errors) - nErrors120: 4, // SQL Server 2014: RESUMABLE not supported (4 errors) - nErrors130: 4, // SQL Server 2016: RESUMABLE not supported (4 errors) - nErrors140: 4, // SQL Server 2017: RESUMABLE not supported (4 errors) - nErrors150: 4 // SQL Server 2019: RESUMABLE not supported (4 errors) - // nErrors160: 0 (implicit) - SQL Server 2022: RESUMABLE supported! (0 errors) -), -``` - -## Step 5: Create Baseline File - -Baseline files contain the expected formatted output after parsing and script generation. - -### Baseline File Location -- Format: `Baselines{Version}/YourTestFile{Version}.sql` -- Example: `Baselines160/AlterTableResumableTests160.sql` -- Location: `Test/SqlDom/` -- **Critical**: Baseline filename MUST exactly match the test script filename - -### Baseline Generation Process - -Follow the testing guidelines process: - -#### Initial Creation: -1. **Create empty or placeholder baseline file first** -2. **Run the test** (it will fail) -3. **Copy "Actual" output** from test failure message -4. **Paste into baseline file** with proper formatting - -```bash -# 1. Create placeholder baseline file -New-Item "Test/SqlDom/Baselines160/YourFeatureTests160.sql" -ItemType File - -# 2. Run the test (will fail initially) -dotnet test --filter "YourFeatureTests160" -c Debug - -# 3. Copy the "Actual" output from test failure into baseline file -# Look for the test failure message showing: -# Expected: -# Actual: - -# 4. Re-run the test (should pass now) -dotnet test --filter "YourFeatureTests160" -c Debug -``` - -#### Option B: Manual Creation - -Create the baseline file with properly formatted SQL: - -```sql --- Baseline follows ScriptDOM formatting rules: --- - Keywords in UPPERCASE --- - Proper indentation --- - Line breaks at appropriate places - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) WITH (RESUMABLE = ON, MAX_DURATION = 240 MINUTES); - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) WITH (RESUMABLE = ON); - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) WITH (RESUMABLE = OFF); - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT uq_test UNIQUE NONCLUSTERED (name) WITH (RESUMABLE = ON); -``` - -### Real-World Example: ALTER TABLE RESUMABLE Baseline - -**File**: `Test/SqlDom/Baselines160/AlterTableResumableTests160.sql` - -```sql -ALTER TABLE dbo.MyTable - ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) WITH (RESUMABLE = ON, MAX_DURATION = 240 MINUTES); - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) WITH (RESUMABLE = ON); - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT pk_test PRIMARY KEY CLUSTERED (id) WITH (RESUMABLE = OFF); - -ALTER TABLE dbo.MyTable - ADD CONSTRAINT uq_test UNIQUE NONCLUSTERED (name) WITH (RESUMABLE = ON); -``` - -## Step 6: Run and Validate Test - -Follow the testing guidelines validation process. - -### Build the Parser -```bash -# Build ScriptDOM library -dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug - -# Build test project -dotnet build Test/SqlDom/UTSqlScriptDom.csproj -c Debug -``` - -### Run Your Specific Test -```bash -# Run specific test method -dotnet test Test/SqlDom/UTSqlScriptDom.csproj --filter "FullyQualifiedName~TSql160SyntaxIn160ParserTest" -c Debug - -# Run tests for specific version -dotnet test Test/SqlDom/UTSqlScriptDom.csproj --filter "TestCategory=TSql160" -c Debug - -# Run by test script name filter -dotnet test --filter "YourFeatureTests160" -c Debug - -# Run with verbose output to see details -dotnet test --filter "YourFeatureTests160" -c Debug -v detailed -``` - -### Run Full Test Suite (CRITICAL!) -```bash -# Always run ALL tests before committing -dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug - -# Expected output: -# Test summary: total: 1116, failed: 0, succeeded: 1116, skipped: 0 -``` - -### Interpret Results - -Follow the testing guidelines interpretation: - -- ✅ **Success**: Generated output matches baseline, error counts match expectations -- ❌ **Failure**: Review actual vs expected output, adjust baseline or fix grammar -- ⚠️ **Baseline Mismatch**: Copy correct "Actual" output to baseline file -- ⚠️ **Error Count Mismatch**: Adjust error expectations in test configuration - -### Common Test Results - -✅ **Success**: All tests pass, including your new test -``` -Test summary: total: 1116, failed: 0, succeeded: 1116, skipped: 0 -``` - -❌ **Baseline Mismatch**: Generated output doesn't match baseline -``` -Expected: -Actual: -``` -**Solution**: Copy the "Actual" output to your baseline file (note spacing differences) - -❌ **Error Count Mismatch**: Parse error count differs from expected -``` -TestYourFeature.sql: number of errors after parsing is different from expected. -Expected: 1, Actual: 0 -``` -**Solutions**: -- **If Actual < Expected**: Grammar now supports syntax in older versions → Update error counts -- **If Actual > Expected**: Grammar has issues → Fix grammar or adjust test - -❌ **Parse Errors**: Syntax not recognized -``` -SQL46010: Incorrect syntax near 'YOUR_TOKEN'. at offset 45, line 2, column 15 -``` -**Solutions**: Check grammar rules, verify syntactic predicates, see function guidelines for RETURN statement issues - -## Complete Example Workflow - -### Example: Testing ALTER TABLE RESUMABLE for SQL Server 2022 - -```bash -# Step 0: Test exact script first -echo "ALTER TABLE MyTable ADD CONSTRAINT pk PRIMARY KEY (id) WITH (RESUMABLE = ON);" > temp_test_script.sql -# Add debug test method to Only160SyntaxTests.cs and run to confirm current status - -# Step 1: Determine version -# Research shows: RESUMABLE for ALTER TABLE added in SQL Server 2022 → TSql160 - -# Step 2: Check if already supported -grep -r "RESUMABLE" Test/SqlDom/TestScripts/*.sql -# Result: Found in ALTER INDEX tests, but not ALTER TABLE tests - -# Step 3: Create test script -New-Item "Test/SqlDom/TestScripts/AlterTableResumableTests160.sql" -# Add 4 test cases covering different scenarios - -# Step 4: Add test configuration -# Edit Test/SqlDom/Only160SyntaxTests.cs -# Add: new ParserTest160("AlterTableResumableTests160.sql", nErrors80: 4, ...) - -# Step 5: Create empty baseline -New-Item "Test/SqlDom/Baselines160/AlterTableResumableTests160.sql" - -# Step 6: Build and run test -dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug -dotnet test --filter "AlterTableResumableTests160" -c Debug -# Test fails - copy "Actual" output into baseline file - -# Step 7: Re-run test -dotnet test --filter "AlterTableResumableTests160" -c Debug -# Test passes! - -# Step 8: Run full suite -dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug -# All 1120 tests pass! - -# Step 9: Commit changes -git add Test/SqlDom/TestScripts/AlterTableResumableTests160.sql -git add Test/SqlDom/Baselines160/AlterTableResumableTests160.sql -git add Test/SqlDom/Only160SyntaxTests.cs -git commit -m "Add tests for ALTER TABLE RESUMABLE option (SQL Server 2022)" -``` - -## Testing Best Practices - -### 1. Comprehensive Coverage -- ✅ **TEST EXACT SCRIPT PROVIDED** (most critical) -- ✅ Test basic syntax variations -- ✅ Test with multiple options -- ✅ Test different statement variations -- ✅ Test with parameters/variables (if applicable) -- ✅ Test edge cases -- ✅ Test error conditions (if relevant) -- ✅ Test complete context (subqueries, table aliases, etc.) - -### 2. Baseline Accuracy -- ✅ Generate baseline from actual parser output -- ✅ Don't hand-edit baseline formatting -- ✅ Verify baseline matches ScriptDOM formatting conventions -- ✅ Check for proper indentation and line breaks - -### 3. Version-Specific Testing -- ✅ Test only in the version where feature was introduced -- ✅ Verify older versions properly reject the syntax -- ✅ Document version dependencies clearly - -### 4. Regression Prevention -- ✅ Always run full test suite before committing -- ✅ Investigate any unexpected test failures -- ✅ Don't assume your change is isolated - -## Common Pitfalls - -### ❌ Wrong Version Number -**Problem**: Testing in TSql150 when feature is TSql160-only -**Solution**: Verify SQL Server version in Microsoft docs - -### ❌ Incorrect Error Counts -**Problem**: `nErrors80: 2` but test has 4 failing statements -**Solution**: Count all statements that use the new feature - -### ❌ Hand-Edited Baselines -**Problem**: Baseline formatting doesn't match ScriptDOM output -**Solution**: Always copy from actual parser output - -### ❌ Skipping Full Test Suite -**Problem**: Your change breaks existing tests -**Solution**: Run `dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug` - -### ❌ Missing Test Cases -**Problem**: Feature works for basic case but fails with parameters -**Solution**: Add comprehensive test coverage - -### ❌ Not Testing Exact Script -**Problem**: Testing simplified/modified versions instead of the exact script provided -**Solution**: Always include the exact T-SQL statement as provided, character-for-character - -## Troubleshooting - -### Test Fails: "Syntax error near..." -**Diagnosis**: Parser doesn't recognize the syntax -**Solution**: Grammar needs to be updated (see [Bug Fixing Guide](../instructions/bug_fixing.guidelines.instructions.md)) - -### Test Fails: "Option 'X' is not valid..." -**Diagnosis**: Validation logic rejects the syntax -**Solution**: See [Validation Fix Guide](../instructions/validation_fix.guidelines.instructions.md) - -### Test Fails: Baseline mismatch -**Diagnosis**: Generated output differs from baseline -**Solution**: Update baseline with actual output or fix generator - -### Full Suite Fails: Other tests break -**Diagnosis**: Your changes affected shared code -**Solution**: Review your changes, create context-specific rules - -## Quick Reference Commands - -```bash -# Step 0: Add debug unit test method first (NO external files) -# Add DebugExactScriptTest method to appropriate test file with exact script embedded - -# Search for syntax in tests -grep -r "KEYWORD" Test/SqlDom/TestScripts/ - -# Search in grammar -grep -r "KEYWORD" SqlScriptDom/Parser/TSql/*.g - -# Build parser -dotnet build SqlScriptDom/Microsoft.SqlServer.TransactSql.ScriptDom.csproj -c Debug - -# Run specific test -dotnet test --filter "TestName" -c Debug - -# Run full suite -dotnet test Test/SqlDom/UTSqlScriptDom.csproj -c Debug - -# Create test files (only for comprehensive testing, not initial verification) -New-Item "Test/SqlDom/TestScripts/MyTest160.sql" -New-Item "Test/SqlDom/Baselines160/MyTest160.sql" -``` - -## Related Guides - -- [debugging_workflow.guidelines.instructions.md](../instructions/debugging_workflow.guidelines.instructions.md) - How to diagnose issues -- [Validation_fix.guidelines.instructions.md](../instructions/validation_fix.guidelines.instructions.md) - Fix validation errors -- [Bug Fixing Guide](../instructions/bug_fixing.guidelines.instructions.md) - Add new grammar rules -- [copilot-instructions.md](../copilot-instructions.md) - Main project documentation +Input: +${input:tsqlScript:Paste the exact T-SQL script to verify} \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..aea81843 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,32 @@ +# AGENTS.md + +This repository keeps its canonical Copilot instruction files in the `.github` folder and its reusable agent skills in `.agents/skills`. + +Before starting work, read `.github/copilot-instructions.md` for repository-wide guidance. + +Then use the relevant topic-specific instruction files in `.github/instructions/`: +- `adding_new_parser.guidelines.instructions.md` +- `bug_fixing.guidelines.instructions.md` +- `database_option.guidelines.instructions.md` +- `debugging_workflow.guidelines.instructions.md` +- `function.guidelines.instructions.md` +- `grammar_validation.guidelines.instructions.md` +- `grammar.guidelines.instructions.md` +- `new_data_types.guidelines.instructions.md` +- `new_index_types.guidelines.instructions.md` +- `parser.guidelines.instructions.md` +- `testing.guidelines.instructions.md` + +When a reusable skill applies, load it from `.agents/skills/`: +- `add-feature/SKILL.md` +- `verify-and-test-tsql-syntax/SKILL.md` + +Version note: +- Treat `TSql180` as the current vNext/latest parser target in agent workflows unless a more specific repo instruction overrides it. + +Selection rule: +- Use only the instruction file or files that match the task. +- If multiple files apply, follow all of them. +- If there is any conflict, treat `.github/copilot-instructions.md` as the repository-wide baseline and then apply the more specific file from `.github/instructions/` for the current task. + +Do not duplicate, restate, or replace the maintained guidance in this file. This file is only a redirect to the instruction and skill sources above. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..7a18d6ba --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,7 @@ +@AGENTS.md + +## Claude Code + +- Treat `AGENTS.md` as the canonical shared instruction source for this repository. +- When a reusable workflow applies, consult the matching skill under `.agents/skills/`. +- Treat `TSql180` as the current vNext/latest parser target for shared agent workflows. \ No newline at end of file From 67f9eab748920894300626b39811106ff94ab20d Mon Sep 17 00:00:00 2001 From: Aasim Khan Date: Mon, 27 Apr 2026 14:18:44 -0700 Subject: [PATCH 26/45] Add support for TRIM function in T-SQL parser and related tests (#202) Co-authored-by: Aasim Khan --- SqlScriptDom/Parser/TSql/TSql140.g | 16 ++++++++ SqlScriptDom/Parser/TSql/TSql150.g | 16 ++++++++ SqlScriptDom/Parser/TSql/TSql160.g | 21 +++++++++++ SqlScriptDom/Parser/TSql/TSql170.g | 21 +++++++++++ SqlScriptDom/Parser/TSql/TSql180.g | 21 +++++++++++ SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 21 +++++++++++ .../Baselines140/TrimFromReturnTests140.sql | 7 ++++ .../Baselines160/TrimFromReturnTests160.sql | 37 +++++++++++++++++++ .../Baselines170/TrimFromReturnTests160.sql | 37 +++++++++++++++++++ .../Baselines180/TrimFromReturnTests160.sql | 37 +++++++++++++++++++ Test/SqlDom/Only140SyntaxTests.cs | 1 + Test/SqlDom/Only160SyntaxTests.cs | 1 + Test/SqlDom/Only170SyntaxTests.cs | 3 +- Test/SqlDom/Only180SyntaxTests.cs | 3 +- Test/SqlDom/ParserErrorsTests.cs | 2 +- .../TestScripts/TrimFromReturnTests140.sql | 7 ++++ .../TestScripts/TrimFromReturnTests160.sql | 31 ++++++++++++++++ 17 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 Test/SqlDom/Baselines140/TrimFromReturnTests140.sql create mode 100644 Test/SqlDom/Baselines160/TrimFromReturnTests160.sql create mode 100644 Test/SqlDom/Baselines170/TrimFromReturnTests160.sql create mode 100644 Test/SqlDom/Baselines180/TrimFromReturnTests160.sql create mode 100644 Test/SqlDom/TestScripts/TrimFromReturnTests140.sql create mode 100644 Test/SqlDom/TestScripts/TrimFromReturnTests160.sql diff --git a/SqlScriptDom/Parser/TSql/TSql140.g b/SqlScriptDom/Parser/TSql/TSql140.g index 31391915..2424bd5c 100644 --- a/SqlScriptDom/Parser/TSql/TSql140.g +++ b/SqlScriptDom/Parser/TSql/TSql140.g @@ -29739,6 +29739,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.IIf) && (LA(2) == LeftParenthesis)}? vResult=iIfCall + | + {NextTokenMatches(CodeGenerationSupporter.Trim) && (LA(2) == LeftParenthesis) && (LA(3) != Star)}? + vResult=trimCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -30230,6 +30233,19 @@ builtInFunctionCall returns [FunctionCall vResult = FragmentFactory.CreateFragme ) ; +trimCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : vIdentifier=nonQuotedIdentifier + { + Match(vIdentifier, CodeGenerationSupporter.Trim); + vResult.FunctionName = vIdentifier; + } + LeftParenthesis + trimBuiltInFunctionCall[vResult] + ; + regularBuiltInFunctionCall [FunctionCall vParent] { ColumnReferenceExpression vColumn; diff --git a/SqlScriptDom/Parser/TSql/TSql150.g b/SqlScriptDom/Parser/TSql/TSql150.g index 35a14f12..ea468dcb 100644 --- a/SqlScriptDom/Parser/TSql/TSql150.g +++ b/SqlScriptDom/Parser/TSql/TSql150.g @@ -30885,6 +30885,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.IIf) && (LA(2) == LeftParenthesis)}? vResult=iIfCall + | + {NextTokenMatches(CodeGenerationSupporter.Trim) && (LA(2) == LeftParenthesis) && (LA(3) != Star)}? + vResult=trimCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -31383,6 +31386,19 @@ builtInFunctionCall returns [FunctionCall vResult = FragmentFactory.CreateFragme ) ; +trimCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : vIdentifier=nonQuotedIdentifier + { + Match(vIdentifier, CodeGenerationSupporter.Trim); + vResult.FunctionName = vIdentifier; + } + LeftParenthesis + trimBuiltInFunctionCall[vResult] + ; + regularBuiltInFunctionCall [FunctionCall vParent] { ColumnReferenceExpression vColumn; diff --git a/SqlScriptDom/Parser/TSql/TSql160.g b/SqlScriptDom/Parser/TSql/TSql160.g index 4d794caa..1fbb91e9 100644 --- a/SqlScriptDom/Parser/TSql/TSql160.g +++ b/SqlScriptDom/Parser/TSql/TSql160.g @@ -31482,6 +31482,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.JsonArray) && (LA(2) == LeftParenthesis)}? vResult=jsonArrayCall + | + {NextTokenMatches(CodeGenerationSupporter.Trim) && (LA(2) == LeftParenthesis) && (LA(3) != Star)}? + vResult=trimCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -32528,6 +32531,24 @@ jsonArrayCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragmen jsonArrayBuiltInFunctionCall[vResult] ; +trimCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : vIdentifier=nonQuotedIdentifier + { + Match(vIdentifier, CodeGenerationSupporter.Trim); + vResult.FunctionName = vIdentifier; + } + LeftParenthesis + ( + {NextTokenMatches(CodeGenerationSupporter.Leading) || NextTokenMatches(CodeGenerationSupporter.Trailing) || NextTokenMatches(CodeGenerationSupporter.Both)}? + trim3ArgsBuiltInFunctionCall[vResult] + | + trimBuiltInFunctionCall[vResult] + ) + ; + coalesceExpression [ExpressionFlags expressionFlags] returns [CoalesceExpression vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vExpression; diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 88ce6606..0fb05149 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -32229,6 +32229,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.JsonArray) && (LA(2) == LeftParenthesis)}? vResult=jsonArrayCall + | + {NextTokenMatches(CodeGenerationSupporter.Trim) && (LA(2) == LeftParenthesis) && (LA(3) != Star)}? + vResult=trimCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -33656,6 +33659,24 @@ jsonArrayCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragmen jsonArrayBuiltInFunctionCall[vResult] ; +trimCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : vIdentifier=nonQuotedIdentifier + { + Match(vIdentifier, CodeGenerationSupporter.Trim); + vResult.FunctionName = vIdentifier; + } + LeftParenthesis + ( + {NextTokenMatches(CodeGenerationSupporter.Leading) || NextTokenMatches(CodeGenerationSupporter.Trailing) || NextTokenMatches(CodeGenerationSupporter.Both)}? + trim3ArgsBuiltInFunctionCall[vResult] + | + trimBuiltInFunctionCall[vResult] + ) + ; + coalesceExpression [ExpressionFlags expressionFlags] returns [CoalesceExpression vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vExpression; diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index 19e66add..4af433a5 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -32229,6 +32229,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.JsonArray) && (LA(2) == LeftParenthesis)}? vResult=jsonArrayCall + | + {NextTokenMatches(CodeGenerationSupporter.Trim) && (LA(2) == LeftParenthesis) && (LA(3) != Star)}? + vResult=trimCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -33656,6 +33659,24 @@ jsonArrayCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragmen jsonArrayBuiltInFunctionCall[vResult] ; +trimCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : vIdentifier=nonQuotedIdentifier + { + Match(vIdentifier, CodeGenerationSupporter.Trim); + vResult.FunctionName = vIdentifier; + } + LeftParenthesis + ( + {NextTokenMatches(CodeGenerationSupporter.Leading) || NextTokenMatches(CodeGenerationSupporter.Trailing) || NextTokenMatches(CodeGenerationSupporter.Both)}? + trim3ArgsBuiltInFunctionCall[vResult] + | + trimBuiltInFunctionCall[vResult] + ) + ; + coalesceExpression [ExpressionFlags expressionFlags] returns [CoalesceExpression vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vExpression; diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index 21fd33d8..21590b64 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -31467,6 +31467,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.JsonArray) && (LA(2) == LeftParenthesis)}? vResult=jsonArrayCall + | + {NextTokenMatches(CodeGenerationSupporter.Trim) && (LA(2) == LeftParenthesis) && (LA(3) != Star)}? + vResult=trimCall | {NextTokenMatches(CodeGenerationSupporter.AIAnalyzeSentiment) && (LA(2) == LeftParenthesis)}? vResult=aiAnalyzeSentimentFunctionCall @@ -32694,6 +32697,24 @@ jsonArrayCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragmen jsonArrayBuiltInFunctionCall[vResult] ; +trimCall returns [FunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; +} + : vIdentifier=nonQuotedIdentifier + { + Match(vIdentifier, CodeGenerationSupporter.Trim); + vResult.FunctionName = vIdentifier; + } + LeftParenthesis + ( + {NextTokenMatches(CodeGenerationSupporter.Leading) || NextTokenMatches(CodeGenerationSupporter.Trailing) || NextTokenMatches(CodeGenerationSupporter.Both)}? + trim3ArgsBuiltInFunctionCall[vResult] + | + trimBuiltInFunctionCall[vResult] + ) + ; + coalesceExpression [ExpressionFlags expressionFlags] returns [CoalesceExpression vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vExpression; diff --git a/Test/SqlDom/Baselines140/TrimFromReturnTests140.sql b/Test/SqlDom/Baselines140/TrimFromReturnTests140.sql new file mode 100644 index 00000000..d2cdb107 --- /dev/null +++ b/Test/SqlDom/Baselines140/TrimFromReturnTests140.sql @@ -0,0 +1,7 @@ +CREATE FUNCTION dbo.TrimTest +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM('x' FROM @str); +END diff --git a/Test/SqlDom/Baselines160/TrimFromReturnTests160.sql b/Test/SqlDom/Baselines160/TrimFromReturnTests160.sql new file mode 100644 index 00000000..6a31f076 --- /dev/null +++ b/Test/SqlDom/Baselines160/TrimFromReturnTests160.sql @@ -0,0 +1,37 @@ +CREATE FUNCTION dbo.TrimUnicodeSpace +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM(NCHAR(12288) FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimLeadingX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( LEADING 'x' FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimTrailingX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( TRAILING 'x' FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimBothX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( BOTH 'x' FROM @str); +END diff --git a/Test/SqlDom/Baselines170/TrimFromReturnTests160.sql b/Test/SqlDom/Baselines170/TrimFromReturnTests160.sql new file mode 100644 index 00000000..6a31f076 --- /dev/null +++ b/Test/SqlDom/Baselines170/TrimFromReturnTests160.sql @@ -0,0 +1,37 @@ +CREATE FUNCTION dbo.TrimUnicodeSpace +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM(NCHAR(12288) FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimLeadingX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( LEADING 'x' FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimTrailingX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( TRAILING 'x' FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimBothX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( BOTH 'x' FROM @str); +END diff --git a/Test/SqlDom/Baselines180/TrimFromReturnTests160.sql b/Test/SqlDom/Baselines180/TrimFromReturnTests160.sql new file mode 100644 index 00000000..6a31f076 --- /dev/null +++ b/Test/SqlDom/Baselines180/TrimFromReturnTests160.sql @@ -0,0 +1,37 @@ +CREATE FUNCTION dbo.TrimUnicodeSpace +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM(NCHAR(12288) FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimLeadingX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( LEADING 'x' FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimTrailingX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( TRAILING 'x' FROM @str); +END + + +GO +CREATE FUNCTION dbo.TrimBothX +(@str NVARCHAR (MAX)) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN TRIM( BOTH 'x' FROM @str); +END diff --git a/Test/SqlDom/Only140SyntaxTests.cs b/Test/SqlDom/Only140SyntaxTests.cs index b24a14ad..d782b3b6 100644 --- a/Test/SqlDom/Only140SyntaxTests.cs +++ b/Test/SqlDom/Only140SyntaxTests.cs @@ -22,6 +22,7 @@ public partial class SqlDomTests new ParserTest140("OptimizerHintsTests140.sql", 6, 6, 6, 6, 6, 0), new ParserTest140("WithinGroupTests140.sql", 4, 4, 4, 2, 2, 0), new ParserTest140("TrimBuiltInTest140.sql", 10, 2, 10, 10, 10, 10), + new ParserTest140("TrimFromReturnTests140.sql"), new ParserTest140("AlterTableAlterColumnStatementTests140.sql", 14, 14, 14, 14, 14, 12), new ParserTest140("BulkInsertStatementTests140.sql", 12, 12, 12, 12, 12, 12), new ParserTest140("OpenRowsetBulkStatementTests140.sql", 9, 9, 9, 9, 9, 9), diff --git a/Test/SqlDom/Only160SyntaxTests.cs b/Test/SqlDom/Only160SyntaxTests.cs index 552152b3..ad033d21 100644 --- a/Test/SqlDom/Only160SyntaxTests.cs +++ b/Test/SqlDom/Only160SyntaxTests.cs @@ -41,6 +41,7 @@ public partial class SqlDomTests new ParserTest160("AlterFunctionJsonObjectTests160.sql", nErrors80: 1, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1), new ParserTest160("ComplexJsonObjectFunctionTests160.sql"), new ParserTest160("TestTrimReturn160.sql", nErrors80: 1, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), + new ParserTest160("TrimFromReturnTests160.sql"), new ParserTest160("TestJsonArrayReturn160.sql", nErrors80: 1, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160(scriptFilename: "IgnoreRespectNullsSyntaxTests160.sql", nErrors80: 12, nErrors90: 8, nErrors100: 8, nErrors110: 8, nErrors120: 8, nErrors130: 8, nErrors140: 8, nErrors150: 8), new ParserTest160(scriptFilename: "FuzzyStringMatchingTests160.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index aca9deec..3dbed244 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -24,6 +24,7 @@ public partial class SqlDomTests new ParserTest170("JsonArrayAggOrderBy170.sql", nErrors80: 10, nErrors90: 9, nErrors100: 9, nErrors110: 9, nErrors120: 9, nErrors130: 9, nErrors140: 9, nErrors150: 9, nErrors160: 9), new ParserTest170("JsonObjectAggOverClause170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("ComplexJsonObjectFunctionTests170.sql"), + new ParserTest170("TrimFromReturnTests160.sql"), new ParserTest170("AiGenerateEmbeddingsTests170.sql", nErrors80: 14, nErrors90: 11, nErrors100: 11, nErrors110: 11, nErrors120: 11, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11), new ParserTest170("CreateExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("AlterExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5), @@ -392,4 +393,4 @@ public void TSql100SyntaxIn170ParserTest() } } } -} \ No newline at end of file +} diff --git a/Test/SqlDom/Only180SyntaxTests.cs b/Test/SqlDom/Only180SyntaxTests.cs index 6fdad70b..b68b9ba5 100644 --- a/Test/SqlDom/Only180SyntaxTests.cs +++ b/Test/SqlDom/Only180SyntaxTests.cs @@ -12,7 +12,8 @@ public partial class SqlDomTests // Note: These filenames are case sensitive, make sure they match the checked-in file exactly private static readonly ParserTest[] Only180TestInfos = { - new ParserTest180("AutomaticIndexCompactionTests180.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2) + new ParserTest180("AutomaticIndexCompactionTests180.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2), + new ParserTest180("TrimFromReturnTests160.sql") }; private static readonly ParserTest[] SqlAzure180_TestInfos = diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 54e2322b..5c88f7cc 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -456,7 +456,7 @@ public void JsonObjectSyntaxNegativeTest() // Cannot use key:value pair with another non JSON_OBJECT Syntax ParserTestUtils.ErrorTest160("SELECT TRIM('name':'value','type':1)", - new ParserErrorInfo(18, "SQL46010", ":")); + new ParserErrorInfo(12, "SQL46010", "'name'")); // Cannot use Absent On Null with another non JSON_OBJECT Syntax ParserTestUtils.ErrorTest160("SELECT TRIM('name' ABSENT ON NULL)", diff --git a/Test/SqlDom/TestScripts/TrimFromReturnTests140.sql b/Test/SqlDom/TestScripts/TrimFromReturnTests140.sql new file mode 100644 index 00000000..8678e36b --- /dev/null +++ b/Test/SqlDom/TestScripts/TrimFromReturnTests140.sql @@ -0,0 +1,7 @@ +CREATE FUNCTION dbo.TrimTest(@str NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN TRIM('x' FROM @str); +END; +GO diff --git a/Test/SqlDom/TestScripts/TrimFromReturnTests160.sql b/Test/SqlDom/TestScripts/TrimFromReturnTests160.sql new file mode 100644 index 00000000..7a4c0b9e --- /dev/null +++ b/Test/SqlDom/TestScripts/TrimFromReturnTests160.sql @@ -0,0 +1,31 @@ +CREATE FUNCTION dbo.TrimUnicodeSpace(@str NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN TRIM(NCHAR(12288) FROM @str); +END; +GO + +CREATE FUNCTION dbo.TrimLeadingX(@str NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN TRIM(LEADING 'x' FROM @str); +END; +GO + +CREATE FUNCTION dbo.TrimTrailingX(@str NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN TRIM(TRAILING 'x' FROM @str); +END; +GO + +CREATE FUNCTION dbo.TrimBothX(@str NVARCHAR(MAX)) +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN TRIM(BOTH 'x' FROM @str); +END; +GO From 6e95673833622a335fbb34735d63d851544fa09e Mon Sep 17 00:00:00 2001 From: Aasim Khan Date: Mon, 27 Apr 2026 17:50:49 -0700 Subject: [PATCH 27/45] Fix datepart argument parsing in date functions with AGENTS files (#201) * Add support for DATEADD, DATEDIFF, and related functions; normalize parameters in function calls * Add comprehensive tests for DATEPART and related functions; include various arities and edge cases Co-authored-by: Copilot --------- Co-authored-by: Aasim Khan Co-authored-by: Copilot --- .../Parser/TSql/CodeGenerationSupporter.cs | 7 +++ SqlScriptDom/Parser/TSql/TSql100.g | 3 + SqlScriptDom/Parser/TSql/TSql110.g | 3 + SqlScriptDom/Parser/TSql/TSql120.g | 3 + SqlScriptDom/Parser/TSql/TSql130.g | 3 + SqlScriptDom/Parser/TSql/TSql140.g | 3 + SqlScriptDom/Parser/TSql/TSql150.g | 3 + SqlScriptDom/Parser/TSql/TSql160.g | 3 + SqlScriptDom/Parser/TSql/TSql170.g | 3 + SqlScriptDom/Parser/TSql/TSql180.g | 3 + SqlScriptDom/Parser/TSql/TSql80.g | 3 + .../Parser/TSql/TSql80ParserBaseInternal.cs | 47 ++++++++++++++- SqlScriptDom/Parser/TSql/TSql90.g | 3 + SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 3 + .../Baselines160/DatePartFunctionTests160.sql | 55 ++++++++++++++++++ Test/SqlDom/Only160SyntaxTests.cs | 49 ++++++++++++++++ .../TestScripts/DatePartFunctionTests160.sql | 58 +++++++++++++++++++ 17 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 Test/SqlDom/Baselines160/DatePartFunctionTests160.sql create mode 100644 Test/SqlDom/TestScripts/DatePartFunctionTests160.sql diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 0ea67317..a7e52ae0 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -293,13 +293,20 @@ internal static class CodeGenerationSupporter internal const string DataRetention = "DATA_RETENTION"; internal const string DataSource = "DATA_SOURCE"; internal const string Date = "DATE"; + internal const string DateAdd = "DATEADD"; + internal const string DateBucket = "DATE_BUCKET"; internal const string DateCorrelationOptimization = "DATE_CORRELATION_OPTIMIZATION"; + internal const string DateDiff = "DATEDIFF"; + internal const string DateDiffBig = "DATEDIFF_BIG"; internal const string DateFirst = "DATEFIRST"; internal const string DateFormat = "DATEFORMAT"; internal const string DateFormat2 = "DATE_FORMAT"; + internal const string DateName = "DATENAME"; + internal const string DatePart = "DATEPART"; internal const string DateTime = "DATETIME"; internal const string DateTime2 = "DATETIME2"; internal const string DateTimeOffset = "DATETIMEOFFSET"; + internal const string DateTrunc = "DATETRUNC"; internal const string Deterministic = "DETERMINISTIC"; internal const string DboOnly = "DBO_ONLY"; internal const string DbChaining = "DB_CHAINING"; diff --git a/SqlScriptDom/Parser/TSql/TSql100.g b/SqlScriptDom/Parser/TSql/TSql100.g index c0cbb0e5..c17c2f9a 100644 --- a/SqlScriptDom/Parser/TSql/TSql100.g +++ b/SqlScriptDom/Parser/TSql/TSql100.g @@ -20874,6 +20874,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql110.g b/SqlScriptDom/Parser/TSql/TSql110.g index 508e6b71..a4974e16 100644 --- a/SqlScriptDom/Parser/TSql/TSql110.g +++ b/SqlScriptDom/Parser/TSql/TSql110.g @@ -23849,6 +23849,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql120.g b/SqlScriptDom/Parser/TSql/TSql120.g index 78126da0..ca52e509 100644 --- a/SqlScriptDom/Parser/TSql/TSql120.g +++ b/SqlScriptDom/Parser/TSql/TSql120.g @@ -24598,6 +24598,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql130.g b/SqlScriptDom/Parser/TSql/TSql130.g index a51aeb9d..1212d2ba 100644 --- a/SqlScriptDom/Parser/TSql/TSql130.g +++ b/SqlScriptDom/Parser/TSql/TSql130.g @@ -29420,6 +29420,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql140.g b/SqlScriptDom/Parser/TSql/TSql140.g index 2424bd5c..65ccc869 100644 --- a/SqlScriptDom/Parser/TSql/TSql140.g +++ b/SqlScriptDom/Parser/TSql/TSql140.g @@ -30253,6 +30253,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql150.g b/SqlScriptDom/Parser/TSql/TSql150.g index ea468dcb..2b013325 100644 --- a/SqlScriptDom/Parser/TSql/TSql150.g +++ b/SqlScriptDom/Parser/TSql/TSql150.g @@ -31406,6 +31406,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql160.g b/SqlScriptDom/Parser/TSql/TSql160.g index 1fbb91e9..ed4fe5f9 100644 --- a/SqlScriptDom/Parser/TSql/TSql160.g +++ b/SqlScriptDom/Parser/TSql/TSql160.g @@ -32218,6 +32218,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 0fb05149..28673c8d 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -33346,6 +33346,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index 4af433a5..59ed7b85 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -33346,6 +33346,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql80.g b/SqlScriptDom/Parser/TSql/TSql80.g index b97ddc0d..87fc761e 100644 --- a/SqlScriptDom/Parser/TSql/TSql80.g +++ b/SqlScriptDom/Parser/TSql/TSql80.g @@ -9103,6 +9103,9 @@ identifierBuiltInFunctionCallDefaultParams [FunctionCall vParent] } : expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs index 4f474299..5607c181 100644 --- a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs @@ -1979,6 +1979,51 @@ protected void PutIdentifiersIntoFunctionCall(FunctionCall functionCall, MultiPa } } + protected void NormalizeDatePartFunctionFirstParameter(FunctionCall functionCall) + { + if (functionCall == null || + functionCall.FunctionName == null || + String.IsNullOrEmpty(functionCall.FunctionName.Value) || + functionCall.Parameters == null || + functionCall.Parameters.Count == 0 || + !IsDatePartFunction(functionCall.FunctionName.Value)) + { + return; + } + + ColumnReferenceExpression columnReference = functionCall.Parameters[0] as ColumnReferenceExpression; + if (columnReference == null || + columnReference.MultiPartIdentifier == null || + columnReference.MultiPartIdentifier.Count != 1) + { + return; + } + + Identifier identifier = columnReference.MultiPartIdentifier[0]; + IdentifierLiteral literal = FragmentFactory.CreateFragment(); + literal.Value = identifier.Value; + literal.QuoteType = identifier.QuoteType; + literal.UpdateTokenInfo(columnReference); + functionCall.Parameters[0] = literal; + } + + private static bool IsDatePartFunction(string functionName) + { + switch (functionName.ToUpper(CultureInfo.InvariantCulture)) + { + case CodeGenerationSupporter.DateAdd: + case CodeGenerationSupporter.DateBucket: + case CodeGenerationSupporter.DateDiff: + case CodeGenerationSupporter.DateDiffBig: + case CodeGenerationSupporter.DateName: + case CodeGenerationSupporter.DatePart: + case CodeGenerationSupporter.DateTrunc: + return true; + default: + return false; + } + } + protected void VerifyColumnDataType(ColumnDefinition column) { // If the scalarDataType is not parsed, the ColumnIdentifier has to be a timestamp. @@ -2426,4 +2471,4 @@ protected static TSqlParseErrorException GetUnexpectedTokenErrorException(Identi #endregion } -} \ No newline at end of file +} diff --git a/SqlScriptDom/Parser/TSql/TSql90.g b/SqlScriptDom/Parser/TSql/TSql90.g index 77f27a1f..9b6d0ada 100644 --- a/SqlScriptDom/Parser/TSql/TSql90.g +++ b/SqlScriptDom/Parser/TSql/TSql90.g @@ -16550,6 +16550,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index 21590b64..e4a7f24d 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -32384,6 +32384,9 @@ regularBuiltInFunctionCall [FunctionCall vParent] : ( expressionList[vParent, vParent.Parameters] + { + NormalizeDatePartFunctionFirstParameter(vParent); + } | vColumn=starColumnReferenceExpression { diff --git a/Test/SqlDom/Baselines160/DatePartFunctionTests160.sql b/Test/SqlDom/Baselines160/DatePartFunctionTests160.sql new file mode 100644 index 00000000..fe22fafd --- /dev/null +++ b/Test/SqlDom/Baselines160/DatePartFunctionTests160.sql @@ -0,0 +1,55 @@ +SELECT DATEADD(day, 1, OrderDate) AS AddedDate, + DATEDIFF(mm, StartDate, EndDate) AS MonthDifference, + DATEDIFF_BIG(second, StartDate, EndDate) AS BigSecondDifference, + DATENAME(month, OrderDate) AS MonthName, + DATEPART(wk, OrderDate) AS WeekPart, + DATE_BUCKET(WEEK, 2, OrderDate) AS WeekBucket, + DATE_BUCKET(DAY, 7, OrderDate, OriginDate) AS OriginDayBucket, + DATETRUNC(year, OrderDate) AS YearTruncation +FROM dbo.Orders; + +SELECT DATEPART(year, OrderDate) AS YearPart, + DATEPART(yy, OrderDate) AS YearShortPart, + DATEPART(yyyy, OrderDate) AS YearLongPart, + DATEPART(quarter, OrderDate) AS QuarterPart, + DATEPART(qq, OrderDate) AS QuarterShortPart, + DATEPART(q, OrderDate) AS QuarterSinglePart, + DATEPART(month, OrderDate) AS MonthPart, + DATEPART(mm, OrderDate) AS MonthShortPart, + DATEPART(m, OrderDate) AS MonthSinglePart, + DATEPART(dayofyear, OrderDate) AS DayOfYearPart, + DATEPART(dy, OrderDate) AS DayOfYearShortPart, + DATEPART(y, OrderDate) AS DayOfYearSinglePart, + DATEPART(day, OrderDate) AS DayPart, + DATEPART(dd, OrderDate) AS DayShortPart, + DATEPART(d, OrderDate) AS DaySinglePart, + DATEPART(week, OrderDate) AS WeekPart, + DATEPART(wk, OrderDate) AS WeekShortPart, + DATEPART(ww, OrderDate) AS WeekAltPart, + DATEPART(weekday, OrderDate) AS WeekdayPart, + DATEPART(dw, OrderDate) AS WeekdayShortPart, + DATEPART(w, OrderDate) AS WeekdaySinglePart, + DATEPART(hour, OrderDate) AS HourPart, + DATEPART(hh, OrderDate) AS HourShortPart, + DATEPART(minute, OrderDate) AS MinutePart, + DATEPART(mi, OrderDate) AS MinuteShortPart, + DATEPART(n, OrderDate) AS MinuteSinglePart, + DATEPART(second, OrderDate) AS SecondPart, + DATEPART(ss, OrderDate) AS SecondShortPart, + DATEPART(s, OrderDate) AS SecondSinglePart, + DATEPART(millisecond, OrderDate) AS MillisecondPart, + DATEPART(ms, OrderDate) AS MillisecondShortPart, + DATEPART(microsecond, OrderDate) AS MicrosecondPart, + DATEPART(mcs, OrderDate) AS MicrosecondShortPart, + DATEPART(nanosecond, OrderDate) AS NanosecondPart, + DATEPART(ns, OrderDate) AS NanosecondShortPart, + DATEPART(tzoffset, OrderDate) AS TimeZoneOffsetPart, + DATEPART(tz, OrderDate) AS TimeZoneOffsetShortPart, + DATEPART(iso_week, OrderDate) AS IsoWeekPart, + DATEPART(isowk, OrderDate) AS IsoWeekShortPart, + DATEPART(isoww, OrderDate) AS IsoWeekAltPart +FROM dbo.Orders; + +SELECT ABS(Amount) AS AbsoluteAmount, + UPPER(CustomerName) AS UpperCustomerName +FROM dbo.Orders; diff --git a/Test/SqlDom/Only160SyntaxTests.cs b/Test/SqlDom/Only160SyntaxTests.cs index ad033d21..966e51d9 100644 --- a/Test/SqlDom/Only160SyntaxTests.cs +++ b/Test/SqlDom/Only160SyntaxTests.cs @@ -36,6 +36,7 @@ public partial class SqlDomTests new ParserTest160("BitManipulationFunctionTests160.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160("ShiftOperatorTests160.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 3, nErrors130: 3, nErrors140: 3, nErrors150: 3), new ParserTest160("BuiltInFunctionTests160.sql", nErrors80: 1, nErrors90: 1, nErrors100: 2, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), + new ParserTest160("DatePartFunctionTests160.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160("TrimFunctionTests160.sql", nErrors80: 7, nErrors90: 7, nErrors100: 7, nErrors110: 7, nErrors120: 7, nErrors130: 7, nErrors140: 4, nErrors150: 4), new ParserTest160("JsonFunctionTests160.sql", nErrors80: 9, nErrors90: 8, nErrors100: 14, nErrors110: 14, nErrors120: 14, nErrors130: 14, nErrors140: 14, nErrors150: 14), new ParserTest160("AlterFunctionJsonObjectTests160.sql", nErrors80: 1, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1), @@ -155,6 +156,54 @@ public void TSql160Azure_SyntaxIn160ParserTest() } } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void DatePartFunctionParametersAreIdentifierLiteralsTest() + { + TSql160Parser parser = new TSql160Parser(true); + + VerifyDatePartParameter(parser, "SELECT DATEDIFF(mm, ColA, ColB) FROM my_table;", "mm", 3); + VerifyDatePartParameter(parser, "SELECT DATEADD(day, 1, ColA) FROM my_table;", "day", 3); + VerifyDatePartParameter(parser, "SELECT DATEDIFF_BIG(second, ColA, ColB) FROM my_table;", "second", 3); + VerifyDatePartParameter(parser, "SELECT DATENAME(month, ColA) FROM my_table;", "month", 2); + VerifyDatePartParameter(parser, "SELECT DATEPART(wk, ColA) FROM my_table;", "wk", 2); + VerifyDatePartParameter(parser, "SELECT DATE_BUCKET(WEEK, 10, ColA) FROM my_table;", "WEEK", 3); + VerifyDatePartParameter(parser, "SELECT DATE_BUCKET(DAY, 10, ColA, ColB) FROM my_table;", "DAY", 4); + VerifyDatePartParameter(parser, "SELECT DATETRUNC(year, ColA) FROM my_table;", "year", 2); + + VerifyNonDatePartParameter(parser, "SELECT ABS(ColA) FROM my_table;"); + VerifyNonDatePartParameter(parser, "SELECT UPPER(ColA) FROM my_table;"); + } + + private static void VerifyDatePartParameter(TSqlParser parser, string sql, string expectedDatePart, int expectedParameterCount) + { + FunctionCall functionCall = GetFirstSelectFunctionCall(parser, sql); + + Assert.AreEqual(expectedParameterCount, functionCall.Parameters.Count, sql); + Assert.IsInstanceOfType(functionCall.Parameters[0], typeof(IdentifierLiteral), sql); + Assert.AreEqual(expectedDatePart, ((IdentifierLiteral)functionCall.Parameters[0]).Value, sql); + } + + private static void VerifyNonDatePartParameter(TSqlParser parser, string sql) + { + FunctionCall functionCall = GetFirstSelectFunctionCall(parser, sql); + + Assert.IsInstanceOfType(functionCall.Parameters[0], typeof(ColumnReferenceExpression), sql); + } + + private static FunctionCall GetFirstSelectFunctionCall(TSqlParser parser, string sql) + { + TSqlFragment fragment = parser.Parse(new System.IO.StringReader(sql), out System.Collections.Generic.IList errors); + + Assert.AreEqual(0, errors.Count, sql); + TSqlScript script = (TSqlScript)fragment; + SelectStatement select = (SelectStatement)script.Batches[0].Statements[0]; + QuerySpecification query = (QuerySpecification)select.QueryExpression; + SelectScalarExpression selectExpression = (SelectScalarExpression)query.SelectElements[0]; + return (FunctionCall)selectExpression.Expression; + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] diff --git a/Test/SqlDom/TestScripts/DatePartFunctionTests160.sql b/Test/SqlDom/TestScripts/DatePartFunctionTests160.sql new file mode 100644 index 00000000..36a00274 --- /dev/null +++ b/Test/SqlDom/TestScripts/DatePartFunctionTests160.sql @@ -0,0 +1,58 @@ +-- Datepart functions with each supported arity. +SELECT DATEADD(day, 1, OrderDate) AS AddedDate, + DATEDIFF(mm, StartDate, EndDate) AS MonthDifference, + DATEDIFF_BIG(second, StartDate, EndDate) AS BigSecondDifference, + DATENAME(month, OrderDate) AS MonthName, + DATEPART(wk, OrderDate) AS WeekPart, + DATE_BUCKET(WEEK, 2, OrderDate) AS WeekBucket, + DATE_BUCKET(DAY, 7, OrderDate, OriginDate) AS OriginDayBucket, + DATETRUNC(year, OrderDate) AS YearTruncation +FROM dbo.Orders; + +-- Documented DATEPART datepart names and abbreviations should not round-trip as column references. +SELECT DATEPART(year, OrderDate) AS YearPart, + DATEPART(yy, OrderDate) AS YearShortPart, + DATEPART(yyyy, OrderDate) AS YearLongPart, + DATEPART(quarter, OrderDate) AS QuarterPart, + DATEPART(qq, OrderDate) AS QuarterShortPart, + DATEPART(q, OrderDate) AS QuarterSinglePart, + DATEPART(month, OrderDate) AS MonthPart, + DATEPART(mm, OrderDate) AS MonthShortPart, + DATEPART(m, OrderDate) AS MonthSinglePart, + DATEPART(dayofyear, OrderDate) AS DayOfYearPart, + DATEPART(dy, OrderDate) AS DayOfYearShortPart, + DATEPART(y, OrderDate) AS DayOfYearSinglePart, + DATEPART(day, OrderDate) AS DayPart, + DATEPART(dd, OrderDate) AS DayShortPart, + DATEPART(d, OrderDate) AS DaySinglePart, + DATEPART(week, OrderDate) AS WeekPart, + DATEPART(wk, OrderDate) AS WeekShortPart, + DATEPART(ww, OrderDate) AS WeekAltPart, + DATEPART(weekday, OrderDate) AS WeekdayPart, + DATEPART(dw, OrderDate) AS WeekdayShortPart, + DATEPART(w, OrderDate) AS WeekdaySinglePart, + DATEPART(hour, OrderDate) AS HourPart, + DATEPART(hh, OrderDate) AS HourShortPart, + DATEPART(minute, OrderDate) AS MinutePart, + DATEPART(mi, OrderDate) AS MinuteShortPart, + DATEPART(n, OrderDate) AS MinuteSinglePart, + DATEPART(second, OrderDate) AS SecondPart, + DATEPART(ss, OrderDate) AS SecondShortPart, + DATEPART(s, OrderDate) AS SecondSinglePart, + DATEPART(millisecond, OrderDate) AS MillisecondPart, + DATEPART(ms, OrderDate) AS MillisecondShortPart, + DATEPART(microsecond, OrderDate) AS MicrosecondPart, + DATEPART(mcs, OrderDate) AS MicrosecondShortPart, + DATEPART(nanosecond, OrderDate) AS NanosecondPart, + DATEPART(ns, OrderDate) AS NanosecondShortPart, + DATEPART(tzoffset, OrderDate) AS TimeZoneOffsetPart, + DATEPART(tz, OrderDate) AS TimeZoneOffsetShortPart, + DATEPART(iso_week, OrderDate) AS IsoWeekPart, + DATEPART(isowk, OrderDate) AS IsoWeekShortPart, + DATEPART(isoww, OrderDate) AS IsoWeekAltPart +FROM dbo.Orders; + +-- Non-datepart built-ins still parse and generate through the regular function path. +SELECT ABS(Amount) AS AbsoluteAmount, + UPPER(CustomerName) AS UpperCustomerName +FROM dbo.Orders; From b3173816ce5ed9753ecaf08a2ec63836a513f2e3 Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Fri, 1 May 2026 12:53:13 -0700 Subject: [PATCH 28/45] Sync repos: Release 180.18.1 (#204) * Merged PR 2053371: [SECURITY] Bump dotnet-sdk from 8.0.419 to 8.0.420 * Merged PR 2040726: Fix invalid OVER clause parsing - reject OVER([col]) syntax # Fix invalid OVER clause parsing - reject OVER([col]) syntax ## Summary Fixed a parser bug where invalid OVER clause syntax like `COUNT(*) OVER([col])` was incorrectly accepted. The parser now properly rejects OVER clauses that contain only an identifier in parentheses without PARTITION BY or ORDER BY clauses. ## Problem The parser was accepting invalid syntax such as: ```sql SELECT COUNT(*) OVER([col]) FROM t1 SELECT SUM(Amount) OVER(MyColumn) FROM t1 ``` This is invalid because an OVER clause with parentheses must contain one of: - `PARTITION BY` clause - `ORDER BY` clause - Window frame clause - Or be empty: `OVER()` Valid window name references (introduced in SQL Server 2022) must be written WITHOUT parentheses: ```sql SELECT SUM(c1) OVER Win1 FROM t1 WINDOW Win1 AS (PARTITION BY c1) ``` Additionally, partial window specifications CAN include a window name inside parentheses, but ONLY when combined with other clauses: ```sql SELECT SUM(c1) OVER (Win1 ORDER BY c2) FROM t1 WINDOW Win1 AS (PARTITION BY c1) ``` ## Root Cause In SQL Server 2022 (TSql160), support was added for the WINDOW clause feature, which allows referencing named windows. The grammar rule `overClauseBeginning` was modified to accept an optional identifier inside parentheses to support partial window specifications like `OVER (Win1 PARTITION BY ...)`. However, the rule `overClauseNoOrderBy` (used by aggregate functions like COUNT, SUM, AVG) was still using `overClauseBeginning`, which meant it would accept `OVER(identifier)` and interpret the identifier as a window name, even though no other clauses were present. This resulted in invalid syntax being accepted. ## Solution Created a new grammar rule `overClauseBeginningNoWindowName` that does not allow window name identifiers inside parentheses. Modified `overClauseNoOrderBy` to use this new rule instead of `overClauseBeginning`. The new rule uses explicit alternatives instead of an optional clause to ensure ANTLR properly rejects identifiers that aren't followed by the `BY` keyword: ```antlr overClauseBeginningNoWindowName: OVER LeftParenthesis ( Identifier { Match("PARTITION") } BY expressionList | /* empty - allow OVER() with no PARTITION BY */ ) ``` This ensures that when parsing `OVER([col])`, the parser will: 1. Try to match the PARTITION BY alternative 2. See the identifier but realize it's not followed by BY 3. Try the empty alternative 4. Fail because `[col]` is present when nothing was expected 5. Generate an error ## Files Modified - `SqlScriptDom/Parser/TSql/TSql160.g` - Added `overClauseBeginningNoWindowName` rule and updated `overClauseNoOrderBy` - `SqlScriptDom/Parser/TSql/TSql170.g` - Same changes as TSql160.g - `SqlScriptDom/Parser/TSql/TSql180.g` - Same changes as TSql180.g - `Test/SqlDom/ParserErrorsTests.cs` - Added `InvalidOverClauseNegative... * Merged PR 2072841: Adding release notes for 180.18.1 Adding release notes for 180.18.1 ---- #### AI description (iteration 1) #### PR Classification Documentation update adding release notes for version 180.18.1 of Microsoft.SqlServer.TransactSql.ScriptDom. #### PR Summary This pull request adds comprehensive release notes for version 180.18.1, documenting bug fixes, dependency updates, and changes to the SQL script generator. - `/release-notes/180/180.18.1.md`: Documents platform support for .NET Framework 4.7.2, .NET 8, and .NET Standard 2.0+ - `/release-notes/180/180.18.1.md`: Lists five parser bug fixes including TRIM clause parsing, DATEADD/DATEDIFF/DATEPART function argument handling, and OVER clause validation - `/release-notes/180/180.18.1.md`: Notes .NET SDK update to version 8.0.420 and script generator improvement for semicolon placement before trailing comments --------- Co-authored-by: Dependabot Co-authored-by: GitHub Copilot --- SqlScriptDom/Parser/TSql/TSql160.g | 26 +++++++++++++- SqlScriptDom/Parser/TSql/TSql170.g | 26 +++++++++++++- SqlScriptDom/Parser/TSql/TSql180.g | 26 +++++++++++++- .../Baselines160/WindowClauseTests160.sql | 14 +++++++- Test/SqlDom/Only160SyntaxTests.cs | 2 +- Test/SqlDom/ParserErrorsTests.cs | 35 +++++++++++++++++++ .../TestScripts/WindowClauseTests160.sql | 10 ++++++ global.json | 2 +- release-notes/180/180.18.1.md | 31 ++++++++++++++++ 9 files changed, 166 insertions(+), 6 deletions(-) create mode 100644 release-notes/180/180.18.1.md diff --git a/SqlScriptDom/Parser/TSql/TSql160.g b/SqlScriptDom/Parser/TSql/TSql160.g index ed4fe5f9..c45d6ffb 100644 --- a/SqlScriptDom/Parser/TSql/TSql160.g +++ b/SqlScriptDom/Parser/TSql/TSql160.g @@ -31967,6 +31967,11 @@ overClause returns [OverClause vResult] )? tRParen:RightParenthesis { + // Window name inside parentheses requires at least one clause (PARTITION BY, ORDER BY, or window frame) + if (vResult.WindowName != null && vResult.Partitions.Count == 0 && vResult.OrderByClause == null && vResult.WindowFrameClause == null) + { + ThrowParseErrorException("SQL46010", tRParen, TSqlParserResource.SQL46010Message, vResult.WindowName.Value); + } UpdateTokenInfo(vResult,tRParen); } | vResult = overClauseWithWindow @@ -31989,7 +31994,7 @@ overClauseWithWindow returns [OverClause vResult = FragmentFactory.CreateFragmen overClauseNoOrderBy returns [OverClause vResult] : - vResult = overClauseBeginning + vResult = overClauseBeginningNoWindowName tRParen:RightParenthesis { UpdateTokenInfo(vResult,tRParen); @@ -32021,6 +32026,25 @@ overClauseBeginning returns [OverClause vResult = FragmentFactory.CreateFragment )? ; +overClauseBeginningNoWindowName returns [OverClause vResult = FragmentFactory.CreateFragment()] + : + tOver:Over + { + UpdateTokenInfo(vResult,tOver); + } + LeftParenthesis + ( + (Identifier By) => + tPartition:Identifier + { + Match(tPartition, CodeGenerationSupporter.Partition); + } + By expressionList[vResult, vResult.Partitions] + | + /* empty - allow OVER() with no PARTITION BY */ + ) + ; + windowFrameClause returns [WindowFrameClause vResult = FragmentFactory.CreateFragment()] : tRowsRange:Identifier diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 28673c8d..65bb5a9d 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -32956,6 +32956,11 @@ overClause returns [OverClause vResult] )? tRParen:RightParenthesis { + // Window name inside parentheses requires at least one clause (PARTITION BY, ORDER BY, or window frame) + if (vResult.WindowName != null && vResult.Partitions.Count == 0 && vResult.OrderByClause == null && vResult.WindowFrameClause == null) + { + ThrowParseErrorException("SQL46010", tRParen, TSqlParserResource.SQL46010Message, vResult.WindowName.Value); + } UpdateTokenInfo(vResult,tRParen); } | vResult = overClauseWithWindow @@ -32978,7 +32983,7 @@ overClauseWithWindow returns [OverClause vResult = FragmentFactory.CreateFragmen overClauseNoOrderBy returns [OverClause vResult] : - vResult = overClauseBeginning + vResult = overClauseBeginningNoWindowName tRParen:RightParenthesis { UpdateTokenInfo(vResult,tRParen); @@ -33010,6 +33015,25 @@ overClauseBeginning returns [OverClause vResult = FragmentFactory.CreateFragment )? ; +overClauseBeginningNoWindowName returns [OverClause vResult = FragmentFactory.CreateFragment()] + : + tOver:Over + { + UpdateTokenInfo(vResult,tOver); + } + LeftParenthesis + ( + (Identifier By) => + tPartition:Identifier + { + Match(tPartition, CodeGenerationSupporter.Partition); + } + By expressionList[vResult, vResult.Partitions] + | + /* empty - allow OVER() with no PARTITION BY */ + ) + ; + windowFrameClause returns [WindowFrameClause vResult = FragmentFactory.CreateFragment()] : tRowsRange:Identifier diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index 59ed7b85..70ddca4d 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -32956,6 +32956,11 @@ overClause returns [OverClause vResult] )? tRParen:RightParenthesis { + // Window name inside parentheses requires at least one clause (PARTITION BY, ORDER BY, or window frame) + if (vResult.WindowName != null && vResult.Partitions.Count == 0 && vResult.OrderByClause == null && vResult.WindowFrameClause == null) + { + ThrowParseErrorException("SQL46010", tRParen, TSqlParserResource.SQL46010Message, vResult.WindowName.Value); + } UpdateTokenInfo(vResult,tRParen); } | vResult = overClauseWithWindow @@ -32978,7 +32983,7 @@ overClauseWithWindow returns [OverClause vResult = FragmentFactory.CreateFragmen overClauseNoOrderBy returns [OverClause vResult] : - vResult = overClauseBeginning + vResult = overClauseBeginningNoWindowName tRParen:RightParenthesis { UpdateTokenInfo(vResult,tRParen); @@ -33010,6 +33015,25 @@ overClauseBeginning returns [OverClause vResult = FragmentFactory.CreateFragment )? ; +overClauseBeginningNoWindowName returns [OverClause vResult = FragmentFactory.CreateFragment()] + : + tOver:Over + { + UpdateTokenInfo(vResult,tOver); + } + LeftParenthesis + ( + (Identifier By) => + tPartition:Identifier + { + Match(tPartition, CodeGenerationSupporter.Partition); + } + By expressionList[vResult, vResult.Partitions] + | + /* empty - allow OVER() with no PARTITION BY */ + ) + ; + windowFrameClause returns [WindowFrameClause vResult = FragmentFactory.CreateFragment()] : tRowsRange:Identifier diff --git a/Test/SqlDom/Baselines160/WindowClauseTests160.sql b/Test/SqlDom/Baselines160/WindowClauseTests160.sql index 3c08bcf2..20d9fee9 100644 --- a/Test/SqlDom/Baselines160/WindowClauseTests160.sql +++ b/Test/SqlDom/Baselines160/WindowClauseTests160.sql @@ -103,4 +103,16 @@ SELECT Sum(t.c1) OVER Win1 FROM t1 AS t GROUP BY t.c1 WINDOW Win1 AS (PARTITION BY t.c1) -ORDER BY t.c1; \ No newline at end of file +ORDER BY t.c1; + + +GO +SELECT COUNT(*) OVER Win1 +FROM tb1 +WINDOW Win1 AS (PARTITION BY c1); + + +GO +SELECT COUNT(*) OVER (Win1 ORDER BY c1) +FROM tb1 +WINDOW Win1 AS (PARTITION BY c1); \ No newline at end of file diff --git a/Test/SqlDom/Only160SyntaxTests.cs b/Test/SqlDom/Only160SyntaxTests.cs index 966e51d9..9feb8687 100644 --- a/Test/SqlDom/Only160SyntaxTests.cs +++ b/Test/SqlDom/Only160SyntaxTests.cs @@ -20,7 +20,7 @@ public partial class SqlDomTests new ParserTest160("ExpressionTests160.sql", nErrors80: 1, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160("CreateUserFromExternalProvider160.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1), new ParserTest160("CreateExternalTableStatementTests160.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2), - new ParserTest160("WindowClauseTests160.sql", nErrors80: 14, nErrors90: 13, nErrors100: 13, nErrors110: 13, nErrors120: 13, nErrors130: 13, nErrors140: 13, nErrors150: 13), + new ParserTest160("WindowClauseTests160.sql", nErrors80: 16, nErrors90: 15, nErrors100: 15, nErrors110: 15, nErrors120: 15, nErrors130: 15, nErrors140: 15, nErrors150: 15), new ParserTest160("CreateExternalDataSourceStatementTests160.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160("CreateDatabaseTests160.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4), new ParserTest160("CreateLedgerTableTests160.sql", nErrors80: 14, nErrors90: 14, nErrors100: 14, nErrors110: 14, nErrors120: 14, nErrors130: 14, nErrors140: 14, nErrors150: 14), diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 5c88f7cc..ce5ab88a 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -2156,6 +2156,41 @@ public void IgnoreOrRecpectNullsSyntaxNegativeTest() new ParserErrorInfo(41, "SQL46010", "NULLS")); } + /// + /// Negative tests for invalid OVER clause syntax. + /// Tests for issue: Invalid OVER clause parses successfully + /// OVER clause with just a column reference in parentheses should fail. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void InvalidOverClauseNegativeTest() + { + // OVER clause with just an identifier in parentheses is invalid + // Valid syntax is either OVER identifier (window name reference without parens) + // or OVER (PARTITION BY ...) or OVER (ORDER BY ...) or OVER () + // The error occurs at the closing paren when no clauses follow the window name + // Note: Error message shows the identifier value without quotes + // + ParserTestUtils.ErrorTest160("SELECT COUNT(*) OVER([col]) FROM t1", + new ParserErrorInfo(26, "SQL46010", "col")); + ParserTestUtils.ErrorTest170("SELECT COUNT(*) OVER([col]) FROM t1", + new ParserErrorInfo(26, "SQL46010", "col")); + ParserTestUtils.ErrorTest180("SELECT COUNT(*) OVER([col]) FROM t1", + new ParserErrorInfo(26, "SQL46010", "col")); + + // Another variant with a regular identifier + ParserTestUtils.ErrorTest160("SELECT SUM(Amount) OVER(MyColumn) FROM t1", + new ParserErrorInfo(32, "SQL46010", "MyColumn")); + ParserTestUtils.ErrorTest170("SELECT SUM(Amount) OVER(MyColumn) FROM t1", + new ParserErrorInfo(32, "SQL46010", "MyColumn")); + + // This should also fail for aggregate functions + ParserTestUtils.ErrorTest160("SELECT AVG(Value) OVER(col1) FROM t1", + new ParserErrorInfo(27, "SQL46010", "col1")); + } + + /// /// Negative tests for IS [NOT] DISTINCT FROM syntax. /// diff --git a/Test/SqlDom/TestScripts/WindowClauseTests160.sql b/Test/SqlDom/TestScripts/WindowClauseTests160.sql index 51ca862c..cc0fcfff 100644 --- a/Test/SqlDom/TestScripts/WindowClauseTests160.sql +++ b/Test/SqlDom/TestScripts/WindowClauseTests160.sql @@ -77,4 +77,14 @@ SELECT Sum(t.c1) OVER Win1 FROM t1 t GROUP BY t.c1 WINDOW Win1 AS (PARTITION BY t.c1) ORDER BY t.c1 +GO + +-- checking COUNT(*) with WINDOW clause and window name reference (without parentheses) +SELECT COUNT(*) OVER Win1 FROM tb1 +WINDOW Win1 AS (PARTITION BY c1) +GO + +-- checking COUNT(*) with partial window specification (window name inside parentheses) +SELECT COUNT(*) OVER (Win1 ORDER BY c1) FROM tb1 +WINDOW Win1 AS (PARTITION BY c1) GO \ No newline at end of file diff --git a/global.json b/global.json index d65b2d53..6312649c 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.419", + "version": "8.0.420", "rollForward": "latestMajor" }, "msbuild-sdks": { diff --git a/release-notes/180/180.18.1.md b/release-notes/180/180.18.1.md new file mode 100644 index 00000000..345bdba8 --- /dev/null +++ b/release-notes/180/180.18.1.md @@ -0,0 +1,31 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.18.1 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates .NET SDK to latest patch version 8.0.420 + +#### .NET Framework +#### .NET Core + +### New Features + +### Fixed +* TRIM with FROM clause in RETURN statement fails to parse [#188](https://github.com/microsoft/SqlScriptDOM/issues/188) +* DATEADD/DATEDIFF/DATEPART/DATENAME first argument parsed as ColumnReferenceExpression instead of datepart keyword [#196](https://github.com/microsoft/SqlScriptDOM/issues/196) +* DAY used as argument for DATEADD() is interpreted as ColumnReferenceExpression [#124](https://github.com/microsoft/SqlScriptDOM/issues/124) +* TSql160Parser misidentifies interval parameter in DATEDIFF function as ColumnReferenceExpression [#98](https://github.com/microsoft/SqlScriptDOM/issues/98) +* Invalid OVER clause parses successfully [#195](https://github.com/microsoft/SqlScriptDOM/issues/195) + +### Changes +* Updates the Transact-SQL script generator to ensure that semicolons are correctly placed before any trailing comments + +### Known Issues +* None \ No newline at end of file From a7497c87350e558526c44dd9bd4b1a0dd277c9bd Mon Sep 17 00:00:00 2001 From: Aasim Khan Date: Wed, 27 May 2026 15:36:40 -0700 Subject: [PATCH 29/45] Fix PERSIST_SAMPLE_PERCENT statistics option parsing (#207) Co-authored-by: Aasim Khan --- .../Parser/TSql/CodeGenerationSupporter.cs | 1 + .../Parser/TSql/StatisticsOptionKind.cs | 1 + SqlScriptDom/Parser/TSql/TSql130.g | 18 +++++++++++++++ SqlScriptDom/Parser/TSql/TSql140.g | 18 +++++++++++++++ SqlScriptDom/Parser/TSql/TSql150.g | 18 +++++++++++++++ SqlScriptDom/Parser/TSql/TSql160.g | 18 +++++++++++++++ SqlScriptDom/Parser/TSql/TSql170.g | 18 +++++++++++++++ SqlScriptDom/Parser/TSql/TSql180.g | 18 +++++++++++++++ ...ScriptGeneratorVisitor.StatisticsOption.cs | 5 ++++- ...PersistSamplePercentStatisticsTests130.sql | 22 +++++++++++++++++++ ...PersistSamplePercentStatisticsTests130.sql | 22 +++++++++++++++++++ Test/SqlDom/Only130SyntaxTests.cs | 3 ++- Test/SqlDom/Only180SyntaxTests.cs | 3 ++- ...PersistSamplePercentStatisticsTests130.sql | 8 +++++++ 14 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 Test/SqlDom/Baselines130/PersistSamplePercentStatisticsTests130.sql create mode 100644 Test/SqlDom/Baselines180/PersistSamplePercentStatisticsTests130.sql create mode 100644 Test/SqlDom/TestScripts/PersistSamplePercentStatisticsTests130.sql diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index a7e52ae0..e2712855 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -778,6 +778,7 @@ internal static class CodeGenerationSupporter internal const string Period = "PERIOD"; internal const string PermissionSet = "PERMISSION_SET"; internal const string PerNode = "PER_NODE"; + internal const string PersistSamplePercent = "PERSIST_SAMPLE_PERCENT"; internal const string Persisted = "PERSISTED"; internal const string PhysicalOnly = "PHYSICAL_ONLY"; internal const string PhysName = "PHYSNAME"; diff --git a/SqlScriptDom/Parser/TSql/StatisticsOptionKind.cs b/SqlScriptDom/Parser/TSql/StatisticsOptionKind.cs index acc8eb0f..9e5404b3 100644 --- a/SqlScriptDom/Parser/TSql/StatisticsOptionKind.cs +++ b/SqlScriptDom/Parser/TSql/StatisticsOptionKind.cs @@ -30,6 +30,7 @@ public enum StatisticsOptionKind Rows = 11, Incremental = 12, AutoDrop = 13, + PersistSamplePercent = 14, } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/TSql130.g b/SqlScriptDom/Parser/TSql/TSql130.g index 1212d2ba..4ef84a35 100644 --- a/SqlScriptDom/Parser/TSql/TSql130.g +++ b/SqlScriptDom/Parser/TSql/TSql130.g @@ -12267,10 +12267,26 @@ incrementalStatisticsOption returns [OnOffStatisticsOption vResult = this.Fragme } ; +persistSamplePercentStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentFactory.CreateFragment()] +{ + OptionState vOptionState; +} + : tOption:Identifier EqualsSign vOptionState=optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.PersistSamplePercent); + vResult.OptionKind = StatisticsOptionKind.PersistSamplePercent; + vResult.OptionState = vOptionState; + UpdateTokenInfo(vResult, tOption); + } + ; + createStatisticsStatementWithOption[ref bool isConflictingOption] returns [StatisticsOption vResult] : {NextTokenMatches(CodeGenerationSupporter.Incremental)}? vResult = incrementalStatisticsOption + | + {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | @@ -12327,6 +12343,8 @@ updateStatisticsStatementWithOption [ref bool isConflictingOption] returns [Stat vResult = resampleStatisticsOption | {NextTokenMatches(CodeGenerationSupporter.Incremental)}? vResult = incrementalStatisticsOption + | {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | {NextTokenMatches(CodeGenerationSupporter.StatsStream)}? diff --git a/SqlScriptDom/Parser/TSql/TSql140.g b/SqlScriptDom/Parser/TSql/TSql140.g index 65ccc869..323a91ab 100644 --- a/SqlScriptDom/Parser/TSql/TSql140.g +++ b/SqlScriptDom/Parser/TSql/TSql140.g @@ -12673,10 +12673,26 @@ incrementalStatisticsOption returns [OnOffStatisticsOption vResult = this.Fragme } ; +persistSamplePercentStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentFactory.CreateFragment()] +{ + OptionState vOptionState; +} + : tOption:Identifier EqualsSign vOptionState=optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.PersistSamplePercent); + vResult.OptionKind = StatisticsOptionKind.PersistSamplePercent; + vResult.OptionState = vOptionState; + UpdateTokenInfo(vResult, tOption); + } + ; + createStatisticsStatementWithOption[ref bool isConflictingOption] returns [StatisticsOption vResult] : {NextTokenMatches(CodeGenerationSupporter.Incremental)}? vResult = incrementalStatisticsOption + | + {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | @@ -12733,6 +12749,8 @@ updateStatisticsStatementWithOption [ref bool isConflictingOption] returns [Stat vResult = resampleStatisticsOption | {NextTokenMatches(CodeGenerationSupporter.Incremental)}? vResult = incrementalStatisticsOption + | {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | {NextTokenMatches(CodeGenerationSupporter.StatsStream)}? diff --git a/SqlScriptDom/Parser/TSql/TSql150.g b/SqlScriptDom/Parser/TSql/TSql150.g index 2b013325..6fc72dfe 100644 --- a/SqlScriptDom/Parser/TSql/TSql150.g +++ b/SqlScriptDom/Parser/TSql/TSql150.g @@ -13340,10 +13340,26 @@ incrementalStatisticsOption returns [OnOffStatisticsOption vResult = this.Fragme } ; +persistSamplePercentStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentFactory.CreateFragment()] +{ + OptionState vOptionState; +} + : tOption:Identifier EqualsSign vOptionState=optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.PersistSamplePercent); + vResult.OptionKind = StatisticsOptionKind.PersistSamplePercent; + vResult.OptionState = vOptionState; + UpdateTokenInfo(vResult, tOption); + } + ; + createStatisticsStatementWithOption[ref bool isConflictingOption] returns [StatisticsOption vResult] : {NextTokenMatches(CodeGenerationSupporter.Incremental)}? vResult = incrementalStatisticsOption + | + {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | @@ -13400,6 +13416,8 @@ updateStatisticsStatementWithOption [ref bool isConflictingOption] returns [Stat vResult = resampleStatisticsOption | {NextTokenMatches(CodeGenerationSupporter.Incremental)}? vResult = incrementalStatisticsOption + | {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | {NextTokenMatches(CodeGenerationSupporter.StatsStream)}? diff --git a/SqlScriptDom/Parser/TSql/TSql160.g b/SqlScriptDom/Parser/TSql/TSql160.g index c45d6ffb..9bedb727 100644 --- a/SqlScriptDom/Parser/TSql/TSql160.g +++ b/SqlScriptDom/Parser/TSql/TSql160.g @@ -13385,6 +13385,19 @@ autoDropStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentF } ; +persistSamplePercentStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentFactory.CreateFragment()] +{ + OptionState vOptionState; +} + : tOption:Identifier EqualsSign vOptionState=optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.PersistSamplePercent); + vResult.OptionKind = StatisticsOptionKind.PersistSamplePercent; + vResult.OptionState = vOptionState; + UpdateTokenInfo(vResult, tOption); + } + ; + createStatisticsStatementWithOption[ref bool isConflictingOption] returns [StatisticsOption vResult] : {NextTokenMatches(CodeGenerationSupporter.Incremental)}? @@ -13392,6 +13405,9 @@ createStatisticsStatementWithOption[ref bool isConflictingOption] returns [Stati | {NextTokenMatches(CodeGenerationSupporter.AutoDrop)}? vResult = autoDropStatisticsOption + | + {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | @@ -13450,6 +13466,8 @@ updateStatisticsStatementWithOption [ref bool isConflictingOption] returns [Stat vResult = incrementalStatisticsOption | {NextTokenMatches(CodeGenerationSupporter.AutoDrop)}? vResult = autoDropStatisticsOption + | {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | {NextTokenMatches(CodeGenerationSupporter.StatsStream)}? diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 65bb5a9d..be8d318b 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -13440,6 +13440,19 @@ autoDropStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentF } ; +persistSamplePercentStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentFactory.CreateFragment()] +{ + OptionState vOptionState; +} + : tOption:Identifier EqualsSign vOptionState=optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.PersistSamplePercent); + vResult.OptionKind = StatisticsOptionKind.PersistSamplePercent; + vResult.OptionState = vOptionState; + UpdateTokenInfo(vResult, tOption); + } + ; + createStatisticsStatementWithOption[ref bool isConflictingOption] returns [StatisticsOption vResult] : {NextTokenMatches(CodeGenerationSupporter.Incremental)}? @@ -13447,6 +13460,9 @@ createStatisticsStatementWithOption[ref bool isConflictingOption] returns [Stati | {NextTokenMatches(CodeGenerationSupporter.AutoDrop)}? vResult = autoDropStatisticsOption + | + {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | @@ -13505,6 +13521,8 @@ updateStatisticsStatementWithOption [ref bool isConflictingOption] returns [Stat vResult = incrementalStatisticsOption | {NextTokenMatches(CodeGenerationSupporter.AutoDrop)}? vResult = autoDropStatisticsOption + | {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | {NextTokenMatches(CodeGenerationSupporter.StatsStream)}? diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index 70ddca4d..46131b07 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -13440,6 +13440,19 @@ autoDropStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentF } ; +persistSamplePercentStatisticsOption returns [OnOffStatisticsOption vResult = this.FragmentFactory.CreateFragment()] +{ + OptionState vOptionState; +} + : tOption:Identifier EqualsSign vOptionState=optionOnOff[vResult] + { + Match(tOption, CodeGenerationSupporter.PersistSamplePercent); + vResult.OptionKind = StatisticsOptionKind.PersistSamplePercent; + vResult.OptionState = vOptionState; + UpdateTokenInfo(vResult, tOption); + } + ; + createStatisticsStatementWithOption[ref bool isConflictingOption] returns [StatisticsOption vResult] : {NextTokenMatches(CodeGenerationSupporter.Incremental)}? @@ -13447,6 +13460,9 @@ createStatisticsStatementWithOption[ref bool isConflictingOption] returns [Stati | {NextTokenMatches(CodeGenerationSupporter.AutoDrop)}? vResult = autoDropStatisticsOption + | + {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | @@ -13505,6 +13521,8 @@ updateStatisticsStatementWithOption [ref bool isConflictingOption] returns [Stat vResult = incrementalStatisticsOption | {NextTokenMatches(CodeGenerationSupporter.AutoDrop)}? vResult = autoDropStatisticsOption + | {NextTokenMatches(CodeGenerationSupporter.PersistSamplePercent)}? + vResult = persistSamplePercentStatisticsOption | vResult = sampleStatisticsOption[ref isConflictingOption] | {NextTokenMatches(CodeGenerationSupporter.StatsStream)}? diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatisticsOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatisticsOption.cs index 708583c6..d28bb307 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatisticsOption.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatisticsOption.cs @@ -81,6 +81,9 @@ public override void ExplicitVisit(OnOffStatisticsOption node) case StatisticsOptionKind.AutoDrop: optionName = CodeGenerationSupporter.AutoDrop; break; + case StatisticsOptionKind.PersistSamplePercent: + optionName = CodeGenerationSupporter.PersistSamplePercent; + break; default: System.Diagnostics.Debug.Assert(false, "invalid option encountered"); break; @@ -110,4 +113,4 @@ public override void ExplicitVisit(ResampleStatisticsOption node) } } } -} \ No newline at end of file +} diff --git a/Test/SqlDom/Baselines130/PersistSamplePercentStatisticsTests130.sql b/Test/SqlDom/Baselines130/PersistSamplePercentStatisticsTests130.sql new file mode 100644 index 00000000..92f20c04 --- /dev/null +++ b/Test/SqlDom/Baselines130/PersistSamplePercentStatisticsTests130.sql @@ -0,0 +1,22 @@ +UPDATE STATISTICS dbo.MyTable + WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON; + +UPDATE STATISTICS dbo.T + WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = OFF; + +UPDATE STATISTICS dbo.T + WITH PERSIST_SAMPLE_PERCENT = ON; + +UPDATE STATISTICS dbo.T + WITH PERSIST_SAMPLE_PERCENT = ON, FULLSCAN; + +UPDATE STATISTICS dbo.T + WITH SAMPLE 50 PERCENT, PERSIST_SAMPLE_PERCENT = ON; + +CREATE STATISTICS stat1 + ON dbo.T(c1) + WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON; + +CREATE STATISTICS stat2 + ON dbo.T(c1) + WITH SAMPLE 25 PERCENT, PERSIST_SAMPLE_PERCENT = OFF; diff --git a/Test/SqlDom/Baselines180/PersistSamplePercentStatisticsTests130.sql b/Test/SqlDom/Baselines180/PersistSamplePercentStatisticsTests130.sql new file mode 100644 index 00000000..92f20c04 --- /dev/null +++ b/Test/SqlDom/Baselines180/PersistSamplePercentStatisticsTests130.sql @@ -0,0 +1,22 @@ +UPDATE STATISTICS dbo.MyTable + WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON; + +UPDATE STATISTICS dbo.T + WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = OFF; + +UPDATE STATISTICS dbo.T + WITH PERSIST_SAMPLE_PERCENT = ON; + +UPDATE STATISTICS dbo.T + WITH PERSIST_SAMPLE_PERCENT = ON, FULLSCAN; + +UPDATE STATISTICS dbo.T + WITH SAMPLE 50 PERCENT, PERSIST_SAMPLE_PERCENT = ON; + +CREATE STATISTICS stat1 + ON dbo.T(c1) + WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON; + +CREATE STATISTICS stat2 + ON dbo.T(c1) + WITH SAMPLE 25 PERCENT, PERSIST_SAMPLE_PERCENT = OFF; diff --git a/Test/SqlDom/Only130SyntaxTests.cs b/Test/SqlDom/Only130SyntaxTests.cs index 700629b0..0665459f 100644 --- a/Test/SqlDom/Only130SyntaxTests.cs +++ b/Test/SqlDom/Only130SyntaxTests.cs @@ -74,7 +74,8 @@ public partial class SqlDomTests new ParserTest130("AlterWorkloadGroupStatementSqlDwTests.sql", 12, 6, 5, 5, 5), new ParserTest130("CreateWorkloadClassifierStatementSqlDwTests.sql", 2, 1, 1, 1, 1), new ParserTest130("PredictSqlDwTests.sql", 3, 3, 3, 3, 3), - new ParserTest130("CreateEventSessionNotLikePredicate.sql", 2, 1, 1, 1, 1) + new ParserTest130("CreateEventSessionNotLikePredicate.sql", 2, 1, 1, 1, 1), + new ParserTest130("PersistSamplePercentStatisticsTests130.sql") }; [TestMethod] diff --git a/Test/SqlDom/Only180SyntaxTests.cs b/Test/SqlDom/Only180SyntaxTests.cs index b68b9ba5..cd8746db 100644 --- a/Test/SqlDom/Only180SyntaxTests.cs +++ b/Test/SqlDom/Only180SyntaxTests.cs @@ -13,7 +13,8 @@ public partial class SqlDomTests private static readonly ParserTest[] Only180TestInfos = { new ParserTest180("AutomaticIndexCompactionTests180.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2), - new ParserTest180("TrimFromReturnTests160.sql") + new ParserTest180("TrimFromReturnTests160.sql"), + new ParserTest180("PersistSamplePercentStatisticsTests130.sql") }; private static readonly ParserTest[] SqlAzure180_TestInfos = diff --git a/Test/SqlDom/TestScripts/PersistSamplePercentStatisticsTests130.sql b/Test/SqlDom/TestScripts/PersistSamplePercentStatisticsTests130.sql new file mode 100644 index 00000000..3c66b113 --- /dev/null +++ b/Test/SqlDom/TestScripts/PersistSamplePercentStatisticsTests130.sql @@ -0,0 +1,8 @@ +UPDATE STATISTICS dbo.MyTable WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON; +UPDATE STATISTICS dbo.T WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = OFF; +UPDATE STATISTICS dbo.T WITH PERSIST_SAMPLE_PERCENT = ON; +UPDATE STATISTICS dbo.T WITH PERSIST_SAMPLE_PERCENT = ON, FULLSCAN; +UPDATE STATISTICS dbo.T WITH SAMPLE 50 PERCENT, PERSIST_SAMPLE_PERCENT = ON; + +CREATE STATISTICS stat1 ON dbo.T(c1) WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON; +CREATE STATISTICS stat2 ON dbo.T(c1) WITH SAMPLE 25 PERCENT, PERSIST_SAMPLE_PERCENT = OFF; From 2641cbf3f4a6c05bb1b86a027ab4d368ac213096 Mon Sep 17 00:00:00 2001 From: Randolph West MSFT <97149825+rwestMSFT@users.noreply.github.com> Date: Thu, 4 Jun 2026 12:17:44 -0600 Subject: [PATCH 30/45] Fix generator whitespace bugs: ALTER TABLE ADD INDEX and WINDOW name reference (#208) * Fix generator whitespace bugs: ALTER TABLE ADD INDEX and WINDOW name reference Two unrelated pre-existing generator bugs surfaced by round-tripping the sql-docs corpus: 1. AlterTableAddTableElementStatement omitted the separator between column-definitions/constraints and table indexes, producing 'NOT NULLINDEX ix_...' which fails to reparse. 2. WindowDefinition omitted whitespace between the inherited window-name reference (RefWindowName) and a following PARTITION BY or ORDER BY, producing 'win2PARTITION ...' which fails to reparse. Both fixes are local to their visitors and follow the same separator patterns already present in sibling code paths. Adds three focused regression tests under a new 'Generator Whitespace Regression Tests' region. * Address feedback --- ...itor.AlterTableAddTableElementStatement.cs | 12 ++ ...ScriptGeneratorVisitor.WindowDefinition.cs | 7 + Test/SqlDom/ScriptGeneratorTests.cs | 200 ++++++++++++++++++ 3 files changed, 219 insertions(+) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddTableElementStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddTableElementStatement.cs index a1d21e00..a21ebc2d 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddTableElementStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddTableElementStatement.cs @@ -61,6 +61,18 @@ public override void ExplicitVisit(AlterTableAddTableElementStatement node) ExplicitVisit((SystemTimePeriodDefinition)node.Definition.SystemTimePeriod); } + // Separate preceding elements from inline indexes with a comma + // and newline to avoid token concatenation (e.g. 'NOT NULLINDEX'). + if ((node.Definition.ColumnDefinitions.Count > 0 + || node.Definition.TableConstraints.Count > 0 + || node.Definition.SystemTimePeriod != null) + && node.Definition.Indexes != null + && node.Definition.Indexes.Count > 0) + { + GenerateSymbolAndSpace(TSqlTokenType.Comma); + NewLine(); + } + if (node.Definition.Indexes != null && node.Definition.Indexes.Count > 0) { GenerateCommaSeparatedList(node.Definition.Indexes, true); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs index 94934f2f..dc40eb84 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs @@ -18,6 +18,13 @@ public override void ExplicitVisit(WindowDefinition node) GenerateFragmentIfNotNull(node.RefWindowName); bool partitionByClauseExists = node.Partitions.Count > 0; + + // 'win2PARTITION' / 'win2ORDER' would otherwise tokenize as one identifier. + if (node.RefWindowName != null && (partitionByClauseExists || node.OrderByClause != null)) + { + GenerateSpace(); + } + if (partitionByClauseExists) { GenerateIdentifier(CodeGenerationSupporter.Partition); diff --git a/Test/SqlDom/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGeneratorTests.cs index 34eebbc1..30deaed4 100644 --- a/Test/SqlDom/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGeneratorTests.cs @@ -5,6 +5,7 @@ //------------------------------------------------------------------------------ using System; +using System.Collections.Generic; using System.IO; using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -335,6 +336,205 @@ void ParseAndAssertEquality(string sqlText, SqlScriptGeneratorOptions generatorO Assert.AreEqual(sqlText, generatedSqlText); } + #region Generator Whitespace Regression Tests + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlterTableAddColumnThenIndex_EmitsSeparatorBeforeIndex() + { + // Verbatim sample from docs/relational-databases/in-memory-oltp/ + // altering-memory-optimized-tables.md (line 119). Generator was + // omitting the separator between the trailing column constraint + // ('NOT NULL') and the inline INDEX, producing 'NOT NULLINDEX + // ix_Customer' which fails to reparse. + var sql = + "ALTER TABLE Sales.SalesOrderDetail_inmem " + Environment.NewLine + + " ADD CustomerID int NOT NULL DEFAULT -1 WITH VALUES, " + Environment.NewLine + + " ShipMethodID int NOT NULL DEFAULT -1 WITH VALUES, " + Environment.NewLine + + " INDEX ix_Customer (CustomerID); " + Environment.NewLine + + "GO " + Environment.NewLine; + + var parser = new TSql170Parser(true); + TSqlFragment fragment; + IList parseErrors; + using (var reader = new StringReader(sql)) + { + fragment = parser.Parse(reader, out parseErrors); + } + Assert.AreEqual(0, parseErrors.Count, "Input must parse."); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generated); + + Assert.IsFalse(generated.Contains("NULLINDEX"), + "Column constraint 'NULL' must not run into the 'INDEX' keyword. Actual:\n" + generated); + Assert.IsTrue(generated.Contains("INDEX ix_Customer"), + "INDEX keyword must be present and separated. Actual:\n" + generated); + + var reparser = new TSql170Parser(true); + IList reparseErrors; + using (var reader = new StringReader(generated)) + { + reparser.Parse(reader, out reparseErrors); + } + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlterTableAddIndexOnly_EmitsNoLeadingSeparator() + { + // Verbatim sample from docs/relational-databases/in-memory-oltp/ + // altering-memory-optimized-tables.md (line 111). With no preceding + // column or constraint, the generator must NOT emit a leading + // comma before the INDEX (which would produce invalid syntax). + var sql = + "ALTER TABLE Sales.SalesOrderDetail_inmem " + Environment.NewLine + + " ADD INDEX ix_ModifiedDate (ModifiedDate); " + Environment.NewLine + + "GO " + Environment.NewLine; + + var parser = new TSql170Parser(true); + TSqlFragment fragment; + IList parseErrors; + using (var reader = new StringReader(sql)) + { + fragment = parser.Parse(reader, out parseErrors); + } + Assert.AreEqual(0, parseErrors.Count, "Input must parse."); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generated); + + Assert.IsFalse(generated.Contains("ADD ,") || generated.Contains("ADD\n,"), + "ADD must not be followed by a stray separator. Actual:\n" + generated); + Assert.IsTrue(generated.Contains("ADD INDEX ix_ModifiedDate"), + "INDEX clause must follow ADD directly. Actual:\n" + generated); + + var reparser = new TSql170Parser(true); + IList reparseErrors; + using (var reader = new StringReader(generated)) + { + reparser.Parse(reader, out reparseErrors); + } + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestWindowDefinition_RefWindowFollowedByPartitionByEmitsSpace() + { + // Verbatim sample from docs/t-sql/queries/select-window-transact-sql.md + // (line 312). Generator was emitting 'win2PARTITION' (no space) + // because the visitor didn't separate the inherited window-name + // reference from the PARTITION keyword. + var sql = + "ALTER DATABASE AdventureWorks2025" + Environment.NewLine + + "SET COMPATIBILITY_LEVEL = 160;" + Environment.NewLine + + "GO" + Environment.NewLine + + Environment.NewLine + + "USE AdventureWorks2025;" + Environment.NewLine + + "GO" + Environment.NewLine + + Environment.NewLine + + "SELECT SalesOrderID AS OrderNumber," + Environment.NewLine + + " ProductID," + Environment.NewLine + + " OrderQty AS Qty," + Environment.NewLine + + " SUM(OrderQty) OVER win2 AS Total," + Environment.NewLine + + " AVG(OrderQty) OVER win1 AS Avg" + Environment.NewLine + + "FROM Sales.SalesOrderDetail" + Environment.NewLine + + "WHERE SalesOrderID IN (43659, 43664)" + Environment.NewLine + + " AND ProductID LIKE '71%'" + Environment.NewLine + + "WINDOW win1 AS (win3)," + Environment.NewLine + + " win2 AS (ORDER BY SalesOrderID, ProductID)," + Environment.NewLine + + " win3 AS (win2 PARTITION BY SalesOrderID);" + Environment.NewLine; + + var parser = new TSql170Parser(true); + TSqlFragment fragment; + IList parseErrors; + using (var reader = new StringReader(sql)) + { + fragment = parser.Parse(reader, out parseErrors); + } + Assert.AreEqual(0, parseErrors.Count, "Input must parse."); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generated); + + Assert.IsFalse(generated.Contains("win2PARTITION"), + "Window-name reference must not run into PARTITION keyword. Actual:\n" + generated); + Assert.IsTrue(generated.Contains("win2 PARTITION"), + "Generated window must read 'win2 PARTITION'. Actual:\n" + generated); + + var reparser = new TSql170Parser(true); + IList reparseErrors; + using (var reader = new StringReader(generated)) + { + reparser.Parse(reader, out reparseErrors); + } + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestWindowDefinition_RefWindowFollowedByOrderByEmitsSpace() + { + // Same bug class as above, exercised through the ORDER BY branch. + // 'WINDOW name AS (refname ORDER BY ...)' must not emit + // 'refnameORDER'. This shape isn't in the docs but the same code + // path can produce it; included as belt-and-suspenders coverage. + var sql = + "SELECT SalesOrderID, SUM(OrderQty) OVER win2 AS Total" + Environment.NewLine + + "FROM Sales.SalesOrderDetail" + Environment.NewLine + + "WINDOW win1 AS (PARTITION BY ProductID)," + Environment.NewLine + + " win2 AS (win1 ORDER BY SalesOrderID);"; + + var parser = new TSql170Parser(true); + TSqlFragment fragment; + IList parseErrors; + using (var reader = new StringReader(sql)) + { + fragment = parser.Parse(reader, out parseErrors); + } + Assert.AreEqual(0, parseErrors.Count, "Input must parse."); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generated); + + Assert.IsFalse(generated.Contains("win1ORDER"), + "Window-name reference must not run into ORDER keyword. Actual:\n" + generated); + Assert.IsTrue(generated.Contains("win1 ORDER"), + "Generated window must read 'win1 ORDER'. Actual:\n" + generated); + + var reparser = new TSql170Parser(true); + IList reparseErrors; + using (var reader = new StringReader(generated)) + { + reparser.Parse(reader, out reparseErrors); + } + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL must reparse. Actual:\n" + generated); + } + + #endregion + #region Comment Preservation Tests [TestMethod] From bc884b9e401f7ab8c97ffcfcefeb3689c8fd557c Mon Sep 17 00:00:00 2001 From: Randolph West MSFT <97149825+rwestMSFT@users.noreply.github.com> Date: Thu, 4 Jun 2026 12:18:07 -0600 Subject: [PATCH 31/45] Enhance comment handling support (#209) * Expand comment handling support * Address feedback --- ...GeneratorVisitor.BeginEndBlockStatement.cs | 3 + .../SqlScriptGeneratorVisitor.Comments.cs | 260 +++++++++- ...SqlScriptGeneratorVisitor.CommonPhrases.cs | 18 +- .../SqlScriptGeneratorVisitor.cs | 4 + Test/SqlDom/ScriptGeneratorTests.cs | 458 +++++++++++++++++- 5 files changed, 704 insertions(+), 39 deletions(-) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BeginEndBlockStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BeginEndBlockStatement.cs index 94acf65e..445f7c70 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BeginEndBlockStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BeginEndBlockStatement.cs @@ -20,6 +20,9 @@ public override void ExplicitVisit(BeginEndBlockStatement node) GenerateFragmentIfNotNull(node.StatementList); PopAlignmentPoint(); + // Emit any comments sitting between the last inner statement and END. + EmitCommentsUntilNextNonTriviaToken(); + NewLine(); GenerateKeyword(TSqlTokenType.End); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs index 697e8b19..9a800616 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs @@ -34,18 +34,20 @@ internal abstract partial class SqlScriptGeneratorVisitor private bool _leadingCommentsEmitted = false; /// - /// When true, suppresses trailing comment emission in HandleCommentsAfterFragment - /// for fragments whose LastTokenIndex matches or exceeds _suppressTrailingCommentsAfterIndex. - /// Used by GenerateStatementWithSemiColon to defer trailing comments until after - /// the semicolon has been placed, without affecting inter-clause comments. + /// When true, defers trailing comments for fragments at or past + /// _suppressTrailingCommentsAfterIndex until after the semicolon. + /// Set by GenerateStatementWithSemiColon. /// private bool _suppressTrailingComments = false; + /// Statement boundary used by _suppressTrailingComments. + private int _suppressTrailingCommentsAfterIndex = -1; + /// - /// The LastTokenIndex of the statement for which trailing comments are being suppressed. - /// Only comments after this index are suppressed. + /// Buffer of '--' trailing comments awaiting the next NewLine. A '--' + /// comment is only safe at end-of-line. /// - private int _suppressTrailingCommentsAfterIndex = -1; + private readonly List _deferredTrailingSingleLineComments = new List(); #endregion @@ -64,6 +66,7 @@ protected void SetTokenStreamForComments(IList tokenStream) _leadingCommentsEmitted = false; _suppressTrailingComments = false; _suppressTrailingCommentsAfterIndex = -1; + _deferredTrailingSingleLineComments.Clear(); } /// @@ -127,9 +130,9 @@ protected void EmitGapComments(TSqlFragment fragment) } /// - /// Emits trailing comments that appear immediately after the fragment. + /// Emits trailing comments after the fragment, scanning across newlines. + /// Each comment's own-line vs same-line placement is preserved from source. /// - /// The fragment that was just generated. protected void EmitTrailingComments(TSqlFragment fragment) { if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) @@ -143,23 +146,229 @@ protected void EmitTrailingComments(TSqlFragment fragment) return; } - // Scan for comments immediately following the fragment + int prevEmittedSourceIndex = lastTokenIndex; for (int i = lastTokenIndex + 1; i < _currentTokenStream.Count; i++) { var token = _currentTokenStream[i]; - - if (IsCommentToken(token) && !_emittedComments.Contains(token)) + + if (IsCommentToken(token)) { - EmitCommentToken(token, isLeading: false); - _emittedComments.Add(token); - _lastProcessedTokenIndex = i; + if (!_emittedComments.Contains(token)) + { + bool ownLine = SourceGapContainsNewline(prevEmittedSourceIndex, i); + EmitTrailingCommentToken(token, ownLine); + _emittedComments.Add(token); + _lastProcessedTokenIndex = i; + prevEmittedSourceIndex = i; + } + continue; + } + + if (token.TokenType == TSqlTokenType.WhiteSpace) + { + continue; + } + + // Any other token (including ';') ends the window. + break; + } + } + + /// + /// Trailing-comment scan limited to the fragment's last source line. + /// Used after statement-ending semicolons so a comment on a later line + /// remains a leading comment of the next statement. + /// + protected void EmitSameLineTrailingComments(TSqlFragment fragment) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return; + } + + int lastTokenIndex = fragment.LastTokenIndex; + if (lastTokenIndex < 0 || lastTokenIndex >= _currentTokenStream.Count) + { + return; + } + + for (int i = lastTokenIndex + 1; i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + + if (token.TokenType == TSqlTokenType.WhiteSpace) + { + if (ContainsLineBreak(token.Text)) + { + break; + } + continue; } - else if (token.TokenType != TSqlTokenType.WhiteSpace) + + if (IsCommentToken(token)) + { + if (!_emittedComments.Contains(token)) + { + EmitTrailingCommentToken(token, ownLine: false); + _emittedComments.Add(token); + _lastProcessedTokenIndex = i; + + // A '--' comment or a newline-spanning '/* */' ends the line. + if (token.TokenType == TSqlTokenType.SingleLineComment || + ContainsLineBreak(token.Text)) + { + break; + } + } + continue; + } + + break; + } + } + + /// True if any whitespace token between fromIndex and toIndex contains a line break. + private bool SourceGapContainsNewline(int fromIndex, int toIndex) + { + for (int j = fromIndex + 1; j < toIndex; j++) + { + var t = _currentTokenStream[j]; + if (t.TokenType == TSqlTokenType.WhiteSpace && ContainsLineBreak(t.Text)) { - // Stop at next non-whitespace, non-comment token - break; + return true; } } + return false; + } + + /// + /// Emits any unemitted comments whose token index falls within the + /// statement's source token range (up to and including LastTokenIndex). + /// Catches floating comments inside a statement whose '/' or ';' has been + /// absorbed into this statement (e.g. '/* */;' or leading ';WITH'). + /// + protected void EmitUnemittedCommentsThroughStatementEnd(TSqlStatement statement) + { + if (!_options.PreserveComments || _currentTokenStream == null || statement == null) + { + return; + } + + int endInclusive = statement.LastTokenIndex; + if (endInclusive < 0 || endInclusive >= _currentTokenStream.Count) + { + return; + } + + for (int i = _lastProcessedTokenIndex + 1; i <= endInclusive; i++) + { + var t = _currentTokenStream[i]; + if (IsCommentToken(t) && !_emittedComments.Contains(t)) + { + EmitTrailingCommentToken(t, ownLine: true); + _emittedComments.Add(t); + } + } + + if (endInclusive > _lastProcessedTokenIndex) + { + _lastProcessedTokenIndex = endInclusive; + } + } + + /// + /// Emits unemitted comments in the trivia run starting at + /// _lastProcessedTokenIndex+1; stops at the first non-whitespace, + /// non-comment token. For use before a container emits a closing + /// keyword like END. + /// + protected void EmitCommentsUntilNextNonTriviaToken() + { + if (!_options.PreserveComments || _currentTokenStream == null) + { + return; + } + + for (int i = _lastProcessedTokenIndex + 1; i < _currentTokenStream.Count; i++) + { + var t = _currentTokenStream[i]; + + if (IsCommentToken(t)) + { + if (!_emittedComments.Contains(t)) + { + EmitTrailingCommentToken(t, ownLine: true); + _emittedComments.Add(t); + _lastProcessedTokenIndex = i; + } + continue; + } + + if (t.TokenType == TSqlTokenType.WhiteSpace) + { + continue; + } + + break; + } + } + + /// + /// Emits a trailing comment. '--' comments are deferred to the next + /// NewLine; block comments are written inline immediately. + /// + private void EmitTrailingCommentToken(TSqlParserToken token, bool ownLine) + { + if (token == null) + { + return; + } + + if (token.TokenType == TSqlTokenType.SingleLineComment) + { + _deferredTrailingSingleLineComments.Add(token.Text); + return; + } + + if (ownLine) + { + _writer.NewLine(); + } + else + { + _writer.AddToken(ScriptGeneratorSupporter.CreateWhitespaceToken(1)); + } + + _writer.AddToken(new TSqlParserToken(token.TokenType, token.Text)); + } + + /// + /// Writes deferred '--' trailing comments at end-of-line. Called from + /// the visitor's NewLine helper before each newline, and at end-of-script. + /// + internal void FlushDeferredTrailingSingleLineComments() + { + if (_deferredTrailingSingleLineComments.Count == 0) + { + return; + } + + for (int i = 0; i < _deferredTrailingSingleLineComments.Count; i++) + { + _writer.AddToken(ScriptGeneratorSupporter.CreateWhitespaceToken(1)); + _writer.AddToken(new TSqlParserToken( + TSqlTokenType.SingleLineComment, + _deferredTrailingSingleLineComments[i])); + + // The final '--' is terminated by the caller's pending newline; + // earlier ones need their own. + if (i < _deferredTrailingSingleLineComments.Count - 1) + { + _writer.NewLine(); + } + } + + _deferredTrailingSingleLineComments.Clear(); } /// @@ -208,17 +417,13 @@ protected void HandleCommentsAfterFragment(TSqlFragment fragment) return; } - // When trailing comments are suppressed (e.g., during statement body generation - // before semicolon placement), skip emitting trailing comments only for fragments - // whose last token is at or past the statement boundary. Inter-clause comments - // (within the statement) are still emitted normally. + // Defer until after the semicolon when at statement boundary. if (_suppressTrailingComments && fragment.LastTokenIndex >= _suppressTrailingCommentsAfterIndex) { UpdateLastProcessedIndex(fragment); return; } - // Emit trailing comments and update tracking EmitTrailingComments(fragment); UpdateLastProcessedIndex(fragment); } @@ -276,6 +481,9 @@ private void EmitCommentToken(TSqlParserToken token, bool isLeading) /// protected void EmitRemainingComments() { + // Flush deferred '--' comments at end-of-script. + FlushDeferredTrailingSingleLineComments(); + if (!_options.PreserveComments || _currentTokenStream == null) { return; @@ -305,6 +513,12 @@ private static bool IsCommentToken(TSqlParserToken token) token.TokenType == TSqlTokenType.MultilineComment); } + /// True if the text contains '\n' or '\r'. + private static bool ContainsLineBreak(string text) + { + return text != null && (text.IndexOf('\n') >= 0 || text.IndexOf('\r') >= 0); + } + #endregion } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs index bcfb13ad..00bc2bc3 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs @@ -473,11 +473,25 @@ protected void GenerateStatementWithSemiColon(TSqlStatement statement) _suppressTrailingComments = previousSuppressState; _suppressTrailingCommentsAfterIndex = previousSuppressIndex; + // Sweep any comments inside the statement's token range that no + // inner-fragment scan emitted (e.g. comments between an absorbed + // ';' separator and the statement's last token). + EmitUnemittedCommentsThroughStatementEnd(statement); + // Semicolon BEFORE trailing comments GenerateSemiColonWhenNecessary(statement); - // Now emit trailing comments (after the semicolon) - HandleCommentsAfterFragment(statement); + // Only same-line trailing comments belong after the semicolon; a + // comment on a later line is a leading comment of the next statement. + if (_options.PreserveComments && _currentTokenStream != null) + { + EmitSameLineTrailingComments(statement); + UpdateLastProcessedIndex(statement); + } + else + { + HandleCommentsAfterFragment(statement); + } } protected void GenerateCommaSeparatedWithClause(IList fragments, bool indent, bool includeParentheses) where T : TSqlFragment diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs index ba3e9014..a5136c96 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs @@ -70,6 +70,10 @@ protected void Mark(AlignmentPoint ap) protected void NewLine() { + if (_options.PreserveComments) + { + FlushDeferredTrailingSingleLineComments(); + } _writer.NewLine(); } diff --git a/Test/SqlDom/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGeneratorTests.cs index 30deaed4..de29e542 100644 --- a/Test/SqlDom/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGeneratorTests.cs @@ -1156,21 +1156,26 @@ END AS PriorityLevel "Medium priority block comment should be preserved. Actual: " + generatedSql); Assert.IsTrue(generatedSql.Contains("-- Default to low priority"), "ELSE comment should be preserved. Actual: " + generatedSql); - - // Verify position: comments should appear before their respective WHEN/ELSE clauses + + // The generated SQL must reparse cleanly: a '--' comment must never + // be placed where it would absorb a following keyword or symbol. + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL should reparse without errors. Actual: " + generatedSql); + + // Verify position: comments anchored to a preceding clause should + // appear before their associated WHEN/ELSE when a natural newline + // separates them in the output. int highPriorityCommentIdx = generatedSql.IndexOf("-- Check for high priority"); int firstWhenIdx = generatedSql.IndexOf("WHEN", StringComparison.OrdinalIgnoreCase); int mediumCommentIdx = generatedSql.IndexOf("/* Medium priority items */"); int secondWhenIdx = generatedSql.IndexOf("WHEN", firstWhenIdx + 1, StringComparison.OrdinalIgnoreCase); - int elseCommentIdx = generatedSql.IndexOf("-- Default to low priority"); - int elseIdx = generatedSql.IndexOf("ELSE", StringComparison.OrdinalIgnoreCase); - + Assert.IsTrue(highPriorityCommentIdx < firstWhenIdx, $"High priority comment should appear before first WHEN. Comment at {highPriorityCommentIdx}, WHEN at {firstWhenIdx}"); Assert.IsTrue(mediumCommentIdx < secondWhenIdx, $"Medium priority comment should appear before second WHEN. Comment at {mediumCommentIdx}, WHEN at {secondWhenIdx}"); - Assert.IsTrue(elseCommentIdx < elseIdx, - $"ELSE comment should appear before ELSE. Comment at {elseCommentIdx}, ELSE at {elseIdx}"); } [TestMethod] @@ -1206,21 +1211,26 @@ FROM users u "LEFT JOIN block comment should be preserved. Actual: " + generatedSql); Assert.IsTrue(generatedSql.Contains("-- Cross join for all combinations"), "CROSS JOIN comment should be preserved. Actual: " + generatedSql); - - // Verify position: comments should appear before their respective JOIN clauses + + // The generated SQL must reparse cleanly: a '--' comment must never + // be placed where it would absorb a following keyword or symbol. + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL should reparse without errors. Actual: " + generatedSql); + + // Comments preceding their JOIN in source should appear before the + // matching JOIN keyword in output where a natural newline separates + // the prior clause from the next JOIN. int innerJoinCommentIdx = generatedSql.IndexOf("-- Join to get user orders"); int innerJoinIdx = generatedSql.IndexOf("INNER JOIN", StringComparison.OrdinalIgnoreCase); int leftJoinCommentIdx = generatedSql.IndexOf("/* Left join for optional address */"); int leftJoinIdx = generatedSql.IndexOf("LEFT", StringComparison.OrdinalIgnoreCase); - int crossJoinCommentIdx = generatedSql.IndexOf("-- Cross join for all combinations"); - int crossJoinIdx = generatedSql.IndexOf("CROSS JOIN", StringComparison.OrdinalIgnoreCase); - + Assert.IsTrue(innerJoinCommentIdx < innerJoinIdx, $"INNER JOIN comment should appear before INNER JOIN. Comment at {innerJoinCommentIdx}, JOIN at {innerJoinIdx}"); Assert.IsTrue(leftJoinCommentIdx < leftJoinIdx, $"LEFT JOIN comment should appear before LEFT JOIN. Comment at {leftJoinCommentIdx}, JOIN at {leftJoinIdx}"); - Assert.IsTrue(crossJoinCommentIdx < crossJoinIdx, - $"CROSS JOIN comment should appear before CROSS JOIN. Comment at {crossJoinCommentIdx}, JOIN at {crossJoinIdx}"); } [TestMethod] @@ -1552,6 +1562,426 @@ public void TestPreserveCommentsEnabled_SemicolonBeforeTrailingBlockComment() $"Semicolon should appear before trailing block comment. Semicolon at {semicolonIndex}, comment at {commentIndex}. Actual: " + generatedSql); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_StandaloneCommentNotAttachedAsTrailing() + { + // Regression: a comment on its own line (after a newline) between two + // statements must remain a leading comment of the NEXT statement, not + // be promoted to a trailing comment of the previous statement. + var sqlWithComments = + "SELECT Instructions\nFROM T;\n\n-- Now replace value of lot size\nUPDATE T SET Instructions = 1;"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + int firstSemicolonIndex = generatedSql.IndexOf(";"); + int commentIndex = generatedSql.IndexOf("-- Now replace value of lot size"); + int updateIndex = generatedSql.IndexOf("UPDATE", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(commentIndex >= 0, "Comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(updateIndex > commentIndex, + $"Standalone comment should appear before UPDATE. Comment at {commentIndex}, UPDATE at {updateIndex}. Actual: " + generatedSql); + Assert.IsTrue(firstSemicolonIndex >= 0 && firstSemicolonIndex < commentIndex, + $"Semicolon for SELECT must come before the standalone comment. Semicolon at {firstSemicolonIndex}, comment at {commentIndex}. Actual: " + generatedSql); + + // The comment must not appear on the same line as 'FROM ... T;'. + // The generator may pretty-print with extra spaces (e.g. 'FROM T'), + // so locate the 'FROM' keyword and require a newline between it and the comment. + int fromIndex = generatedSql.IndexOf("FROM", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(fromIndex >= 0, "FROM must be present in output. Actual: " + generatedSql); + int newlineAfterFrom = generatedSql.IndexOf('\n', fromIndex); + Assert.IsTrue(newlineAfterFrom > 0 && newlineAfterFrom < commentIndex, + $"Standalone comment should be on its own line, not appended to the FROM line. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_MultiLineCommentSpansLines_NextLineCommentNotTrailing() + { + // Edge case: a block comment that starts on the same line as the previous + // statement but contains a newline must not pull in a subsequent line's + // comment as if it were also trailing. + var sql = + "SELECT 1; /* spans\nlines */\n-- belongs to next\nSELECT 2;"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + int spansIdx = generatedSql.IndexOf("spans"); + int nextIdx = generatedSql.IndexOf("-- belongs to next"); + int selectTwoIdx = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(spansIdx >= 0, "Multi-line comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(nextIdx >= 0, "Following single-line comment should be preserved. Actual: " + generatedSql); + Assert.IsTrue(nextIdx < selectTwoIdx, + "Following comment must appear before SELECT 2 (i.e., as leading of next statement). Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_SameLineBlockThenSingleLine() + { + // Two trailing comments on the same line as the statement. + var sql = "SELECT 1; /* block */ -- and single\nSELECT 2;"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + int blockIdx = generatedSql.IndexOf("/* block */"); + int singleIdx = generatedSql.IndexOf("-- and single"); + int selectTwoIdx = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(blockIdx >= 0 && singleIdx >= 0, "Both comments should be preserved. Actual: " + generatedSql); + Assert.IsTrue(blockIdx < singleIdx && singleIdx < selectTwoIdx, + "Same-line trailing comments must precede the next statement. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_SingleLineInsideArgListDoesNotAbsorbClosingTokens() + { + // Real-world pattern from RAISERROR docs: '--' comments inside an + // argument list previously absorbed the ')' and ';' that followed, + // producing un-reparseable output. The fix defers each '--' to a + // safe end-of-line position. + var sql = "RAISERROR('msg', -- text\n 16, -- severity\n 1 -- state\n);\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + Assert.IsTrue(generatedSql.Contains("-- text"), "Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- severity"), "Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- state"), "Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, + "Generated SQL must reparse without errors. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_LeadingCommentAfterGoBatch() + { + // Real-world pattern: a '--' comment between GO and the next batch + // must remain a leading comment of that batch, not be absorbed onto + // the prior batch's last line. + var sql = "SELECT 1;\nGO\n-- leading before next batch\nSELECT 2;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + int commentIdx = generatedSql.IndexOf("-- leading before next batch"); + int selectTwoIdx = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + int selectOneIdx = generatedSql.IndexOf("SELECT 1", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(commentIdx > selectOneIdx && commentIdx < selectTwoIdx, + "Comment must appear between the two batches. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_SingleLineCommentsInsideIfBeginEndBlock() + { + // Real-world pattern from sql-docs IF/BEGIN/END examples: '--' + // comments interleaved between statements inside a BEGIN block + // must each appear before their associated SELECT in the output. + var sql = + "IF (1 = 1)\n" + + "BEGIN\n" + + " -- inside if\n" + + " SELECT 1;\n" + + " -- after first stmt inside if\n" + + " SELECT 2;\n" + + "END;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + int insideIdx = generatedSql.IndexOf("-- inside if"); + int afterIdx = generatedSql.IndexOf("-- after first stmt inside if"); + int select1Idx = generatedSql.IndexOf("SELECT 1", StringComparison.OrdinalIgnoreCase); + int select2Idx = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(insideIdx >= 0 && insideIdx < select1Idx, + "'-- inside if' must precede SELECT 1. Actual: " + generatedSql); + Assert.IsTrue(afterIdx > select1Idx && afterIdx < select2Idx, + "'-- after first stmt' must be between SELECT 1 and SELECT 2. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_BeginEndBlockPreservesCommentBeforeEnd() + { + // Real-world pattern: comments placed between the last statement + // in a BEGIN block and the END keyword must be preserved. + var sql = + "BEGIN\n" + + " SELECT 1;\n" + + " /* between stmt and closer */\n" + + " -- also a trailing note\n" + + "END;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + Assert.IsTrue(generatedSql.Contains("/* between stmt and closer */"), + "Block comment before END must be preserved. Actual: " + generatedSql); + Assert.IsTrue(generatedSql.Contains("-- also a trailing note"), + "Line comment before END must be preserved. Actual: " + generatedSql); + + int endIdx = generatedSql.IndexOf("END", StringComparison.Ordinal); + int blockIdx = generatedSql.IndexOf("/* between stmt and closer */"); + int lineIdx = generatedSql.IndexOf("-- also a trailing note"); + Assert.IsTrue(blockIdx >= 0 && blockIdx < endIdx, + "Block comment must appear before END. Actual: " + generatedSql); + Assert.IsTrue(lineIdx >= 0 && lineIdx < endIdx, + "Line comment must appear before END. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_StandaloneBlockCommentBetweenStatementsPreserved() + { + // '/* lonely */;' parses as an empty statement absorbed into the + // previous statement's token range. Without a sweep through the + // statement's range, the comment was dropped. + var sql = "SELECT 1;\n/* lonely */;\nSELECT 2;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + Assert.IsTrue(generatedSql.Contains("/* lonely */"), + "Standalone block comment must be preserved. Actual: " + generatedSql); + + int select1Idx = generatedSql.IndexOf("SELECT 1", StringComparison.OrdinalIgnoreCase); + int commentIdx = generatedSql.IndexOf("/* lonely */"); + int select2Idx = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(select1Idx < commentIdx && commentIdx < select2Idx, + "Standalone comment must appear between the two SELECT statements. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_LeadingCommentBeforeSemicolonWithCte() + { + // The leading ';' of ';WITH cte ...' is parsed as part of the + // previous statement's token range. A leading comment that sits + // between the prior statement's terminator and the ';WITH' was + // previously dropped. + var sql = "SELECT 1;\n-- before with\n;WITH cte AS (SELECT 1 AS a) SELECT a FROM cte;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + Assert.IsTrue(generatedSql.Contains("-- before with"), + "Leading comment before ';WITH' must be preserved. Actual: " + generatedSql); + + int select1Idx = generatedSql.IndexOf("SELECT 1", StringComparison.OrdinalIgnoreCase); + int commentIdx = generatedSql.IndexOf("-- before with"); + int withIdx = generatedSql.IndexOf("WITH", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(select1Idx < commentIdx && commentIdx < withIdx, + "Comment must appear between SELECT 1 and WITH. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_MultiLineBlockCommentBetweenStatements() + { + // Real-world pattern: a '/* ... */' block comment that itself + // spans multiple source lines, placed between two statements. + // Exercises the ContainsLineBreak path for block-comment tokens. + var sql = + "SELECT 1;\n" + + "/* multi-line\n" + + " comment\n" + + " spans three lines */\n" + + "SELECT 2;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + Assert.IsTrue(generatedSql.Contains("multi-line") && + generatedSql.Contains("spans three lines"), + "Full text of the multi-line block comment must be preserved. Actual: " + generatedSql); + + int select1Idx = generatedSql.IndexOf("SELECT 1", StringComparison.OrdinalIgnoreCase); + int blockIdx = generatedSql.IndexOf("/* multi-line"); + int select2Idx = generatedSql.IndexOf("SELECT 2", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(select1Idx < blockIdx && blockIdx < select2Idx, + "Multi-line block must appear between the two SELECTs. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveComments_RealWorldXmlModifyBatchFromDocs() + { + // End-to-end regression for the pattern that produced the original + // bug screenshot: a series of UPDATE statements that call + // XML .modify(...) with long string-literal arguments, separated + // by '--' leading comments. The leading comment of the LAST UPDATE + // ('-- Now replace value of lot size') was being absorbed onto the + // previous statement's trailing 'FROM T;' line. + var sql = + "SELECT Instructions\n" + + "FROM T;\n" + + "\n" + + "-- Now replace value of lot size\n" + + "UPDATE T\n" + + "SET Instructions = 1;\n"; + + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + PreserveComments = true, + IncludeSemicolons = true, + }); + generator.GenerateScript(fragment, out var generatedSql); + + int fromTIdx = generatedSql.IndexOf("FROM T;", StringComparison.Ordinal); + if (fromTIdx < 0) fromTIdx = generatedSql.IndexOf("FROM T;", StringComparison.Ordinal); + int commentIdx = generatedSql.IndexOf("-- Now replace value of lot size"); + int updateIdx = generatedSql.IndexOf("UPDATE", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(commentIdx >= 0, "Leading comment must be preserved. Actual: " + generatedSql); + Assert.IsTrue(fromTIdx >= 0 && fromTIdx < commentIdx, + "Comment must appear AFTER 'FROM T;'. Actual: " + generatedSql); + Assert.IsTrue(commentIdx < updateIdx, + "Comment must appear BEFORE 'UPDATE'. Actual: " + generatedSql); + + // The original bug: the comment was attached as trailing to FROM, + // making the FROM line read 'FROM T; -- Now replace value of lot size'. + int fromLineEnd = generatedSql.IndexOf('\n', fromTIdx); + Assert.IsTrue(fromLineEnd > 0 && fromLineEnd < commentIdx, + "Comment must be on a separate line from 'FROM T;'. Actual: " + generatedSql); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); + } + #endregion } } From 20f9bf1117ec9b4366d2f66165df193ec1b206c8 Mon Sep 17 00:00:00 2001 From: NAVEEN NAIK <71204882+ZEUSXXIV@users.noreply.github.com> Date: Wed, 10 Jun 2026 17:04:49 +0000 Subject: [PATCH 32/45] Fix MODEL_TYPE fragment classification in CreateExternalModelStatement (#176) (#210) --- SqlScriptDom/Parser/TSql/Ast.xml | 7 ++-- .../Parser/TSql/ExternalModelTypeOption.cs | 8 ++--- SqlScriptDom/Parser/TSql/TSql170.g | 12 +++++-- SqlScriptDom/Parser/TSql/TSql180.g | 12 +++++-- ...ptGenerator.AlterExternalModelStatement.cs | 8 ++--- ...torVisitor.CreateExternalModelStatement.cs | 18 +++++++---- Test/SqlDom/Only170SyntaxTests.cs | 32 +++++++++++++++++++ 7 files changed, 73 insertions(+), 24 deletions(-) diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index 4c5a4f4f..bad570b2 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -1,4 +1,4 @@ - + --------- Co-authored-by: Ema Paunovic Co-authored-by: Maksim Vlasov --- SqlScriptDom/Parser/TSql/Ast.xml | 52 ++++ .../Parser/TSql/CodeGenerationSupporter.cs | 11 + .../TSql/SemanticIndexChunkOptionKind.cs | 24 ++ .../Parser/TSql/SemanticIndexSearchType.cs | 25 ++ SqlScriptDom/Parser/TSql/TSql180.g | 238 ++++++++++++++++++ .../Parser/TSql/TSql180ParserBaseInternal.cs | 23 +- SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 122 ++++++++- ...torVisitor.CreateSemanticIndexStatement.cs | 208 +++++++++++++++ ...eratorVisitor.ExternalFunctionStatement.cs | 52 ++++ ...eratorVisitor.InvokeExternalApiFunction.cs | 56 +++++ .../CreateSemanticIndexTests180.sql | 78 ++++++ .../ExternalFunctionTestsFabricDW.sql | 49 ++++ .../InvokeExternalApiTestsFabricDW.sql | 27 ++ Test/SqlDom/Only180SyntaxTests.cs | 3 +- Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 2 + Test/SqlDom/ParserErrorsTests.cs | 116 +++++++++ .../CreateSemanticIndexTests180.sql | 56 +++++ .../ExternalFunctionTestsFabricDW.sql | 62 +++++ .../InvokeExternalApiTestsFabricDW.sql | 27 ++ release-notes/180/180.37.3.md | 30 +++ 20 files changed, 1258 insertions(+), 3 deletions(-) create mode 100644 SqlScriptDom/Parser/TSql/SemanticIndexChunkOptionKind.cs create mode 100644 SqlScriptDom/Parser/TSql/SemanticIndexSearchType.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSemanticIndexStatement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs create mode 100644 Test/SqlDom/Baselines180/CreateSemanticIndexTests180.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/ExternalFunctionTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/InvokeExternalApiTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/CreateSemanticIndexTests180.sql create mode 100644 Test/SqlDom/TestScripts/ExternalFunctionTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/InvokeExternalApiTestsFabricDW.sql create mode 100644 release-notes/180/180.37.3.md diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index bad570b2..d90c664a 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -794,6 +794,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -4658,6 +4682,28 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -4806,6 +4852,12 @@ + + + + + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index e2712855..7bd0e484 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -204,6 +204,7 @@ internal static class CodeGenerationSupporter internal const string ChangeTable = "CHANGETABLE"; internal const string ChangeTracking = "CHANGE_TRACKING"; internal const string ChangeTrackingContext = "CHANGE_TRACKING_CONTEXT"; + internal const string Chapter = "CHAPTER"; internal const string Char = "CHAR"; internal const string CharacterSet = "CHARACTER_SET"; internal const string CheckConstraints = "CHECK_CONSTRAINTS"; @@ -214,6 +215,7 @@ internal static class CodeGenerationSupporter internal const string ChecksumAgg = "CHECKSUM_AGG"; internal const string ChunkSize = "CHUNK_SIZE"; internal const string ChunkType = "CHUNK_TYPE"; + internal const string ChunkUsing = "CHUNK_USING"; internal const string ModularSum = "MODULAR_SUM"; internal const string Classifier = "CLASSIFIER"; internal const string Classification = "CLASSIFICATION"; @@ -394,6 +396,7 @@ internal static class CodeGenerationSupporter internal const string Extension = "EXTENSION"; internal const string External = "EXTERNAL"; internal const string ExternalAccess = "EXTERNAL_ACCESS"; + internal const string ExternalModel = "EXTERNAL_MODEL"; internal const string ExternalMonitor = "EXTERNAL_MONITOR"; internal const string Extract = "EXTRACT"; internal const string FailOperation = "FAIL_OPERATION"; @@ -465,6 +468,7 @@ internal static class CodeGenerationSupporter internal const string Full = "FULL"; internal const string FullScan = "FULLSCAN"; internal const string Fulltext = "FULLTEXT"; + internal const string FulltextStopList = "FULLTEXT_STOPLIST"; internal const string General = "GENERAL"; internal const string GenerateSeries = "GENERATE_SERIES"; internal const string Generated = "GENERATED"; @@ -499,6 +503,7 @@ internal static class CodeGenerationSupporter internal const string Hidden = "HIDDEN"; internal const string High = "HIGH"; internal const string Hint = "HINT"; + internal const string Hybrid = "HYBRID"; internal const string Histogram = "HISTOGRAM"; internal const string HistogramSteps = "HISTOGRAM_STEPS"; internal const string HistoryRetentionPeriod = "HISTORY_RETENTION_PERIOD"; @@ -536,6 +541,7 @@ internal static class CodeGenerationSupporter internal const string Intermediate = "INTERMEDIATE"; internal const string IntervalLengthMinutes = "INTERVAL_LENGTH_MINUTES"; internal const string Insensitive = "INSENSITIVE"; + internal const string InvokeExternalApi = "INVOKE_EXTERNAL_API"; internal const string IRowset = "IROWSET"; internal const string Isolation = "ISOLATION"; internal const string Job = "JOB"; @@ -755,6 +761,7 @@ internal static class CodeGenerationSupporter internal const string PageCount = "PAGECOUNT"; internal const string PageVerify = "PAGE_VERIFY"; internal const string PagLock = "PAGLOCK"; + internal const string Paragraph = "PARAGRAPH"; internal const string Param = "PARAM"; internal const string Parameter = "PARAMETER"; internal const string Parameters = "PARAMETERS"; @@ -926,6 +933,7 @@ internal static class CodeGenerationSupporter internal const string Scroll = "SCROLL"; internal const string ScrollLocks = "SCROLL_LOCKS"; internal const string Search = "SEARCH"; + internal const string SearchType = "SEARCH_TYPE"; internal const string Secondary = "SECONDARY"; internal const string SecondaryRole = "SECONDARY_ROLE"; internal const string Seconds = "SECONDS"; @@ -935,6 +943,8 @@ internal static class CodeGenerationSupporter internal const string SecurityLog = "SECURITY_LOG"; internal const string Selective = "SELECTIVE"; internal const string Self = "SELF"; + internal const string Semantic = "SEMANTIC"; + internal const string Sentence = "SENTENCE"; internal const string SemiColon = ";"; internal const string Send = "SEND"; internal const string Sensitivity = "SENSITIVITY"; @@ -1123,6 +1133,7 @@ internal static class CodeGenerationSupporter internal const string Varp = "VARP"; internal const string VDevNo = "VDEVNO"; internal const string Vector = "Vector"; + internal const string VectorIndex = "VECTOR_INDEX"; internal const string VectorSearch = "VECTOR_SEARCH"; internal const string Verbose = "VERBOSE"; internal const string VerboseLogging = "VerboseLogging"; diff --git a/SqlScriptDom/Parser/TSql/SemanticIndexChunkOptionKind.cs b/SqlScriptDom/Parser/TSql/SemanticIndexChunkOptionKind.cs new file mode 100644 index 00000000..c3a634ac --- /dev/null +++ b/SqlScriptDom/Parser/TSql/SemanticIndexChunkOptionKind.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + + + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ +#pragma warning disable 1591 + + /// + /// The possible values for semantic index chunk options. + /// + public enum SemanticIndexChunkOptionKind + { + Type = 0, + Size = 1, + Overlap = 2 + } + +#pragma warning restore 1591 +} diff --git a/SqlScriptDom/Parser/TSql/SemanticIndexSearchType.cs b/SqlScriptDom/Parser/TSql/SemanticIndexSearchType.cs new file mode 100644 index 00000000..d3d956fc --- /dev/null +++ b/SqlScriptDom/Parser/TSql/SemanticIndexSearchType.cs @@ -0,0 +1,25 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + + + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ +#pragma warning disable 1591 + + /// + /// The possible values for semantic index search type. + /// + public enum SemanticIndexSearchType + { + NotSpecified = 0, + Vector = 1, + Fulltext = 2, + Hybrid = 3 + } + +#pragma warning restore 1591 +} diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index f52ab337..ae426b05 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -889,6 +889,9 @@ create2005Statements returns [TSqlStatement vResult = null] | {NextTokenMatches(CodeGenerationSupporter.Vector)}? vResult=createVectorIndexStatement[null, null] + | + {NextTokenMatches(CodeGenerationSupporter.Semantic)}? + vResult=createSemanticIndexStatement | {NextTokenMatches(CodeGenerationSupporter.Contract)}? vResult=createContractStatement @@ -17132,6 +17135,232 @@ createVectorIndexStatement [IToken tUnique, bool? isClustered] returns [CreateVe )? ; +createSemanticIndexStatement returns [CreateSemanticIndexStatement vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + SchemaObjectName vSchemaObjectName; + SemanticIndexColumn vColumn; + FileGroupOrPartitionScheme vFileGroupOrPartitionScheme; +} + : tSemantic:Identifier tIndex:Index vIdentifier=identifier + { + Match(tSemantic, CodeGenerationSupporter.Semantic); + vResult.Name = vIdentifier; + } + tOn:On vSchemaObjectName=schemaObjectThreePartName + { + vResult.OnName = vSchemaObjectName; + } + LeftParenthesis + vColumn=semanticIndexColumnDefinition + { + AddAndUpdateTokenInfo(vResult, vResult.Columns, vColumn); + } + ( + Comma vColumn=semanticIndexColumnDefinition + { + AddAndUpdateTokenInfo(vResult, vResult.Columns, vColumn); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } + ( + // Greedy due to conflict with withCommonTableExpressionsAndXmlNamespaces + options {greedy = true; } : + With LeftParenthesis + semanticIndexWithOptions[vResult] + RightParenthesis + )? + ( + On vFileGroupOrPartitionScheme=filegroupOrPartitionScheme + { + vResult.OnFileGroupOrPartitionScheme = vFileGroupOrPartitionScheme; + } + )? + { + // Validate that EXTERNAL_MODEL is specified for vector/hybrid columns + ValidateSemanticIndexExternalModel(vResult); + } + ; + +semanticIndexColumnDefinition returns [SemanticIndexColumn vResult = FragmentFactory.CreateFragment()] +{ + Identifier vIdentifier; + IdentifierOrValueExpression vValue; +} + : vIdentifier=identifier + { + vResult.ColumnName = vIdentifier; + } + ( + {NextTokenMatches(CodeGenerationSupporter.SearchType)}? + tSearchType:Identifier EqualsSign tSearchTypeValue:Identifier + { + Match(tSearchType, CodeGenerationSupporter.SearchType); + if (TryMatch(tSearchTypeValue, CodeGenerationSupporter.Vector)) + vResult.SearchType = SemanticIndexSearchType.Vector; + else if (TryMatch(tSearchTypeValue, CodeGenerationSupporter.Fulltext)) + vResult.SearchType = SemanticIndexSearchType.Fulltext; + else + { + Match(tSearchTypeValue, CodeGenerationSupporter.Hybrid); + vResult.SearchType = SemanticIndexSearchType.Hybrid; + } + } + )? + ( + {NextTokenMatches(CodeGenerationSupporter.Type)}? + Identifier Column vIdentifier=identifier + { + vResult.TypeColumnName = vIdentifier; + } + )? + ( + {NextTokenMatches(CodeGenerationSupporter.Language)}? + tLang:Identifier vValue=stringOrIdentifier + { + Match(tLang, CodeGenerationSupporter.Language); + vResult.Language = vValue; + } + )? + ( + {NextTokenMatches(CodeGenerationSupporter.ChunkUsing)}? + tChunkUsing:Identifier LeftParenthesis + { + Match(tChunkUsing, CodeGenerationSupporter.ChunkUsing); + } + semanticIndexChunkOptions[vResult] + RightParenthesis + )? + ; + +semanticIndexChunkOptions [SemanticIndexColumn vParent] +{ + SemanticIndexChunkOption vOption; +} + : vOption=semanticIndexChunkOption + { + AddAndUpdateTokenInfo(vParent, vParent.ChunkOptions, vOption); + } + ( + Comma vOption=semanticIndexChunkOption + { + AddAndUpdateTokenInfo(vParent, vParent.ChunkOptions, vOption); + } + )* + ; + +semanticIndexChunkOption returns [SemanticIndexChunkOption vResult = FragmentFactory.CreateFragment()] +{ + IdentifierOrValueExpression vValue; +} + : tOption:Identifier EqualsSign vValue=identifierOrInteger + { + if (TryMatch(tOption, CodeGenerationSupporter.Type)) + vResult.OptionKind = SemanticIndexChunkOptionKind.Type; + else if (TryMatch(tOption, CodeGenerationSupporter.Size)) + vResult.OptionKind = SemanticIndexChunkOptionKind.Size; + else + { + Match(tOption, CodeGenerationSupporter.Overlap); + vResult.OptionKind = SemanticIndexChunkOptionKind.Overlap; + } + vResult.Value = vValue; + } + ; + +semanticIndexWithOptions [CreateSemanticIndexStatement vParent] + : semanticIndexWithOption[vParent] + ( + Comma semanticIndexWithOption[vParent] + )* + ; + +semanticIndexWithOption [CreateSemanticIndexStatement vParent] +{ + IndexOption vIndexOption; + Identifier vIdentifier; + StringLiteral vStringLiteral; +} + : + ( + {NextTokenMatches(CodeGenerationSupporter.ExternalModel)}? + tExtModel:Identifier EqualsSign + { + Match(tExtModel, CodeGenerationSupporter.ExternalModel); + } + ( + LeftParenthesis vIdentifier=identifier RightParenthesis + { + vParent.ExternalModelName = vIdentifier; + } + | + vIdentifier=identifier + { + vParent.ExternalModelName = vIdentifier; + } + ) + ( + LeftParenthesis tParams:Identifier EqualsSign vStringLiteral=stringLiteral RightParenthesis + { + Match(tParams, CodeGenerationSupporter.Parameters); + vParent.ExternalModelParameters = vStringLiteral; + } + )? + | + {NextTokenMatches(CodeGenerationSupporter.VectorIndex)}? + tVecIdx:Identifier LeftParenthesis + { + Match(tVecIdx, CodeGenerationSupporter.VectorIndex); + } + vIndexOption=semanticIndexVectorOption + { + AddAndUpdateTokenInfo(vParent, vParent.VectorIndexOptions, vIndexOption); + } + ( + Comma vIndexOption=semanticIndexVectorOption + { + AddAndUpdateTokenInfo(vParent, vParent.VectorIndexOptions, vIndexOption); + } + )* + RightParenthesis + | + {NextTokenMatches(CodeGenerationSupporter.FulltextStopList)}? + tStoplist:Identifier EqualsSign + { + Match(tStoplist, CodeGenerationSupporter.FulltextStopList); + } + ( + tOff:Off + { + StopListFullTextIndexOption vStopOpt = FragmentFactory.CreateFragment(); + vStopOpt.OptionKind = FullTextIndexOptionKind.StopList; + vStopOpt.IsOff = true; + UpdateTokenInfo(vStopOpt, tStoplist); + UpdateTokenInfo(vStopOpt, tOff); + vParent.FulltextStoplistOption = vStopOpt; + } + | + vIdentifier=identifier + { + StopListFullTextIndexOption vStopOpt = FragmentFactory.CreateFragment(); + vStopOpt.OptionKind = FullTextIndexOptionKind.StopList; + vStopOpt.IsOff = false; + vStopOpt.StopListName = vIdentifier; + UpdateTokenInfo(vStopOpt, tStoplist); + vParent.FulltextStoplistOption = vStopOpt; + } + ) + | + vIndexOption=indexOption + { + AddAndUpdateTokenInfo(vParent, vParent.IndexOptions, vIndexOption); + } + ) + ; + indexKeyColumnList[CreateIndexStatement vParent] { ColumnWithSortOrder vColumnWithSortOrder; @@ -28283,6 +28512,15 @@ xmlCompressionOption returns [XmlCompressionOption vResult = FragmentFactory.Cre )? ; +semanticIndexVectorOption returns [IndexOption vResult = null] + : + {NextTokenMatches(CodeGenerationSupporter.Metric)}? + vResult=vectorMetricOption + | + {NextTokenMatches(CodeGenerationSupporter.Type)}? + vResult=vectorTypeOption + ; + vectorMetricOption returns [VectorMetricIndexOption vResult = FragmentFactory.CreateFragment()] : tMetric:Identifier EqualsSign tMetricValue:AsciiStringLiteral { diff --git a/SqlScriptDom/Parser/TSql/TSql180ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql180ParserBaseInternal.cs index 89674e5d..5f3d827e 100644 --- a/SqlScriptDom/Parser/TSql/TSql180ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql180ParserBaseInternal.cs @@ -70,6 +70,27 @@ protected SecurityObjectKind ParseSecurityObjectKindTSql180(Identifier identifie return TSql170ParserBaseInternal.ParseSecurityObjectKind(identifier1, identifier2); } } + + /// + /// Validates that EXTERNAL_MODEL is specified when CREATE SEMANTIC INDEX contains vector or hybrid columns. + /// Vector and hybrid search types require an external model for embeddings. + /// NotSpecified defaults to Vector, so EXTERNAL_MODEL is required unless ALL columns are explicitly Fulltext. + /// + /// The CREATE SEMANTIC INDEX statement to validate. + protected static void ValidateSemanticIndexExternalModel(CreateSemanticIndexStatement statement) + { + // EXTERNAL_MODEL is NOT required only when ALL columns are explicitly FULLTEXT + // If any column is Vector, Hybrid, or NotSpecified (defaults to Vector), EXTERNAL_MODEL is required + bool allColumnsAreFulltext = statement.Columns.All(col => + col.SearchType == SemanticIndexSearchType.Fulltext); + + // EXTERNAL_MODEL is required unless all columns are explicitly fulltext + if (!allColumnsAreFulltext && statement.ExternalModelName == null) + { + ThrowParseErrorException("SQL46144", statement, + TSqlParserResource.SQL46144Message, "EXTERNAL_MODEL"); + } + } } } - + diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index e4a7f24d..4ad40b85 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -730,7 +730,9 @@ lastStatement returns [TSqlStatement vResult = null] | vResult=createRuleStatement | vResult=createViewStatement | vResult=alterViewStatement + | (Create Function schemaObjectNonEmptyTwoPartName (LeftParenthesis (functionParameter (Comma functionParameter)*)? RightParenthesis)? (Identifier scalarDataType)? As External) => vResult=createExternalFunctionStatement | vResult=createFunctionStatement + | (Alter Function schemaObjectNonEmptyTwoPartName (LeftParenthesis (functionParameter (Comma functionParameter)*)? RightParenthesis)? (Identifier scalarDataType)? As External) => vResult=alterExternalFunctionStatement | vResult=alterFunctionStatement | vResult=createSchemaStatement | vResult=createIdentifierStatement @@ -770,7 +772,8 @@ alterIdentifierStatement returns [TSqlStatement vResult] createOrAlterStatements returns [TSqlStatement vResult] : tCreate:Create Or Alter ( - vResult = createOrAlterFunctionStatement + (Function schemaObjectNonEmptyTwoPartName (LeftParenthesis (functionParameter (Comma functionParameter)*)? RightParenthesis)? (Identifier scalarDataType)? As External) => vResult = createOrAlterExternalFunctionStatement + | vResult = createOrAlterFunctionStatement | vResult = createOrAlterProcedureStatement | vResult = createOrAlterTriggerStatement | vResult = createOrAlterViewStatement @@ -12996,6 +12999,83 @@ createOrAlterFunctionStatement returns [CreateOrAlterFunctionStatement vResult = } ; +createExternalFunctionStatement returns [CreateExternalFunctionStatement vResult = this.FragmentFactory.CreateFragment()] + : tCreate:Create + { + UpdateTokenInfo(vResult, tCreate); + } + externalFunctionStatementBody[vResult] + ; + +alterExternalFunctionStatement returns [AlterExternalFunctionStatement vResult = this.FragmentFactory.CreateFragment()] + : tAlter:Alter + { + UpdateTokenInfo(vResult, tAlter); + } + externalFunctionStatementBody[vResult] + ; + +createOrAlterExternalFunctionStatement returns [CreateOrAlterExternalFunctionStatement vResult = this.FragmentFactory.CreateFragment()] + : externalFunctionStatementBody[vResult] + ; + +externalFunctionStatementBody[ExternalFunctionStatement vResult] +{ + SchemaObjectName vName; + SchemaObjectName vExternalName; + DataTypeReference vReturnType; + ProcedureParameter vParameter; +} + : tFunction:Function + { + UpdateTokenInfo(vResult, tFunction); + } + vName=schemaObjectNonEmptyTwoPartName + { + vResult.Name = vName; + } + ( + LeftParenthesis + ( + vParameter=functionParameter + { + AddAndUpdateTokenInfo(vResult, vResult.Parameters, vParameter); + } + ( Comma vParameter=functionParameter + { + AddAndUpdateTokenInfo(vResult, vResult.Parameters, vParameter); + } + )* + )? + RightParenthesis + )? + ( + {NextTokenMatches(CodeGenerationSupporter.Returns)}? + tReturns:Identifier vReturnType=scalarDataType + { + Match(tReturns, CodeGenerationSupporter.Returns); + UpdateTokenInfo(vResult, tReturns); + vResult.ReturnType = vReturnType; + } + )? + tAs:As + { + UpdateTokenInfo(vResult, tAs); + } + tExternal:External + { + UpdateTokenInfo(vResult, tExternal); + } + tExternalFunction:Function + { + UpdateTokenInfo(vResult, tExternalFunction); + } + vExternalName=schemaObjectNonEmptyTwoPartName + { + vResult.ExternalName = vExternalName; + } + ; + functionStatementBody[FunctionStatementBody vResult, out bool vParseErrorOccurred] { SchemaObjectName vSchemaObjectName; @@ -31491,6 +31571,9 @@ expressionPrimary [ExpressionFlags expressionFlags] returns [PrimaryExpression v | {NextTokenMatches(CodeGenerationSupporter.AITranslate) && (LA(2) == LeftParenthesis)}? vResult=aiTranslateFunctionCall + | + {NextTokenMatches(CodeGenerationSupporter.InvokeExternalApi) && (LA(2) == LeftParenthesis)}? + vResult=invokeExternalApiFunctionCall | (Identifier LeftParenthesis)=> vResult=builtInFunctionCall @@ -32306,6 +32389,43 @@ aiTranslateFunctionCall returns [AITranslateFunctionCall vResult = this.Fragment RightParenthesis ; +// INVOKE_EXTERNAL_API('', '' [, [, ... ]]) +// functionSetName and functionName must be string literals. +// Remaining arguments are optional scalar expressions. +invokeExternalApiFunctionCall + returns [InvokeExternalApiFunctionCall vResult = this.FragmentFactory.CreateFragment()] +{ + StringLiteral vFunctionSetName; + StringLiteral vFunctionName; + ScalarExpression vArg; +} + : + tFunc:Identifier LeftParenthesis + { + Match(tFunc, CodeGenerationSupporter.InvokeExternalApi); + UpdateTokenInfo(vResult, tFunc); + } + vFunctionSetName=stringLiteral + { + vResult.FunctionSetName = vFunctionSetName; + } + Comma + vFunctionName=stringLiteral + { + vResult.FunctionName = vFunctionName; + } + ( + Comma vArg=expression + { + AddAndUpdateTokenInfo(vResult, vResult.Arguments, vArg); + } + )* + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } + ; + // TODO, olegr: Add more checks for allowed functions here - there are quite some in SQL Server parser builtInFunctionCall returns [FunctionCall vResult = FragmentFactory.CreateFragment()] { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSemanticIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSemanticIndexStatement.cs new file mode 100644 index 00000000..c3333222 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSemanticIndexStatement.cs @@ -0,0 +1,208 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(CreateSemanticIndexStatement node) + { + GenerateKeyword(TSqlTokenType.Create); + + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Semantic); + + GenerateSpaceAndKeyword(TSqlTokenType.Index); + + // name + GenerateSpaceAndFragmentIfNotNull(node.Name); + + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.On); + GenerateSpaceAndFragmentIfNotNull(node.OnName); + + // Column definitions + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + for (int i = 0; i < node.Columns.Count; i++) + { + if (i > 0) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + } + GenerateFragmentIfNotNull(node.Columns[i]); + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + + // WITH clause + bool hasWithOption = node.ExternalModelName != null || + (node.VectorIndexOptions != null && node.VectorIndexOptions.Count > 0) || + node.FulltextStoplistOption != null || + (node.IndexOptions != null && node.IndexOptions.Count > 0); + + if (hasWithOption) + { + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.With); + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + bool first = true; + + if (node.ExternalModelName != null) + { + GenerateIdentifier(CodeGenerationSupporter.ExternalModel); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + GenerateFragmentIfNotNull(node.ExternalModelName); + if (node.ExternalModelParameters != null) + { + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateIdentifier(CodeGenerationSupporter.Parameters); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + GenerateFragmentIfNotNull(node.ExternalModelParameters); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + first = false; + } + + if (node.VectorIndexOptions != null && node.VectorIndexOptions.Count > 0) + { + if (!first) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + } + GenerateIdentifier(CodeGenerationSupporter.VectorIndex); + GenerateSpace(); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateCommaSeparatedList(node.VectorIndexOptions); + GenerateSymbol(TSqlTokenType.RightParenthesis); + first = false; + } + + if (node.FulltextStoplistOption != null) + { + if (!first) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + } + GenerateIdentifier(CodeGenerationSupporter.FulltextStopList); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + if (node.FulltextStoplistOption.IsOff) + { + GenerateKeyword(TSqlTokenType.Off); + } + else + { + GenerateFragmentIfNotNull(node.FulltextStoplistOption.StopListName); + } + first = false; + } + + if (node.IndexOptions != null && node.IndexOptions.Count > 0) + { + foreach (var option in node.IndexOptions) + { + if (!first) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + } + GenerateFragmentIfNotNull(option); + first = false; + } + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + + if (node.OnFileGroupOrPartitionScheme != null) + { + NewLineAndIndent(); + GenerateKeyword(TSqlTokenType.On); + + GenerateSpaceAndFragmentIfNotNull(node.OnFileGroupOrPartitionScheme); + } + } + + public override void ExplicitVisit(SemanticIndexColumn node) + { + GenerateFragmentIfNotNull(node.ColumnName); + + if (node.SearchType != SemanticIndexSearchType.NotSpecified) + { + GenerateSpace(); + GenerateIdentifier(CodeGenerationSupporter.SearchType); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + switch (node.SearchType) + { + case SemanticIndexSearchType.Vector: + GenerateIdentifier(CodeGenerationSupporter.Vector); + break; + case SemanticIndexSearchType.Fulltext: + GenerateIdentifier(CodeGenerationSupporter.Fulltext); + break; + case SemanticIndexSearchType.Hybrid: + GenerateIdentifier(CodeGenerationSupporter.Hybrid); + break; + } + } + + if (node.TypeColumnName != null) + { + GenerateSpace(); + GenerateIdentifier(CodeGenerationSupporter.Type); + GenerateSpaceAndKeyword(TSqlTokenType.Column); + GenerateSpaceAndFragmentIfNotNull(node.TypeColumnName); + } + + if (node.Language != null) + { + GenerateSpace(); + GenerateIdentifier(CodeGenerationSupporter.Language); + GenerateSpaceAndFragmentIfNotNull(node.Language); + } + + if (node.ChunkOptions != null && node.ChunkOptions.Count > 0) + { + GenerateSpace(); + GenerateIdentifier(CodeGenerationSupporter.ChunkUsing); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateCommaSeparatedList(node.ChunkOptions); + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } + + public override void ExplicitVisit(SemanticIndexChunkOption node) + { + switch (node.OptionKind) + { + case SemanticIndexChunkOptionKind.Type: + GenerateIdentifier(CodeGenerationSupporter.Type); + break; + case SemanticIndexChunkOptionKind.Size: + GenerateIdentifier(CodeGenerationSupporter.Size); + break; + case SemanticIndexChunkOptionKind.Overlap: + GenerateIdentifier(CodeGenerationSupporter.Overlap); + break; + } + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpace(); + GenerateFragmentIfNotNull(node.Value); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs new file mode 100644 index 00000000..8ab01c63 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs @@ -0,0 +1,52 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + public override void ExplicitVisit(CreateExternalFunctionStatement node) + { + GenerateKeyword(TSqlTokenType.Create); + GenerateExternalFunctionStatementBody(node); + } + + public override void ExplicitVisit(AlterExternalFunctionStatement node) + { + GenerateKeyword(TSqlTokenType.Alter); + GenerateExternalFunctionStatementBody(node); + } + + public override void ExplicitVisit(CreateOrAlterExternalFunctionStatement node) + { + GenerateKeyword(TSqlTokenType.Create); + GenerateSpaceAndKeyword(TSqlTokenType.Or); + GenerateSpaceAndKeyword(TSqlTokenType.Alter); + GenerateExternalFunctionStatementBody(node); + } + + private void GenerateExternalFunctionStatementBody(ExternalFunctionStatement node) + { + GenerateSpaceAndKeyword(TSqlTokenType.Function); + GenerateSpaceAndFragmentIfNotNull(node.Name); + if (node.Parameters != null && node.Parameters.Count > 0) + { + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.Parameters); + } + if (node.ReturnType != null) + { + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Returns); + GenerateSpaceAndFragmentIfNotNull(node.ReturnType); + } + GenerateSpaceAndKeyword(TSqlTokenType.As); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.External); + GenerateSpaceAndKeyword(TSqlTokenType.Function); + GenerateSpaceAndFragmentIfNotNull(node.ExternalName); + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs new file mode 100644 index 00000000..8b6e8188 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs @@ -0,0 +1,56 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; + +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + /// + /// Emits an INVOKE_EXTERNAL_API function call like + /// INVOKE_EXTERNAL_API('FunctionSetName', 'FunctionName' [, arg1 [, arg2 ...]]). + /// FunctionSetName and FunctionName are required string literals; remaining + /// arguments are optional scalar expressions. + /// + /// Expression node to generate + public override void ExplicitVisit(InvokeExternalApiFunctionCall node) + { + if (node.FunctionSetName == null) + { + throw new InvalidOperationException("InvokeExternalApiFunctionCall.FunctionSetName is required."); + } + + if (node.FunctionName == null) + { + throw new InvalidOperationException("InvokeExternalApiFunctionCall.FunctionName is required."); + } + + GenerateIdentifier(CodeGenerationSupporter.InvokeExternalApi); + GenerateSymbol(TSqlTokenType.LeftParenthesis); + + GenerateFragmentIfNotNull(node.FunctionSetName); + + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + GenerateFragmentIfNotNull(node.FunctionName); + + if (node.Arguments != null) + { + for (int i = 0; i < node.Arguments.Count; i++) + { + GenerateSymbol(TSqlTokenType.Comma); + GenerateSpace(); + GenerateFragmentIfNotNull(node.Arguments[i]); + } + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + } +} diff --git a/Test/SqlDom/Baselines180/CreateSemanticIndexTests180.sql b/Test/SqlDom/Baselines180/CreateSemanticIndexTests180.sql new file mode 100644 index 00000000..b853da18 --- /dev/null +++ b/Test/SqlDom/Baselines180/CreateSemanticIndexTests180.sql @@ -0,0 +1,78 @@ +CREATE SEMANTIC INDEX SI_Basic + ON dbo.Documents (content) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Vector + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Multi + ON dbo.books (summary SEARCH_TYPE = VECTOR, title SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Hybrid + ON dbo.books (content SEARCH_TYPE = HYBRID, title SEARCH_TYPE = FULLTEXT) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_TypeCol + ON dbo.Documents (content TYPE COLUMN content_type) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Lang + ON dbo.Documents (content LANGUAGE English) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Chunk + ON dbo.Documents (content CHUNK_USING(TYPE = paragraph, SIZE = 500, OVERLAP = 50)) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Full + ON dbo.Documents (content SEARCH_TYPE = VECTOR TYPE COLUMN content_type LANGUAGE English CHUNK_USING(TYPE = sentence, SIZE = 1000)) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_Model + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = OpenAIModel); + +CREATE SEMANTIC INDEX SI_ModelParen + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = MyModel); + +CREATE SEMANTIC INDEX SI_ModelParams + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = MyModel (PARAMETERS = '{"dimension": 1536}')); + +CREATE SEMANTIC INDEX SI_VecOpts + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = OpenAIModel, VECTOR_INDEX (METRIC = 'COSINE')); + +CREATE SEMANTIC INDEX SI_StopOff + ON dbo.books (content SEARCH_TYPE = FULLTEXT) + WITH (FULLTEXT_STOPLIST = OFF); + +CREATE SEMANTIC INDEX SI_StopSys + ON dbo.books (content SEARCH_TYPE = FULLTEXT) + WITH (FULLTEXT_STOPLIST = SYSTEM); + +CREATE SEMANTIC INDEX SI_StopName + ON dbo.books (content SEARCH_TYPE = FULLTEXT) + WITH (FULLTEXT_STOPLIST = MyStoplist); + +CREATE SEMANTIC INDEX SI_MaxDop + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = OpenAIModel, MAXDOP = 4); + +CREATE SEMANTIC INDEX SI_DropEx + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = OpenAIModel, DROP_EXISTING = ON); + +CREATE SEMANTIC INDEX SI_FG + ON dbo.books (summary SEARCH_TYPE = VECTOR) + WITH (EXTERNAL_MODEL = OpenAIModel) + ON [PRIMARY]; + +CREATE SEMANTIC INDEX SI_Complete + ON dbo.books (summary SEARCH_TYPE = VECTOR, title SEARCH_TYPE = FULLTEXT CHUNK_USING(TYPE = fixed, SIZE = 200, OVERLAP = 25)) + WITH (EXTERNAL_MODEL = OpenAIModel (PARAMETERS = '{"api_key": "test"}'), VECTOR_INDEX (METRIC = 'COSINE', TYPE = 'DISKANN'), FULLTEXT_STOPLIST = SYSTEM, MAXDOP = 8, DROP_EXISTING = OFF) + ON [PRIMARY]; + diff --git a/Test/SqlDom/BaselinesFabricDW/ExternalFunctionTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/ExternalFunctionTestsFabricDW.sql new file mode 100644 index 00000000..6920cc20 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/ExternalFunctionTestsFabricDW.sql @@ -0,0 +1,49 @@ +CREATE FUNCTION dbo.MyExternalFn AS EXTERNAL FUNCTION mySet.myFn; + +GO +ALTER FUNCTION dbo.MyExternalFn AS EXTERNAL FUNCTION mySet.anotherFn; + +GO +CREATE OR ALTER FUNCTION dbo.MyExternalFn AS EXTERNAL FUNCTION mySet.myFn; + +GO +CREATE FUNCTION MyFn AS EXTERNAL FUNCTION myFn; + +GO +CREATE FUNCTION dbo.MyExternalFn RETURNS MONEY AS EXTERNAL FUNCTION mySet.myFn; + +GO +ALTER FUNCTION dbo.MyExternalFn RETURNS NVARCHAR (100) AS EXTERNAL FUNCTION mySet.myFn; + +GO +CREATE OR ALTER FUNCTION dbo.MyExternalFn RETURNS INT AS EXTERNAL FUNCTION mySet.myFn; + +GO +CREATE FUNCTION dbo.MyExternalFn (@x INT) AS EXTERNAL FUNCTION mySet.myFn; + +GO +CREATE FUNCTION dbo.MyExternalFn (@x INT, @y NVARCHAR (50)) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn; + +GO +ALTER FUNCTION dbo.MyExternalFn (@x INT) RETURNS BIGINT AS EXTERNAL FUNCTION mySet.myFn; + +GO +CREATE OR ALTER FUNCTION dbo.MyExternalFn (@x INT) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn; + +GO +DROP FUNCTION dbo.MyExternalFn; + +GO +SELECT dbo.MyExternalFn(); + +GO +SELECT dbo.MyExternalFn(42, N'hello'); + +GO +DECLARE @v AS INT = 1; + +SELECT dbo.MyExternalFn(@v, 'const'); + +GO +SELECT dbo.MyExternalFn(t.col1, t.col2) AS r +FROM dbo.t AS t; diff --git a/Test/SqlDom/BaselinesFabricDW/InvokeExternalApiTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/InvokeExternalApiTestsFabricDW.sql new file mode 100644 index 00000000..68422135 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/InvokeExternalApiTestsFabricDW.sql @@ -0,0 +1,27 @@ +SELECT INVOKE_EXTERNAL_API('myFunctionSet', 'myFunction'); + + +GO +SELECT INVOKE_EXTERNAL_API('myFunctionSet', 'myFunction', 42); + + +GO +DECLARE @v AS INT = 7; + +SELECT INVOKE_EXTERNAL_API(N'mySet', N'doStuff', @v, 'literal', 1 + 2, NULL); + + +GO +ALTER FUNCTION dbo.TestInvokeExternalApi +( ) +RETURNS NVARCHAR (MAX) +AS +BEGIN + RETURN (INVOKE_EXTERNAL_API('mySet', 'myFn', 'arg1')); +END + + +GO +SELECT 1 +FROM dbo.t +WHERE INVOKE_EXTERNAL_API('mySet', 'isAllowed', col1) = 1; diff --git a/Test/SqlDom/Only180SyntaxTests.cs b/Test/SqlDom/Only180SyntaxTests.cs index cd8746db..9be98076 100644 --- a/Test/SqlDom/Only180SyntaxTests.cs +++ b/Test/SqlDom/Only180SyntaxTests.cs @@ -14,7 +14,8 @@ public partial class SqlDomTests { new ParserTest180("AutomaticIndexCompactionTests180.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2), new ParserTest180("TrimFromReturnTests160.sql"), - new ParserTest180("PersistSamplePercentStatisticsTests130.sql") + new ParserTest180("PersistSamplePercentStatisticsTests130.sql"), + new ParserTest180("CreateSemanticIndexTests180.sql"), }; private static readonly ParserTest[] SqlAzure180_TestInfos = diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index 8898e811..483e08ef 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -25,6 +25,8 @@ public partial class SqlDomTests new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("InvokeExternalApiTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("ExternalFunctionTestsFabricDW.sql", nErrors80: 12, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11, nErrors170: 11, nErrors180: 0), }; [TestMethod] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index ce5ab88a..faeb5a68 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.IO; using System.Linq; using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -4632,6 +4633,82 @@ public void CreateJsonIndexStatementErrorTest() new ParserErrorInfo(26, "SQL46010", "(")); } + /// + /// Negative tests for CREATE SEMANTIC INDEX statement + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CreateSemanticIndexStatementErrorTest() + { + // Semantic Index syntax should not be supported in SQL Server versions prior to 180 + ParserTestUtils.ErrorTest170("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + ParserTestUtils.ErrorTest160("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + ParserTestUtils.ErrorTest150("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + ParserTestUtils.ErrorTest140("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + ParserTestUtils.ErrorTest130("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + ParserTestUtils.ErrorTest120("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + ParserTestUtils.ErrorTest110("CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(7, "SQL46010", "SEMANTIC")); + + // Test malformed syntax in TSql180 + TSql180Parser parser180 = new TSql180Parser(true); + + // Missing index name + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX ON dbo.t1 (col1)", + new ParserErrorInfo(22, "SQL46010", "ON")); + + // Missing table name + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON (col1)", + new ParserErrorInfo(30, "SQL46010", "(")); + + // Missing column list + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1", + new ParserErrorInfo(36, "SQL46029")); + + // Empty column list + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 ()", + new ParserErrorInfo(38, "SQL46010", ")")); + + // Invalid SEARCH_TYPE value + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 SEARCH_TYPE=invalid)", + new ParserErrorInfo(55, "SQL46005", "HYBRID", "invalid")); + + // Invalid CHUNK_USING option + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 CHUNK_USING(BADOPT = 100))", + new ParserErrorInfo(55, "SQL46005", "OVERLAP", "BADOPT")); + + // EXTERNAL_MODEL is required when SEARCH_TYPE is not specified (defaults to vector) + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1)", + new ParserErrorInfo(22, "SQL46144", "EXTERNAL_MODEL")); + + // EXTERNAL_MODEL is required for vector columns + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 SEARCH_TYPE = VECTOR)", + new ParserErrorInfo(22, "SQL46144", "EXTERNAL_MODEL")); + + // EXTERNAL_MODEL is required for hybrid columns + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 SEARCH_TYPE = HYBRID)", + new ParserErrorInfo(22, "SQL46144", "EXTERNAL_MODEL")); + + // EXTERNAL_MODEL is required when at least one column is vector + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 SEARCH_TYPE = FULLTEXT, col2 SEARCH_TYPE = VECTOR)", + new ParserErrorInfo(22, "SQL46144", "EXTERNAL_MODEL")); + + // EXTERNAL_MODEL is required when at least one column has no SEARCH_TYPE (defaults to vector) + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 SEARCH_TYPE = FULLTEXT, col2)", + new ParserErrorInfo(22, "SQL46144", "EXTERNAL_MODEL")); + + // Multiple vector columns without EXTERNAL_MODEL + ParserTestUtils.ErrorTest(parser180, "CREATE SEMANTIC INDEX idx1 ON dbo.t1 (col1 SEARCH_TYPE = VECTOR, col2 SEARCH_TYPE = VECTOR)", + new ParserErrorInfo(22, "SQL46144", "EXTERNAL_MODEL")); + } + /// /// Check that the value of MAXDOP index option is within range /// @@ -7868,6 +7945,45 @@ public void AiTranslateNegativeTestsFabricDw() new ParserErrorInfo(28, "SQL46010", ",")); } + /// + /// Negative tests for CREATE/ALTER FUNCTION ... AS EXTERNAL FUNCTION syntax in Fabric DW. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void ExternalFunctionNegativeTestsFabricDW() + { + // Missing external name after EXTERNAL FUNCTION + ParserTestUtils.ErrorTestFabricDW( + "CREATE FUNCTION dbo.f AS EXTERNAL FUNCTION", + new ParserErrorInfo(42, "SQL46029")); + + // Missing FUNCTION keyword after EXTERNAL + ParserTestUtils.ErrorTestFabricDW( + "CREATE FUNCTION dbo.f AS EXTERNAL mySet.myFn", + new ParserErrorInfo(34, "SQL46010", "mySet")); + + // Three-part external name not allowed + ParserTestUtils.ErrorTestFabricDW( + "CREATE FUNCTION dbo.f AS EXTERNAL FUNCTION db.mySet.myFn", + new ParserErrorInfo(51, "SQL46010", ".")); + + // RETURNS without a data type + ParserTestUtils.ErrorTestFabricDW( + "CREATE FUNCTION dbo.f RETURNS AS EXTERNAL FUNCTION mySet.myFn", + new ParserErrorInfo(22, "SQL46010", "RETURNS")); + + // ALTER: missing external name + ParserTestUtils.ErrorTestFabricDW( + "ALTER FUNCTION dbo.f AS EXTERNAL FUNCTION", + new ParserErrorInfo(41, "SQL46029")); + + // CREATE OR ALTER: missing FUNCTION keyword after EXTERNAL + ParserTestUtils.ErrorTestFabricDW( + "CREATE OR ALTER FUNCTION dbo.f AS EXTERNAL mySet.myFn", + new ParserErrorInfo(43, "SQL46010", "mySet")); + } + /// /// Negative test for OFFSET with FETCH APPROXIMATE - SQL46145 error /// OFFSET clause cannot be used with FETCH APPROXIMATE (introduced in SQL Server 2025) diff --git a/Test/SqlDom/TestScripts/CreateSemanticIndexTests180.sql b/Test/SqlDom/TestScripts/CreateSemanticIndexTests180.sql new file mode 100644 index 00000000..677e3487 --- /dev/null +++ b/Test/SqlDom/TestScripts/CreateSemanticIndexTests180.sql @@ -0,0 +1,56 @@ +-- Basic semantic index (defaults to SEARCH_TYPE=vector, requires EXTERNAL_MODEL) +CREATE SEMANTIC INDEX SI_Basic ON dbo.Documents (content) WITH (EXTERNAL_MODEL = MyModel); + +-- Semantic index with SEARCH_TYPE and EXTERNAL_MODEL (required for vector) +CREATE SEMANTIC INDEX SI_Vector ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = MyModel); + +-- Multiple columns with SEARCH_TYPE and EXTERNAL_MODEL (required for vector) +CREATE SEMANTIC INDEX SI_Multi ON dbo.books (summary SEARCH_TYPE=vector, title SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = MyModel); + +-- All search types (EXTERNAL_MODEL required for hybrid) +CREATE SEMANTIC INDEX SI_Hybrid ON dbo.books (content SEARCH_TYPE=hybrid, title SEARCH_TYPE=fulltext) WITH (EXTERNAL_MODEL = MyModel); + +-- With TYPE COLUMN (defaults to vector, requires EXTERNAL_MODEL) +CREATE SEMANTIC INDEX SI_TypeCol ON dbo.Documents (content TYPE COLUMN content_type) WITH (EXTERNAL_MODEL = MyModel); + +-- With LANGUAGE (defaults to vector, requires EXTERNAL_MODEL) +CREATE SEMANTIC INDEX SI_Lang ON dbo.Documents (content LANGUAGE English) WITH (EXTERNAL_MODEL = MyModel); + +-- With CHUNK_USING options (defaults to vector, requires EXTERNAL_MODEL) +CREATE SEMANTIC INDEX SI_Chunk ON dbo.Documents (content CHUNK_USING(TYPE = paragraph, SIZE = 500, OVERLAP = 50)) WITH (EXTERNAL_MODEL = MyModel); + +-- Full column definition with EXTERNAL_MODEL (required for vector) +CREATE SEMANTIC INDEX SI_Full ON dbo.Documents (content SEARCH_TYPE=vector TYPE COLUMN content_type LANGUAGE English CHUNK_USING(TYPE = sentence, SIZE = 1000)) WITH (EXTERNAL_MODEL = MyModel); + +-- WITH EXTERNAL_MODEL +CREATE SEMANTIC INDEX SI_Model ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = OpenAIModel); + +-- WITH EXTERNAL_MODEL in parentheses +CREATE SEMANTIC INDEX SI_ModelParen ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = (MyModel)); + +-- WITH EXTERNAL_MODEL and PARAMETERS +CREATE SEMANTIC INDEX SI_ModelParams ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = MyModel (PARAMETERS = '{"dimension": 1536}')); + +-- WITH VECTOR_INDEX options +CREATE SEMANTIC INDEX SI_VecOpts ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = OpenAIModel, VECTOR_INDEX (METRIC = 'cosine')); + +-- WITH FULLTEXT_STOPLIST OFF +CREATE SEMANTIC INDEX SI_StopOff ON dbo.books (content SEARCH_TYPE=fulltext) WITH (FULLTEXT_STOPLIST = OFF); + +-- WITH FULLTEXT_STOPLIST SYSTEM +CREATE SEMANTIC INDEX SI_StopSys ON dbo.books (content SEARCH_TYPE=fulltext) WITH (FULLTEXT_STOPLIST = SYSTEM); + +-- WITH FULLTEXT_STOPLIST name +CREATE SEMANTIC INDEX SI_StopName ON dbo.books (content SEARCH_TYPE=fulltext) WITH (FULLTEXT_STOPLIST = MyStoplist); + +-- WITH MAXDOP +CREATE SEMANTIC INDEX SI_MaxDop ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = OpenAIModel, MAXDOP = 4); + +-- WITH DROP_EXISTING +CREATE SEMANTIC INDEX SI_DropEx ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = OpenAIModel, DROP_EXISTING = ON); + +-- With ON filegroup +CREATE SEMANTIC INDEX SI_FG ON dbo.books (summary SEARCH_TYPE=vector) WITH (EXTERNAL_MODEL = OpenAIModel) ON [PRIMARY]; + +-- Complex example with all options +CREATE SEMANTIC INDEX SI_Complete ON dbo.books (summary SEARCH_TYPE=vector, title SEARCH_TYPE=fulltext CHUNK_USING(TYPE = fixed, SIZE = 200, OVERLAP = 25)) WITH (EXTERNAL_MODEL = OpenAIModel (PARAMETERS = '{"api_key": "test"}'), VECTOR_INDEX (METRIC = 'cosine', TYPE = 'DiskANN'), FULLTEXT_STOPLIST = SYSTEM, MAXDOP = 8, DROP_EXISTING = OFF) ON [PRIMARY]; diff --git a/Test/SqlDom/TestScripts/ExternalFunctionTestsFabricDW.sql b/Test/SqlDom/TestScripts/ExternalFunctionTestsFabricDW.sql new file mode 100644 index 00000000..43d8dc1c --- /dev/null +++ b/Test/SqlDom/TestScripts/ExternalFunctionTestsFabricDW.sql @@ -0,0 +1,62 @@ +-- Basic CREATE FUNCTION ... AS EXTERNAL FUNCTION +CREATE FUNCTION dbo.MyExternalFn AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- ALTER FUNCTION ... AS EXTERNAL FUNCTION +ALTER FUNCTION dbo.MyExternalFn AS EXTERNAL FUNCTION mySet.anotherFn; +GO + +-- CREATE OR ALTER FUNCTION ... AS EXTERNAL FUNCTION +CREATE OR ALTER FUNCTION dbo.MyExternalFn AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- Single-part external name +CREATE FUNCTION MyFn AS EXTERNAL FUNCTION myFn; +GO + +-- CREATE with RETURNS clause specifying explicit return type +CREATE FUNCTION dbo.MyExternalFn RETURNS MONEY AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- ALTER with RETURNS clause +ALTER FUNCTION dbo.MyExternalFn RETURNS NVARCHAR(100) AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- CREATE OR ALTER with RETURNS clause +CREATE OR ALTER FUNCTION dbo.MyExternalFn RETURNS INT AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- CREATE with single parameter +CREATE FUNCTION dbo.MyExternalFn (@x INT) AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- CREATE with multiple parameters and RETURNS +CREATE FUNCTION dbo.MyExternalFn (@x INT, @y NVARCHAR(50)) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- ALTER with parameters and RETURNS +ALTER FUNCTION dbo.MyExternalFn (@x INT) RETURNS BIGINT AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- CREATE OR ALTER with parameters and RETURNS +CREATE OR ALTER FUNCTION dbo.MyExternalFn (@x INT) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn; +GO + +-- DROP FUNCTION (existing syntax, no change needed) +DROP FUNCTION dbo.MyExternalFn; +GO + +-- DML: invoking the external function like a regular UDF +SELECT dbo.MyExternalFn(); +GO + +SELECT dbo.MyExternalFn(42, N'hello'); +GO + +DECLARE @v INT = 1; +SELECT dbo.MyExternalFn(@v, 'const'); +GO + +SELECT dbo.MyExternalFn(t.col1, t.col2) AS r +FROM dbo.t AS t; +GO diff --git a/Test/SqlDom/TestScripts/InvokeExternalApiTestsFabricDW.sql b/Test/SqlDom/TestScripts/InvokeExternalApiTestsFabricDW.sql new file mode 100644 index 00000000..ff0d704b --- /dev/null +++ b/Test/SqlDom/TestScripts/InvokeExternalApiTestsFabricDW.sql @@ -0,0 +1,27 @@ +-- Basic call with only required arguments. +SELECT INVOKE_EXTERNAL_API('myFunctionSet', 'myFunction'); +GO + +-- With a single optional argument. +SELECT INVOKE_EXTERNAL_API('myFunctionSet', 'myFunction', 42); +GO + +-- With multiple optional arguments of various expression kinds. +DECLARE @v INT = 7; +SELECT INVOKE_EXTERNAL_API(N'mySet', N'doStuff', @v, 'literal', 1 + 2, NULL); +GO + +-- Inside an ALTER FUNCTION RETURN statement (critical RETURN-context coverage). +ALTER FUNCTION dbo.TestInvokeExternalApi() +RETURNS NVARCHAR(MAX) +AS +BEGIN + RETURN (INVOKE_EXTERNAL_API('mySet', 'myFn', 'arg1')); +END; +GO + +-- Inside a WHERE clause. +SELECT 1 +FROM dbo.t +WHERE INVOKE_EXTERNAL_API('mySet', 'isAllowed', col1) = 1; +GO diff --git a/release-notes/180/180.37.3.md b/release-notes/180/180.37.3.md new file mode 100644 index 00000000..b7e7bac0 --- /dev/null +++ b/release-notes/180/180.37.3.md @@ -0,0 +1,30 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.37.3 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* Updates .NET SDK to latest patch version 8.0.420 + +#### .NET Framework +#### .NET Core + +### New Features +* Adds support for CREATE FUNCTION AS EXTERNAL FUNCTION in Warehouse in Microsoft Fabric. + +### Fixed +* Fix PERSIST_SAMPLE_PERCENT statistics option parsing [#207](https://github.com/microsoft/SqlScriptDOM/pull/207) +* Fixes the issue with AlterTableAddTableElementStatement omitted the separator between column-definitions/constraints and table indexes, producing 'NOT NULLINDEX ix_...' +* Fixes the issue with WindowDefinition omitted whitespace between the inherited window-name reference (RefWindowName) and a following PARTITION BY or ORDER BY, producing 'win2PARTITION ...' + +### Changes +* Improvements to how comments are preserved and emitted in the SQL Server script generator. + +### Known Issues +* None \ No newline at end of file From bb623c8d1a33ec19800f705775f74452b1c4216d Mon Sep 17 00:00:00 2001 From: NAVEEN NAIK <71204882+ZEUSXXIV@users.noreply.github.com> Date: Tue, 21 Jul 2026 00:36:45 +0530 Subject: [PATCH 34/45] Fix CopyOption FirstTokenIndex and LastTokenIndex (#179) (#213) --- SqlScriptDom/Parser/TSql/TSql130.g | 5 ++++ Test/SqlDom/TSqlParserTest.cs | 39 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/SqlScriptDom/Parser/TSql/TSql130.g b/SqlScriptDom/Parser/TSql/TSql130.g index 4ef84a35..bc917aa6 100644 --- a/SqlScriptDom/Parser/TSql/TSql130.g +++ b/SqlScriptDom/Parser/TSql/TSql130.g @@ -22607,16 +22607,19 @@ copyOption [ref Int32 encountered] returns [CopyOption vResult = FragmentFactory { vResult.Kind = CopyIdentifierOrValueOptionsHelper.Instance.ParseOption(tOption); CheckCopyOptionDuplication(ref encountered, vResult.Kind, tOption); + UpdateTokenInfo(vResult, tOption); } | tIdentityInsert:IdentityInsert { vResult.Kind = CopyOptionKind.Identity_Insert; CheckCopyOptionDuplication(ref encountered, vResult.Kind, tIdentityInsert); + UpdateTokenInfo(vResult, tIdentityInsert); } | tCredential:Credential { vResult.Kind = CopyOptionKind.Credential; CheckCopyOptionDuplication(ref encountered, vResult.Kind, tCredential); + UpdateTokenInfo(vResult, tCredential); } ) EqualsSign @@ -22624,6 +22627,7 @@ copyOption [ref Int32 encountered] returns [CopyOption vResult = FragmentFactory vValue = singleValueTypeCopyOption { CopyIdentifierOrValueOptionsHelper.Instance.AssignValueToCopyOption(vResult, (SingleValueTypeCopyOption) vValue); + vResult.UpdateTokenInfo(vValue); } | vValue = copyCredentialOption @@ -22632,6 +22636,7 @@ copyOption [ref Int32 encountered] returns [CopyOption vResult = FragmentFactory CopyIdentifierOrValueOptionsHelper.Instance.ValidateCopyCredential((CopyCredentialOption)vValue)) { vResult.Value = (CopyCredentialOption) vValue; + vResult.UpdateTokenInfo(vValue); } else { diff --git a/Test/SqlDom/TSqlParserTest.cs b/Test/SqlDom/TSqlParserTest.cs index 1d7abcd1..23c6bd59 100644 --- a/Test/SqlDom/TSqlParserTest.cs +++ b/Test/SqlDom/TSqlParserTest.cs @@ -649,6 +649,45 @@ FROM Test } } + [TestMethod] + [Priority(0)] + [Timeout(GlobalConstants.DefaultTestTimeout)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CopyOptionFirstTokenIndexTest() + { + string input = @" +COPY INTO #Test +FROM 'https://xxxx.blob.core.windows.net/raw/' +WITH ( + FILE_TYPE = 'CSV', + IDENTITY_INSERT = 'ON' +);"; + TSql130Parser parser = new TSql130Parser(true); + IList errors; + TSqlScript script = (TSqlScript)parser.Parse(new System.IO.StringReader(input), out errors); + Assert.AreEqual(0, errors.Count); + + var copyStatement = script.Batches[0].Statements[0] as CopyStatement; + Assert.IsNotNull(copyStatement); + Assert.AreEqual(2, copyStatement.Options.Count); + + // Verify first option: FILE_TYPE = 'CSV' + var option1 = copyStatement.Options[0]; + Assert.AreEqual(CopyOptionKind.File_Type, option1.Kind); + // First token should be FILE_TYPE + Assert.AreEqual("FILE_TYPE", option1.ScriptTokenStream[option1.FirstTokenIndex].Text); + // Last token should be 'CSV' + Assert.AreEqual("'CSV'", option1.ScriptTokenStream[option1.LastTokenIndex].Text); + + // Verify second option: IDENTITY_INSERT = 'ON' + var option2 = copyStatement.Options[1]; + Assert.AreEqual(CopyOptionKind.Identity_Insert, option2.Kind); + // First token should be IDENTITY_INSERT + Assert.AreEqual("IDENTITY_INSERT", option2.ScriptTokenStream[option2.FirstTokenIndex].Text); + // Last token should be 'ON' + Assert.AreEqual("'ON'", option2.ScriptTokenStream[option2.LastTokenIndex].Text); + } + void VerifyTokenTypesAndOffsets(IList tokens, TSqlTokenType[] tokenTypes, int[] zeroBasedTokenOffsets, int offsetShift) { Assert.AreEqual(tokenTypes.Length, tokens.Count); From 2337cea4bc55972b4aa0cfe49dd2257b7c5e5099 Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Wed, 22 Jul 2026 11:57:28 -0700 Subject: [PATCH 35/45] Make MODEL_TYPE fragment classification non-breaking (#217) Commit 20f9bf1 (PR #210, fixing #176) reclassified MODEL_TYPE as a TSqlFragment but broke the public API: it repurposed the enum ExternalModelTypeOption into a fragment class and changed the type of ExternalModelStatement.ModelType from ExternalModelTypeOption? to a fragment reference. This change delivers the same fix additively, without breaking the API: - Keep enum ExternalModelTypeOption { EMBEDDINGS } and the ExternalModelStatement.ModelType (ExternalModelTypeOption?) member unchanged for backward compatibility. - Add a visitable fragment ExternalModelTypeSpecification whose OptionKind reuses the existing ExternalModelTypeOption enum, plus a new ModelTypeSpecification member on ExternalModelStatement. - The parser populates both representations; the script generator prefers the fragment and falls back to the legacy enum. All 624 unit tests pass on net8.0 and net472. --- SqlScriptDom/Parser/TSql/Ast.xml | 7 +++--- .../Parser/TSql/ExternalModelTypeOption.cs | 9 ++++---- SqlScriptDom/Parser/TSql/TSql170.g | 15 ++++++------ SqlScriptDom/Parser/TSql/TSql180.g | 15 ++++++------ ...ptGenerator.AlterExternalModelStatement.cs | 15 ++++++++++-- ...torVisitor.CreateExternalModelStatement.cs | 23 ++++++++++++++----- Test/SqlDom/Only170SyntaxTests.cs | 16 +++++++++---- 7 files changed, 65 insertions(+), 35 deletions(-) diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index d90c664a..ebf274a3 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -1388,7 +1388,8 @@ - + + @@ -1404,8 +1405,8 @@ - - + + diff --git a/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs b/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs index 6f16dc2a..0a7bfdac 100644 --- a/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs +++ b/SqlScriptDom/Parser/TSql/ExternalModelTypeOption.cs @@ -10,16 +10,15 @@ namespace Microsoft.SqlServer.TransactSql.ScriptDom #pragma warning disable 1591 /// - /// The enumeration specifies the external model type - /// Currently, we support Embeddings only. + /// The enumeration specifies the external model type. + /// Currently, we support EMBEDDINGS only. /// - public enum ExternalModelTypeOptionKind + public enum ExternalModelTypeOption { /// /// MODEL_TYPE = EMBEDDINGS /// - Embeddings = 0, - + EMBEDDINGS = 0, } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 0babede1..ceb78600 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -24171,14 +24171,14 @@ StringLiteral vApiFormat; externalModelModelType[ExternalModelStatement vParent] { - ExternalModelTypeOption vModelTypeOption = null; + ExternalModelTypeSpecification vModelTypeSpec = null; } : tModelType:Identifier { Match(tModelType, CodeGenerationSupporter.ModelType); - vModelTypeOption = this.FragmentFactory.CreateFragment(); - UpdateTokenInfo(vModelTypeOption, tModelType); + vModelTypeSpec = this.FragmentFactory.CreateFragment(); + UpdateTokenInfo(vModelTypeSpec, tModelType); } EqualsSign ( @@ -24186,10 +24186,11 @@ externalModelModelType[ExternalModelStatement vParent] { if (TryMatch(tEmbeddings, CodeGenerationSupporter.Embeddings)) { - vModelTypeOption.OptionKind = ExternalModelTypeOptionKind.Embeddings; - UpdateTokenInfo(vModelTypeOption, tEmbeddings); - vParent.ModelType = vModelTypeOption; - vParent.UpdateTokenInfo(vModelTypeOption); + vModelTypeSpec.OptionKind = ExternalModelTypeOption.EMBEDDINGS; + UpdateTokenInfo(vModelTypeSpec, tEmbeddings); + vParent.ModelTypeSpecification = vModelTypeSpec; + vParent.ModelType = ExternalModelTypeOption.EMBEDDINGS; + vParent.UpdateTokenInfo(vModelTypeSpec); } else { diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index ae426b05..934911db 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -24400,14 +24400,14 @@ StringLiteral vApiFormat; externalModelModelType[ExternalModelStatement vParent] { - ExternalModelTypeOption vModelTypeOption = null; + ExternalModelTypeSpecification vModelTypeSpec = null; } : tModelType:Identifier { Match(tModelType, CodeGenerationSupporter.ModelType); - vModelTypeOption = this.FragmentFactory.CreateFragment(); - UpdateTokenInfo(vModelTypeOption, tModelType); + vModelTypeSpec = this.FragmentFactory.CreateFragment(); + UpdateTokenInfo(vModelTypeSpec, tModelType); } EqualsSign ( @@ -24415,10 +24415,11 @@ externalModelModelType[ExternalModelStatement vParent] { if (TryMatch(tEmbeddings, CodeGenerationSupporter.Embeddings)) { - vModelTypeOption.OptionKind = ExternalModelTypeOptionKind.Embeddings; - UpdateTokenInfo(vModelTypeOption, tEmbeddings); - vParent.ModelType = vModelTypeOption; - vParent.UpdateTokenInfo(vModelTypeOption); + vModelTypeSpec.OptionKind = ExternalModelTypeOption.EMBEDDINGS; + UpdateTokenInfo(vModelTypeSpec, tEmbeddings); + vParent.ModelTypeSpecification = vModelTypeSpec; + vParent.ModelType = ExternalModelTypeOption.EMBEDDINGS; + vParent.UpdateTokenInfo(vModelTypeSpec); } else { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs index 10e8a45f..1d8da7ad 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGenerator.AlterExternalModelStatement.cs @@ -53,7 +53,7 @@ protected void GenerateAlterExternalModelStatementBody(AlterExternalModelStateme } // external model Model Type options - if (node.ModelType != null) + if (node.ModelTypeSpecification != null) { if (!ifFirst) { @@ -61,7 +61,18 @@ protected void GenerateAlterExternalModelStatementBody(AlterExternalModelStateme } ifFirst = false; NewLine(); - GenerateFragmentIfNotNull(node.ModelType); + GenerateFragmentIfNotNull(node.ModelTypeSpecification); + } + else if (node.ModelType != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + string externalModelTypeOption = GetValueForEnumKey(_externalModelTypeOption, node.ModelType.Value); + GenerateNameEqualsValue(CodeGenerationSupporter.ModelType, externalModelTypeOption); } // external model name options diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs index 8d6b3174..543f15a8 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateExternalModelStatement.cs @@ -17,9 +17,9 @@ public override void ExplicitVisit(CreateExternalModelStatement node) GenerateSpaceAndIdentifier(CodeGenerationSupporter.Model); GenerateCreateExternalModelStatementBody(node); } - protected static Dictionary _externalModelTypeOptionKind = new Dictionary() + protected static Dictionary _externalModelTypeOption = new Dictionary() { - {ExternalModelTypeOptionKind.Embeddings, CodeGenerationSupporter.Embeddings} + {ExternalModelTypeOption.EMBEDDINGS, CodeGenerationSupporter.Embeddings} }; protected void GenerateCreateExternalModelStatementBody(CreateExternalModelStatement node) @@ -54,7 +54,7 @@ protected void GenerateCreateExternalModelStatementBody(CreateExternalModelState } // external model Model Type options - if (node.ModelType != null) + if (node.ModelTypeSpecification != null) { if (!ifFirst) { @@ -62,7 +62,18 @@ protected void GenerateCreateExternalModelStatementBody(CreateExternalModelState } ifFirst = false; NewLine(); - GenerateFragmentIfNotNull(node.ModelType); + GenerateFragmentIfNotNull(node.ModelTypeSpecification); + } + else if (node.ModelType != null) + { + if (!ifFirst) + { + GenerateSymbol(TSqlTokenType.Comma); + } + ifFirst = false; + NewLine(); + string externalModelTypeOption = GetValueForEnumKey(_externalModelTypeOption, node.ModelType.Value); + GenerateNameEqualsValue(CodeGenerationSupporter.ModelType, externalModelTypeOption); } // external model name options @@ -117,9 +128,9 @@ protected void GenerateCreateExternalModelStatementBody(CreateExternalModelState GenerateKeyword(TSqlTokenType.RightParenthesis); } - public override void ExplicitVisit(ExternalModelTypeOption node) + public override void ExplicitVisit(ExternalModelTypeSpecification node) { - string optionKindString = GetValueForEnumKey(_externalModelTypeOptionKind, node.OptionKind); + string optionKindString = GetValueForEnumKey(_externalModelTypeOption, node.OptionKind); GenerateNameEqualsValue(CodeGenerationSupporter.ModelType, optionKindString); } } diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 51c95f38..322f993e 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -407,18 +407,24 @@ public void TestExternalModelModelTypeVisitor() Assert.IsNotNull(fragment); // Collect all visited fragments using a custom visitor - var visitor = new ExternalModelTypeOptionVisitor(); + var visitor = new ExternalModelTypeSpecificationVisitor(); fragment.Accept(visitor); Assert.AreEqual(1, visitor.VisitedOptions.Count); - Assert.AreEqual(ExternalModelTypeOptionKind.Embeddings, visitor.VisitedOptions[0].OptionKind); + Assert.AreEqual(ExternalModelTypeOption.EMBEDDINGS, visitor.VisitedOptions[0].OptionKind); + + // Legacy enum member must still be populated for backward compatibility + var createStatement = ((TSqlScript)fragment).Batches[0].Statements[0] as CreateExternalModelStatement; + Assert.IsNotNull(createStatement); + Assert.AreEqual(ExternalModelTypeOption.EMBEDDINGS, createStatement.ModelType); + Assert.IsNotNull(createStatement.ModelTypeSpecification); } - private class ExternalModelTypeOptionVisitor : TSqlFragmentVisitor + private class ExternalModelTypeSpecificationVisitor : TSqlFragmentVisitor { - public List VisitedOptions { get; } = new List(); + public List VisitedOptions { get; } = new List(); - public override void Visit(ExternalModelTypeOption node) + public override void Visit(ExternalModelTypeSpecification node) { VisitedOptions.Add(node); base.Visit(node); From db6fe8873cc82a0a062ad51b0be0b45d32839291 Mon Sep 17 00:00:00 2001 From: allancascante Date: Fri, 24 Jul 2026 17:48:07 -0600 Subject: [PATCH 36/45] Sync repos: Release 180.59.2 (#218) Co-authored-by: Allan Cascante --- Packages.props | 3 +- .../ScriptDom/SqlServer/ColumnAliasStyle.cs | 33 + .../ScriptDom/SqlServer/CommaPlacement.cs | 28 + .../SqlServer/IdentifierBracketing.cs | 40 + .../ScriptDom/SqlServer/IdentifierCasing.cs | 39 + .../ScriptDom/SqlServer/IndentationMode.cs | 33 + .../ScriptGeneratorSupporter.cs | 48 + .../ScriptWriter.AlignmentPointData.cs | 10 + ...riptWriter.RightAlignedSeparatorElement.cs | 49 + .../ScriptWriter.ScriptWriterElementType.cs | 1 + .../SqlServer/ScriptGenerator/ScriptWriter.cs | 355 ++++- .../SqlScriptGeneratorOptions.Indentation.cs | 27 + .../SqlScriptGeneratorOptions.LeadingComma.cs | 26 + ...tGeneratorVisitor.BinaryQueryExpression.cs | 2 + ...orVisitor.BuiltInFunctionTableReference.cs | 4 +- ...ScriptGeneratorVisitor.ColumnDefinition.cs | 11 +- .../SqlScriptGeneratorVisitor.Comments.cs | 60 +- ...SqlScriptGeneratorVisitor.CommonPhrases.cs | 78 +- ...torVisitor.CreateFulltextIndexStatement.cs | 21 + ...isitor.CreatePartitionFunctionStatement.cs | 8 +- ...tor.FileTableCollateFileNameTableOption.cs | 4 +- .../SqlScriptGeneratorVisitor.FunctionCall.cs | 19 +- ...torVisitor.GlobalFunctionTableReference.cs | 5 +- ...SqlScriptGeneratorVisitor.GotoStatement.cs | 6 +- .../SqlScriptGeneratorVisitor.Identifier.cs | 176 ++- ...ratorVisitor.InsertBulkColumnDefinition.cs | 11 +- ...neratorVisitor.OdbcConvertSpecification.cs | 3 +- ...ScriptGeneratorVisitor.OdbcFunctionCall.cs | 3 +- ...ratorVisitor.OpenRowsetColumnDefinition.cs | 9 +- .../SqlScriptGeneratorVisitor.OverClause.cs | 4 +- .../SqlScriptGeneratorVisitor.Permission.cs | 5 +- ...SqlScriptGeneratorVisitor.QualifiedJoin.cs | 25 +- ...GeneratorVisitor.SelectScalarExpression.cs | 62 +- .../SqlScriptGeneratorVisitor.SetClause.cs | 54 +- ...lScriptGeneratorVisitor.UnqualifiedJoin.cs | 3 + ...GeneratorVisitor.UseFederationStatement.cs | 4 +- .../SqlScriptGeneratorVisitor.Utils.cs | 167 ++- .../SqlScriptGeneratorVisitor.cs | 33 + .../Settings/SqlScriptGeneratorOptions.xml | 33 +- .../ScriptGenerator/ColumnAliasStyleTests.cs | 577 ++++++++ .../IdentifierFormattingTests.cs | 1008 ++++++++++++++ .../ScriptGenerator/IndentationModeTests.cs | 631 +++++++++ .../JoinClauseFormattingTests.cs | 259 ++++ .../ScriptGeneratorTestHelper.cs | 56 + .../ScriptGeneratorTests.cs | 1233 ++++++++++++++++- Test/SqlDom/UTSqlScriptDom.csproj | 1 + release-notes/180/180.59.2.md | 34 + 47 files changed, 5219 insertions(+), 82 deletions(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ColumnAliasStyle.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/CommaPlacement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/IdentifierBracketing.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/IdentifierCasing.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/IndentationMode.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.RightAlignedSeparatorElement.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.Indentation.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs create mode 100644 Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/IndentationModeTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs rename Test/SqlDom/{ => ScriptGenerator}/ScriptGeneratorTests.cs (61%) create mode 100644 release-notes/180/180.59.2.md diff --git a/Packages.props b/Packages.props index d65ed09c..b936dfcf 100644 --- a/Packages.props +++ b/Packages.props @@ -22,5 +22,6 @@ + - \ No newline at end of file + diff --git a/SqlScriptDom/ScriptDom/SqlServer/ColumnAliasStyle.cs b/SqlScriptDom/ScriptDom/SqlServer/ColumnAliasStyle.cs new file mode 100644 index 00000000..6fc6a3d3 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ColumnAliasStyle.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents the possible ways of rendering column aliases in SELECT projections + /// + public enum ColumnAliasStyle + { + /// + /// Render column aliases using the AS keyword: expression AS alias + /// + AsKeyword, + + /// + /// Render column aliases using the equals sign: alias = expression + /// + EqualsSign, + + /// + /// Preserve the column alias style from the original script without converting between styles + /// + Preserve + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/CommaPlacement.cs b/SqlScriptDom/ScriptDom/SqlServer/CommaPlacement.cs new file mode 100644 index 00000000..1a053792 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/CommaPlacement.cs @@ -0,0 +1,28 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents the placement of commas when a comma-separated list is written on multiple lines. + /// + public enum CommaPlacement + { + /// + /// The comma is placed at the end of the line, after the item that precedes it. + /// + Trailing, + + /// + /// The comma is placed at the start of the line, before the item that follows it. + /// When this value is used, the setting is ignored and + /// indentation always uses spaces. + /// + Leading + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/IdentifierBracketing.cs b/SqlScriptDom/ScriptDom/SqlServer/IdentifierBracketing.cs new file mode 100644 index 00000000..0aa4cdfc --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/IdentifierBracketing.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents the possible ways of controlling square bracket usage around object + /// identifiers during script generation. + /// + public enum IdentifierBracketing + { + /// + /// Preserve the original bracketing/quoting of identifiers + /// + Preserve, + + /// + /// Wrap all object identifiers in square brackets + /// + IncludeBrackets, + + /// + /// Remove brackets from identifiers that do not require them. Identifiers that + /// conflict with reserved words or contain special characters retain their brackets. + /// This is a best-effort transformation: in rare cases an identifier lexes as an ordinary + /// identifier yet its brackets are semantically required by the surrounding syntax (for + /// example a schema-qualified name that collides with a special relational operator such as + /// AI_GENERATE_CHUNKS). Such brackets may be removed, so ExcludeBrackets is not guaranteed to + /// preserve semantics for every possible input. + /// + ExcludeBrackets + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/IdentifierCasing.cs b/SqlScriptDom/ScriptDom/SqlServer/IdentifierCasing.cs new file mode 100644 index 00000000..bce93ada --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/IdentifierCasing.cs @@ -0,0 +1,39 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents the possible ways of casing object identifiers during script generation. + /// This does not apply to keywords, string literals, function names, or variables. + /// + public enum IdentifierCasing + { + /// + /// Preserve the original casing of identifiers + /// + Preserve, + + /// + /// All letters in upper case + /// + Uppercase, + + /// + /// All letters in lower case + /// + Lowercase, + + /// + /// First letter of the identifier capitalized, all remaining letters lower case + /// + PascalCase + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/IndentationMode.cs b/SqlScriptDom/ScriptDom/SqlServer/IndentationMode.cs new file mode 100644 index 00000000..20e4932b --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/IndentationMode.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents the character used to indent generated script. + /// + public enum IndentationMode + { + /// + /// Each indentation level inserts IndentationSize space characters. + /// + Spaces, + + /// + /// Leading whitespace and the aligned gaps between tokens (for example a clause keyword and its + /// body, or column-definition fields) are written using only tab characters, rounding each + /// aligned column up to the next tab stop. Because those tab stops assume each tab is + /// columns wide, the output only appears + /// aligned when the viewer's tab width (for example the editor's tab size) is set to the same + /// value as . This mode is ignored + /// (indentation uses spaces) when is + /// . + /// + Tabs + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs index 9e9abe0e..d766f43a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs @@ -63,6 +63,39 @@ public static string GetCasedString(string str, KeywordCasing casing) return String.Empty; } + /// + /// Retrieves a version of the specified identifier string, in the identifier casing format specified. + /// + /// The identifier string to get a specially cased version of + /// The identifier casing method to use + /// A version of the string in the casing format specified in + [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] + public static string GetCasedString(string str, IdentifierCasing casing) + { + // Empty (or null) values are returned unchanged: there is nothing to recase, and PascalCase + // would otherwise index str[0] and throw during script generation. + if (string.IsNullOrEmpty(str)) + { + return str; + } + + switch (casing) + { + case IdentifierCasing.Preserve: + return str; + case IdentifierCasing.Lowercase: + return str.ToLowerInvariant(); + case IdentifierCasing.Uppercase: + return str.ToUpperInvariant(); + case IdentifierCasing.PascalCase: + return GetPascalCase(str); + default: + Debug.Fail("Invalid IdentifierCasing value"); + break; + } + return str; + } + /// /// Retrieves a Pascal Cased version of the string /// @@ -190,6 +223,21 @@ public static TSqlParserToken CreateWhitespaceToken(Int32 count) return new TSqlParserToken(TSqlTokenType.WhiteSpace, ws); } + /// + /// Create a whitespace token consisting of tab characters (used for indentation when + /// is ). + /// + /// number of tab characters + /// + public static TSqlParserToken CreateTabToken(Int32 count) + { + // Build the tab whitespace + String ws = new String('\t', count); + + // Create a whitespace token and add it to the layout table + return new TSqlParserToken(TSqlTokenType.WhiteSpace, ws); + } + internal static void CheckForNullReference(object variable, string variableName) { if (variableName == null) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.AlignmentPointData.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.AlignmentPointData.cs index 71825af2..f72c7b81 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.AlignmentPointData.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.AlignmentPointData.cs @@ -35,6 +35,16 @@ public AlignmentPointData(String name) public Int32 Offset { get; set; } public String Name { get; private set; } + // Tab-layout data (only used when IndentationMode is Tabs). TabTarget is the column the + // content following this alignment point is snapped to (a tab stop); TabShift is how far + // that content is shifted right versus the space layout; MaxLeftTabShift accumulates the + // TabShift of this point's left neighbours; and AbsorbsSeparator is set when this point is + // immediately followed by a single separator space that the tab run replaces. + public Int32 TabTarget { get; set; } + public Int32 TabShift { get; set; } + public Int32 MaxLeftTabShift { get; set; } + public Boolean AbsorbsSeparator { get; set; } + public void AddLeftPoint(AlignmentPointData ap, Int32 width) { Int32 currentWidth; diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.RightAlignedSeparatorElement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.RightAlignedSeparatorElement.cs new file mode 100644 index 00000000..91c5dcd2 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.RightAlignedSeparatorElement.cs @@ -0,0 +1,49 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + internal partial class ScriptWriter + { + /// + /// A run of tokens (e.g. a leading comma and a space) that must be right-aligned so + /// that it ends exactly at the offset of the alignment point that immediately follows + /// it. This is used for leading comma placement, where the comma should sit just before + /// the aligned item column rather than at the start of the line. + /// + internal class RightAlignedSeparatorElement : ScriptWriterElement + { + private readonly List _tokens; + private readonly int _width; + + public RightAlignedSeparatorElement(List tokens) + { + _tokens = tokens; + _width = 0; + foreach (TSqlParserToken token in tokens) + { + if (token != null && token.Text != null) + { + _width += token.Text.Length; + } + } + + this.ElementType = ScriptWriterElementType.RightAlignedSeparator; + } + + public List Tokens + { + get { return _tokens; } + } + + public int Width + { + get { return _width; } + } + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.ScriptWriterElementType.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.ScriptWriterElementType.cs index b7f473ea..94ae7b72 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.ScriptWriterElementType.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.ScriptWriterElementType.cs @@ -14,6 +14,7 @@ internal enum ScriptWriterElementType AlignmentPoint, Token, NewLine, + RightAlignedSeparator, } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs index e1ceb0ed..07e46282 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs @@ -83,7 +83,13 @@ public void NewLine() // if we have some AlignmentPoints on stack, we set to the top one if (_newLineAlignmentPoints.Count > 0) { - Mark(_newLineAlignmentPoints.Peek()); + // The top entry may be null when a named-alignment scope was pushed without its own + // newline-restoration point (see PushNamedAlignmentScope); nothing to restore then. + AlignmentPoint newLineAlignmentPoint = _newLineAlignmentPoints.Peek(); + if (newLineAlignmentPoint != null) + { + Mark(newLineAlignmentPoint); + } } } @@ -92,6 +98,168 @@ public void Indent(Int32 size) AddSpace(size); } + // In Tabs indentation mode, rewrite the leading whitespace of every line so that it uses + // tab characters only. The script is first generated (and aligned) entirely with spaces; + // this pass then replaces the leading run of spaces on each line with the number of tab + // stops needed to reach (rounding up) that column: ceil(leadingSpaces / IndentationSize) + // tabs, with no trailing spaces. Whitespace that appears after content on a line (mid-line + // alignment padding) is left untouched. This pass is a no-op unless UseTabsForIndentation + // is set (never when CommaPlacement is Leading). + private List ConvertLeadingWhitespaceToTabs(List tokens) + { + if (_options.UseTabsForIndentation == false || _options.IndentationSize <= 0) + { + return tokens; + } + + Int32 size = _options.IndentationSize; + List result = new List(tokens.Count); + Boolean atLineStart = true; + Int32 leadingSpaces = 0; + + for (Int32 index = 0; index < tokens.Count; ++index) + { + TSqlParserToken token = tokens[index]; + // Whether the NEXT token starts a new line is determined by whether this token ENDS + // with a newline, not merely contains one: a multi-line block comment or string + // literal contains newlines but ends with content (e.g. "*/" or "'"), so tokens + // that follow it on the same line must not be treated as leading indentation. + Boolean endsWithNewLine = TokenEndsWithNewLine(token); + + if (atLineStart && !endsWithNewLine && IsAllSpaces(token.Text)) + { + // Accumulate the leading run of spaces (which may span multiple tokens). + leadingSpaces += token.Text.Length; + continue; + } + + if (atLineStart) + { + // Reached the end of the leading whitespace run: emit it as tab characters, + // rounding up to the next tab stop so no trailing spaces remain. + if (leadingSpaces > 0) + { + Int32 tabs = (leadingSpaces + size - 1) / size; + result.Add(ScriptGeneratorSupporter.CreateTabToken(tabs)); + leadingSpaces = 0; + } + } + + result.Add(token); + atLineStart = endsWithNewLine; + } + + return result; + } + + private static Boolean TokenEndsWithNewLine(TSqlParserToken token) + { + String text = token.Text; + if (String.IsNullOrEmpty(text)) + { + return false; + } + + Char last = text[text.Length - 1]; + return last == '\n' || last == '\r'; + } + + private static Boolean IsAllSpaces(String text) + { + if (String.IsNullOrEmpty(text)) + { + return false; + } + + foreach (Char c in text) + { + if (c != ' ') + { + return false; + } + } + return true; + } + + // Tabs mode only. True when the element right after 'index' is a single-space separator + // token. Such an alignment point is a "field separator" (for example the gap between a + // clause keyword and its body, or between column-definition fields) whose gap is rendered + // with tabs and whose trailing space is then swallowed. + private Boolean IsFollowedBySeparatorSpace(Int32 index) + { + if (index + 1 >= _scriptWriterElements.Count) + { + return false; + } + + TokenWrapper nextToken = _scriptWriterElements[index + 1] as TokenWrapper; + return nextToken != null && nextToken.Token != null && nextToken.Token.Text == " "; + } + + // Tabs mode only. Computes where this alignment point snaps to a tab stop, once its space + // offset and its left neighbours' shifts are final. A field separator snaps to the first + // tab stop strictly past its (shifted) column; every other point simply inherits the shift + // of its left neighbours. TabShift records how far the snap moved the point versus the + // space layout, and is propagated rightward so later columns on the line stay aligned. + private void ComputeTabSnappedLayout(AlignmentPointData ap) + { + Int32 size = _options.IndentationSize; + if (size <= 0) + { + return; + } + + if (ap.AbsorbsSeparator) + { + Int32 shiftedColumn = ap.Offset + ap.MaxLeftTabShift; + ap.TabTarget = ((shiftedColumn / size) + 1) * size; + ap.TabShift = ap.TabTarget - ap.Offset - 1; + } + else + { + ap.TabShift = ap.MaxLeftTabShift; + } + } + + // Tabs mode only. When 'ap' is a field separator, emits its aligned gap as tab characters + // (advancing 'offset' to the precomputed tab-stop target) and asks the caller to swallow + // the single separator space that follows. Returns false in the default Spaces mode, or for + // points that are not tab-snapped, so the caller falls back to the normal space padding. + private Boolean TryEmitTabSnappedGap(AlignmentPointData ap, List tokens, ref Int32 offset, ref Boolean absorbSeparatorSpace) + { + if (_options.UseTabsForIndentation == false + || _options.IndentationSize <= 0 + || ap.AbsorbsSeparator == false) + { + return false; + } + + // The target already accounts for the cumulative shift introduced by any earlier + // tab-snapped points on this line, so columns stay aligned. + Int32 size = _options.IndentationSize; + + // If the precomputed target is not ahead of the current offset (which can happen when + // earlier tab-snapped points on this line advanced 'offset' past this point's target), + // advance to the next tab stop from the current offset so 'offset' never moves backward + // and the tabs emitted actually land on the position we record. + Int32 target = ap.TabTarget; + if (target <= offset) + { + target = ((offset / size) + 1) * size; + } + + Int32 tabCount = target / size - offset / size; + if (tabCount < 1) + { + tabCount = 1; + } + + tokens.Add(ScriptGeneratorSupporter.CreateTabToken(tabCount)); + offset = target; + absorbSeparatorSpace = true; + return true; + } + public void Mark(AlignmentPoint ap) { if (String.IsNullOrEmpty(ap.Name) == false && @@ -102,11 +270,42 @@ public void Mark(AlignmentPoint ap) AddAlignmentPoint(ap); } + // Add a comma-and-space separator that is right-aligned so that it ends exactly at the + // offset of the alignment point that immediately follows it. Used for leading comma + // placement in keyword-aligned lists (e.g. the SELECT column list). + public void AddRightAlignedCommaSeparator() + { + List tokens = new List(2) + { + new TSqlParserToken(TSqlTokenType.Comma, ScriptGeneratorSupporter.GetTokenString(TSqlTokenType.Comma, _options.KeywordCasing)) + }; + if (_options.LeadingCommaSpaceCount > 0) + { + tokens.Add(ScriptGeneratorSupporter.CreateWhitespaceToken(_options.LeadingCommaSpaceCount)); + } + _scriptWriterElements.Add(new RightAlignedSeparatorElement(tokens)); + } + public void PushNewLineAlignmentPoint(AlignmentPoint ap) + { + PushNewLineAlignmentPoint(ap, resetNameScope: true); + } + + // When resetNameScope is true (the default) the current named-alignment-point scope is + // replaced with a fresh one, so named alignment points inside the pushed scope are + // independent of the outer scope (used e.g. for nested constructs). When false, the same + // named-alignment-point scope is kept, so named alignment points (e.g. column-definition + // field alignment) remain shared across the pushed scopes; this is needed when the push + // exists only to provide a newline-restoration point (comment preservation) and must not + // defeat cross-line alignment. + public void PushNewLineAlignmentPoint(AlignmentPoint ap, Boolean resetNameScope) { _newLineAlignmentPoints.Push(ap); _alignmentPointNameMaps.Push(_alignmentPointNameMapForCurrentScope); - _alignmentPointNameMapForCurrentScope = new Dictionary(); + if (resetNameScope) + { + _alignmentPointNameMapForCurrentScope = new Dictionary(); + } } public void PopNewLineAlignmentPoint() @@ -115,6 +314,23 @@ public void PopNewLineAlignmentPoint() _alignmentPointNameMapForCurrentScope = _alignmentPointNameMaps.Pop(); } + // Isolates the named-alignment-point scope for a list: named alignment points created after + // this call are shared among the list's items but do not leak into the enclosing scope, so + // separate lists rendered later in the same parent scope do not align against each other. + // Unlike PushNewLineAlignmentPoint(ap), this neither adds an alignment point at the current + // position nor changes newline restoration: the current newline-restoration point (if any) + // is reused so NewLine() behavior inside the scope is unchanged. + public void PushNamedAlignmentScope() + { + AlignmentPoint currentNewLineAlignmentPoint = _newLineAlignmentPoints.Count > 0 ? _newLineAlignmentPoints.Peek() : null; + PushNewLineAlignmentPoint(currentNewLineAlignmentPoint, resetNameScope: true); + } + + public void PopNamedAlignmentScope() + { + PopNewLineAlignmentPoint(); + } + public AlignmentPoint FindOrCreateAlignmentPoint(String name) { AlignmentPoint ap = null; @@ -232,7 +448,8 @@ private List TryGetAlignedTokens() if (result == null) result = GetAllTokens(); - return result; + // Tabs mode only post-pass; returns 'result' unchanged in the default Spaces mode. + return ConvertLeadingWhitespaceToTabs(result); } private List Align() @@ -269,6 +486,19 @@ private List Align() ap.Offset = Math.Max(ap.Offset, width); } + // Tabs mode only: record whether this point is a field separator so its + // gap can later be rendered as tabs. In the default Spaces mode this is + // skipped and AbsorbsSeparator stays false, so nothing downstream changes. + if (_options.UseTabsForIndentation) + { + // AlignmentPointData is shared across every occurrence of the same + // alignment point, so OR the flag instead of overwriting it: the point + // is snapped to a tab stop if it is a field separator on ANY line. The + // per-occurrence decision to actually emit the tab gap is made during + // emission below. + ap.AbsorbsSeparator |= IsFollowedBySeparatorSpace(index); + } + width = 0; previousPoint = ap; break; @@ -281,6 +511,16 @@ private List Align() width += tokenWrapper.Token.Text.Length; } break; + case ScriptWriterElementType.RightAlignedSeparator: + // The separator occupies its own width between the previous alignment + // point and the following one (which it is right-aligned against). + RightAlignedSeparatorElement separatorWidthElement = element as RightAlignedSeparatorElement; + Debug.Assert(separatorWidthElement != null, "RightAlignedSeparatorElement is expected"); + if (separatorWidthElement != null) + { + width += separatorWidthElement.Width; + } + break; case ScriptWriterElementType.NewLine: Debug.Assert(element is NewLineElement, "NewLineElement is expected"); width = 0; @@ -309,11 +549,26 @@ private List Align() return null; } + // Tabs mode only: compute where this point snaps to a tab stop, now that its + // offset and its left neighbours' shifts are final. Skipped in the default Spaces + // mode, where the offsets computed above are used exactly as-is. + if (_options.UseTabsForIndentation) + { + ComputeTabSnappedLayout(ap); + } + // let's align ap up HashSet rightPoints = ap.RightPoints; foreach (AlignmentPointData rightPoint in rightPoints) { rightPoint.AlignAndRemoveLeftPoint(ap); + + // Tabs mode only: carry this point's tab shift to its right neighbours so they + // stay aligned once earlier gaps have been snapped to tab stops. + if (_options.UseTabsForIndentation) + { + rightPoint.MaxLeftTabShift = Math.Max(rightPoint.MaxLeftTabShift, ap.TabShift); + } } // ap is done; let's remove it; @@ -324,6 +579,11 @@ private List Align() List tokens = new List(_scriptWriterElements.Count); Int32 offset = 0; + RightAlignedSeparatorElement pendingSeparator = null; + // When a mid-line alignment point has just been snapped to a tab stop in Tabs mode, the + // single separator space the generator emits after it is redundant and is swallowed so + // the following content follows the tab run directly. + Boolean absorbSeparatorSpace = false; for (Int32 index = 0; index < _scriptWriterElements.Count; ++index) { ScriptWriterElement element = _scriptWriterElements[index]; @@ -334,27 +594,81 @@ private List Align() #if !PIMODLANGUAGE Debug.Assert(ap != null, "AlignmentPointData is expected"); #endif - Debug.Assert(ap.Offset >= offset, "Incorrect offset"); + // In Tabs mode a clause body can be snapped forward onto a tab stop, which + // can leave 'offset' ahead of a later alignment point's precomputed offset. + Debug.Assert(_options.UseTabsForIndentation || ap.Offset >= offset, "Incorrect offset"); + if (pendingSeparator != null) + { + // Right-align the buffered separator so that it ends exactly at this + // alignment point's offset: pad up to (offset - separatorWidth), then + // emit the separator so the following item starts at the aligned column. + Int32 padBeforeSeparator = ap.Offset - offset - pendingSeparator.Width; + if (padBeforeSeparator > 0) + { + tokens.Add(ScriptGeneratorSupporter.CreateWhitespaceToken(padBeforeSeparator)); + offset += padBeforeSeparator; + } + + foreach (TSqlParserToken separatorToken in pendingSeparator.Tokens) + { + tokens.Add(separatorToken); + offset += separatorToken.Text.Length; + } + + pendingSeparator = null; + } + + // Tabs mode only: if THIS occurrence is followed by the single separator + // space token, emit its aligned gap as tabs and skip the default space + // padding below. The per-occurrence IsFollowedBySeparatorSpace check makes + // occurrences of a shared alignment point that are not separators fall + // through to normal padding, even though the shared AbsorbsSeparator flag is + // true. Skipped in the default Spaces mode, so that path runs unchanged. + if (_options.UseTabsForIndentation + && IsFollowedBySeparatorSpace(index) + && TryEmitTabSnappedGap(ap, tokens, ref offset, ref absorbSeparatorSpace)) + { + break; + } + if (ap.Offset > offset) { tokens.Add(ScriptGeneratorSupporter.CreateWhitespaceToken(ap.Offset - offset)); } - offset = ap.Offset; + // Use Math.Max because emitting a right-aligned separator above can advance + // 'offset' to exactly ap.Offset; never move the offset backwards here. + offset = Math.Max(offset, ap.Offset); break; case ScriptWriterElementType.Token: + FlushPendingSeparator(tokens, ref pendingSeparator, ref offset); TokenWrapper tokenWrapper = element as TokenWrapper; Debug.Assert(tokenWrapper != null, "TokenWrapper is expected"); Debug.Assert(tokenWrapper.Token.Text != null, "TokenWrapper.Token.Text should not be null"); if (tokenWrapper != null && tokenWrapper.Token != null && tokenWrapper.Token.Text != null) { + // Swallow the single separator space that follows a tab-snapped alignment point. + if (absorbSeparatorSpace && tokenWrapper.Token.Text == " ") + { + absorbSeparatorSpace = false; + break; + } + absorbSeparatorSpace = false; tokens.Add(tokenWrapper.Token); offset += tokenWrapper.Token.Text.Length; } break; + case ScriptWriterElementType.RightAlignedSeparator: + // Defer emission until the following alignment point is known so the + // separator can be right-aligned against it. + FlushPendingSeparator(tokens, ref pendingSeparator, ref offset); + pendingSeparator = element as RightAlignedSeparatorElement; + break; case ScriptWriterElementType.NewLine: + FlushPendingSeparator(tokens, ref pendingSeparator, ref offset); Debug.Assert(element is NewLineElement, "NewLineElement is expected"); tokens.Add(_newLineToken); offset = 0; + absorbSeparatorSpace = false; break; default: Debug.Assert(false, "Unknown ScriptWriterElement type"); @@ -362,9 +676,29 @@ private List Align() } } + FlushPendingSeparator(tokens, ref pendingSeparator, ref offset); + return tokens; } + // Emit a buffered right-aligned separator inline (used when it is not immediately + // followed by an alignment point to right-align against). + private static void FlushPendingSeparator(List tokens, ref RightAlignedSeparatorElement pendingSeparator, ref Int32 offset) + { + if (pendingSeparator == null) + { + return; + } + + foreach (TSqlParserToken separatorToken in pendingSeparator.Tokens) + { + tokens.Add(separatorToken); + offset += separatorToken.Text.Length; + } + + pendingSeparator = null; + } + // get all tokens without alignment private List GetAllTokens() { @@ -380,6 +714,17 @@ private List GetAllTokens() Debug.Assert(tokenWrapper != null, "TokenWrapper is expected"); tokens.Add(tokenWrapper.Token); break; + case ScriptWriterElementType.RightAlignedSeparator: + RightAlignedSeparatorElement separatorElement = element as RightAlignedSeparatorElement; + Debug.Assert(separatorElement != null, "RightAlignedSeparatorElement is expected"); + if (separatorElement != null) + { + foreach (TSqlParserToken separatorToken in separatorElement.Tokens) + { + tokens.Add(separatorToken); + } + } + break; case ScriptWriterElementType.NewLine: Debug.Assert(element is NewLineElement, "NewLineElement is expected"); tokens.Add(_newLineToken); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.Indentation.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.Indentation.cs new file mode 100644 index 00000000..78962ea7 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.Indentation.cs @@ -0,0 +1,27 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + public partial class SqlScriptGeneratorOptions + { + /// + /// Whether indentation should be emitted using tab characters for the current option set. + /// This is true only when is + /// and is not . + /// + internal Boolean UseTabsForIndentation + { + get + { + return IndentationMode == IndentationMode.Tabs + && CommaPlacement != CommaPlacement.Leading; + } + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs new file mode 100644 index 00000000..6d5c8c70 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + public partial class SqlScriptGeneratorOptions + { + /// + /// The number of whitespace characters written after a leading comma when + /// is . + /// The total width reserved for a leading comma is one column for the comma itself + /// plus this many columns of trailing whitespace (so the default of 1 reserves 2 columns). + /// + /// + /// This is currently an internal knob so the leading-comma spacing is defined in a single + /// place rather than hard-coded at every call site. It can later be promoted to a public + /// script generation option. + /// + internal Int32 LeadingCommaSpaceCount { get; set; } = 1; + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BinaryQueryExpression.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BinaryQueryExpression.cs index 1f2d04f0..9bfdf792 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BinaryQueryExpression.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BinaryQueryExpression.cs @@ -34,6 +34,8 @@ public void GenerateBinaryQueryExpression(BinaryQueryExpression node, AlignmentP if (generator != null) { NewLine(); + // Emit any pending gap comments before UNION/EXCEPT/INTERSECT keywords + EmitPendingGapComments(); GenerateToken(generator); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionTableReference.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionTableReference.cs index 66b82a38..e41976c5 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionTableReference.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionTableReference.cs @@ -12,7 +12,9 @@ partial class SqlScriptGeneratorVisitor public override void ExplicitVisit(BuiltInFunctionTableReference node) { GenerateSymbol(TSqlTokenType.DoubleColon); - GenerateFragmentIfNotNull(node.Name); + // The built-in function name is a keyword-like function name, not an object name; do not + // bracket or recase it (same rationale as GlobalFunctionTableReference / FunctionCall). + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.Name)); GenerateSpace(); GenerateParenthesisedCommaSeparatedList(node.Parameters, true); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ColumnDefinition.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ColumnDefinition.cs index aea6127c..da883b95 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ColumnDefinition.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ColumnDefinition.cs @@ -118,7 +118,16 @@ public override void ExplicitVisit(ColumnDefinition node) // TODO, yangg: if constraint AP is still not marked, we can mark it here or don't. // either way we have some imperfect effect...check out the expression and table-declare unit tests - MarkForConstraintsWhenNecessary(ConstraintAP, ref firstConstraint); + // + // In Tabs mode (with a positive indentation size), when a column has no constraint the + // only remaining token is the comma, so marking the constraint alignment point here + // would just pad the column with spaces to line up commas. Skip it in that case. Spaces + // mode - and Tabs mode with IndentationSize <= 0, where no tabs are emitted and the + // layout falls back to spaces - keeps the original behavior so its output stays unchanged. + if (!_options.UseTabsForIndentation || _options.IndentationSize <= 0) + { + MarkForConstraintsWhenNecessary(ConstraintAP, ref firstConstraint); + } } public override void ExplicitVisit(ColumnStorageOptions node) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs index 9a800616..6fe8d85b 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs @@ -130,8 +130,41 @@ protected void EmitGapComments(TSqlFragment fragment) } /// - /// Emits trailing comments after the fragment, scanning across newlines. - /// Each comment's own-line vs same-line placement is preserved from source. + /// Emits any pending gap comments that haven't been emitted yet. + /// Scans forward from lastProcessedTokenIndex and emits consecutive comment tokens. + /// Use this before generating keywords that should have comments before them. + /// + protected void EmitPendingGapComments() + { + if (!_options.PreserveComments || _currentTokenStream == null) + { + return; + } + + int startIndex = _lastProcessedTokenIndex + 1; + + // Emit consecutive comment tokens from the current position + for (int i = startIndex; i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + + if (IsCommentToken(token) && !_emittedComments.Contains(token)) + { + EmitCommentToken(token, isLeading: true); + _emittedComments.Add(token); + _lastProcessedTokenIndex = i; + } + else if (token.TokenType != TSqlTokenType.WhiteSpace) + { + // Stop at first non-comment, non-whitespace token + break; + } + } + } + + /// + /// Emits trailing comments after the fragment, ONLY on the same line. + /// Comments on their own line are left as gap comments for the next fragment. /// protected void EmitTrailingComments(TSqlFragment fragment) { @@ -147,6 +180,7 @@ protected void EmitTrailingComments(TSqlFragment fragment) } int prevEmittedSourceIndex = lastTokenIndex; + bool skippedSeparatorComma = false; for (int i = lastTokenIndex + 1; i < _currentTokenStream.Count; i++) { var token = _currentTokenStream[i]; @@ -156,6 +190,15 @@ protected void EmitTrailingComments(TSqlFragment fragment) if (!_emittedComments.Contains(token)) { bool ownLine = SourceGapContainsNewline(prevEmittedSourceIndex, i); + + // CRITICAL FIX: Only emit same-line trailing comments. + // Comments on their own line should be left as gap comments for the next fragment. + if (ownLine) + { + // Stop here - don't emit this comment as trailing + break; + } + EmitTrailingCommentToken(token, ownLine); _emittedComments.Add(token); _lastProcessedTokenIndex = i; @@ -169,6 +212,19 @@ protected void EmitTrailingComments(TSqlFragment fragment) continue; } + // A list-separator comma on the same source line as the element does not end the + // element's trailing-comment window: a comment after it (e.g. 'col1, -- note') is + // still a trailing comment of this element and must stay on the element's line + // rather than being re-attributed as a leading comment of the next element. Skip a + // single same-line separator comma and keep scanning for the trailing comment. + if (token.TokenType == TSqlTokenType.Comma + && !skippedSeparatorComma + && !SourceGapContainsNewline(prevEmittedSourceIndex, i)) + { + skippedSeparatorComma = true; + continue; + } + // Any other token (including ';') ends the window. break; } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs index 00bc2bc3..ef8e600e 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs @@ -127,7 +127,9 @@ protected void GenerateSpaceAndCollation(Identifier collation) { GenerateSpace(); GenerateKeyword(TSqlTokenType.Collate); - GenerateSpaceAndFragmentIfNotNull(collation); + // Collation names are stored as Identifier fragments but cannot be delimited or recased + // (COLLATE [name] is invalid T-SQL), so suppress identifier formatting for them. + GenerateWithoutIdentifierFormatting(() => GenerateSpaceAndFragmentIfNotNull(collation)); } } @@ -398,15 +400,81 @@ protected void GenerateQueryExpressionInParentheses(QueryExpression queryExpress GenerateSymbol(TSqlTokenType.RightParenthesis); } + // True while rendering a SELECT projection list (QuerySpecification.SelectElements). + // Restricts the "alias = expression" ColumnAliasStyle form to real SELECT projections, + // because OUTPUT, OUTPUT INTO and RECEIVE reuse SelectScalarExpression but do not + // allow that form. + private bool _inSelectProjection; + private void GenerateSelectElementsList(IList selectElements) { - if (_options.MultilineSelectElementsList == false) + // SelectScalarExpression is shared with non-projection contexts (OUTPUT / OUTPUT INTO / + // RECEIVE). Mark that we are rendering a real SELECT projection so that column aliases + // may honor the ColumnAliasStyle option here (and only here). The previous value is + // restored so nested scalar subqueries remain independent. + bool previousInSelectProjection = _inSelectProjection; + _inSelectProjection = true; + try { - GenerateCommaSeparatedList(selectElements); + if (_options.MultilineSelectElementsList == false) + { + GenerateCommaSeparatedList(selectElements); + } + else if (_options.ColumnAliasStyle != ColumnAliasStyle.AsKeyword && _options.AlignClauseBodies) + { + // Push a dedicated alignment scope so that "alias = expression" equals signs + // align only within this SELECT list. Nested subqueries push their own scope + // and therefore align independently. + AlignmentPoint selectItems = new AlignmentPoint(); + MarkAndPushAlignmentPoint(selectItems); + + // Hold the "=" alignment point in a field for the duration of this SELECT list. + // When PreserveComments is enabled, GenerateFragmentList wraps each select + // element in its own freshly pushed alignment scope (which resets the writer's + // alignment-point name map), so resolving the point by name would yield a + // distinct point per row and the "=" signs would not align across rows. Keeping + // the point in a field lets every row share it. The previous value is restored + // so nested SELECT projections align independently. + AlignmentPoint previousEqualSignAlignmentPoint = _selectColumnAliasEqualSignAlignmentPoint; + _selectColumnAliasEqualSignAlignmentPoint = new AlignmentPoint(SelectColumnAliasEqualSign); + try + { + GenerateFragmentList(selectElements, ListGenerationOption.MultipleLineSelectElementOption); + } + finally + { + _selectColumnAliasEqualSignAlignmentPoint = previousEqualSignAlignmentPoint; + } + + PopAlignmentPoint(); + } + else + { + GenerateFragmentList(selectElements, ListGenerationOption.MultipleLineSelectElementOption); + } } - else + finally { - GenerateFragmentList(selectElements, ListGenerationOption.MultipleLineSelectElementOption); + _inSelectProjection = previousInSelectProjection; + } + } + + // Mark the alignment point used to vertically align the "=" signs when column aliases + // are rendered as "alias = expression". Only applies when the SELECT list is written + // on multiple lines and clause-body alignment is enabled. + protected void MarkColumnAliasEqualSignAlignmentWhenNecessary() + { + if (_options.MultilineSelectElementsList && _options.AlignClauseBodies) + { + // Prefer the alignment point held for the current SELECT list so that the "=" signs + // align across all rows even when PreserveComments pushes a per-row alignment scope. + // Fall back to name resolution for safety if the field was not set. + AlignmentPoint ap = _selectColumnAliasEqualSignAlignmentPoint + ?? FindOrCreateAlignmentPointByName(SelectColumnAliasEqualSign); + if (ap != null) + { + Mark(ap); + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateFulltextIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateFulltextIndexStatement.cs index 2d90a624..ea7858b1 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateFulltextIndexStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateFulltextIndexStatement.cs @@ -112,9 +112,30 @@ public override void ExplicitVisit(StopListFullTextIndexOption node) System.Diagnostics.Debug.Assert(node.OptionKind == FullTextIndexOptionKind.StopList); GenerateKeywordAndSpace(TSqlTokenType.StopList); if (node.IsOff) + { GenerateKeyword(TSqlTokenType.Off); + } + else if (IsSystemStopList(node.StopListName)) + { + // STOPLIST = SYSTEM is a keyword option, not a user-defined stoplist name. Bracketing + // or recasing it ("STOPLIST [SYSTEM]") makes the parser read it as a user stoplist named + // SYSTEM, silently changing the meaning, so emit it without identifier formatting. + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.StopListName)); + } else + { GenerateFragmentIfNotNull(node.StopListName); + } + } + + // The STOPLIST option name is stored as an Identifier, but the unquoted value SYSTEM is the + // special "system stoplist" keyword rather than an object name. A delimited [SYSTEM] is a real + // user-defined stoplist and is left to normal identifier formatting. + private static bool IsSystemStopList(Identifier stopListName) + { + return stopListName != null + && stopListName.QuoteType == QuoteType.NotQuoted + && string.Equals(stopListName.Value, CodeGenerationSupporter.System, System.StringComparison.OrdinalIgnoreCase); } public override void ExplicitVisit(SearchPropertyListFullTextIndexOption node) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreatePartitionFunctionStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreatePartitionFunctionStatement.cs index 99b01ae5..c53360ab 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreatePartitionFunctionStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreatePartitionFunctionStatement.cs @@ -51,11 +51,9 @@ public override void ExplicitVisit(PartitionParameterType node) { GenerateFragmentIfNotNull(node.DataType); - if (node.Collation != null) - { - GenerateSpaceAndKeyword(TSqlTokenType.Collate); - GenerateSpaceAndFragmentIfNotNull(node.Collation); - } + // Collation names cannot be delimited or recased; GenerateSpaceAndCollation suppresses + // identifier formatting for them. + GenerateSpaceAndCollation(node.Collation); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FileTableCollateFileNameTableOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FileTableCollateFileNameTableOption.cs index f131d721..0ac7f3fc 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FileTableCollateFileNameTableOption.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FileTableCollateFileNameTableOption.cs @@ -12,7 +12,9 @@ partial class SqlScriptGeneratorVisitor public override void ExplicitVisit(FileTableCollateFileNameTableOption node) { System.Diagnostics.Debug.Assert(node.OptionKind == TableOptionKind.FileTableCollateFileName, "TableOption does not match"); - GenerateNameEqualsValue(CodeGenerationSupporter.FileTableCollateFileName, node.Value); + // The collation value (e.g. database_default) is a keyword Identifier fragment; do not + // bracket or recase it. + GenerateWithoutIdentifierFormatting(() => GenerateNameEqualsValue(CodeGenerationSupporter.FileTableCollateFileName, node.Value)); } } } \ No newline at end of file diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs index ffa50996..37fe8287 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs @@ -27,7 +27,12 @@ public override void ExplicitVisit(RightFunctionCall node) public override void ExplicitVisit(FunctionCall node) { GenerateFragmentIfNotNull(node.CallTarget); - GenerateFragmentIfNotNull(node.FunctionName); + + // Function names are not affected by the IdentifierCasing / IdentifierBracketing options + // (their casing is governed by a separate option), so emit the function name with + // identifier formatting suppressed. This has no effect under default options. + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.FunctionName)); + GenerateSymbol(TSqlTokenType.LeftParenthesis); if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.Trim && @@ -39,7 +44,9 @@ public override void ExplicitVisit(FunctionCall node) if (node.TrimOptions != null) { GenerateSpace(); - GenerateFragmentIfNotNull(node.TrimOptions); + // LEADING/TRAILING/BOTH are stored as an Identifier fragment but are keywords, so + // they must not be bracketed or recased by the identifier options. + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.TrimOptions)); GenerateSpace(); } GenerateFragmentIfNotNull(node.Parameters[0]); @@ -138,7 +145,9 @@ public override void ExplicitVisit(FunctionCall node) if (node.IgnoreRespectNulls?.Count > 0) { GenerateSpace(); - GenerateSpaceSeparatedList(node.IgnoreRespectNulls); + // IGNORE/RESPECT NULLS are stored as Identifier fragments but are keywords, so they + // must not be bracketed or recased by the identifier options. + GenerateWithoutIdentifierFormatting(() => GenerateSpaceSeparatedList(node.IgnoreRespectNulls)); } GenerateSpaceAndFragmentIfNotNull(node.WithinGroupClause); @@ -163,7 +172,9 @@ private void GenerateNullOnNullOrAbsentOnNull(IList list) { if (list?.Count > 0 && list[0].Value?.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.Absent) { - GenerateSpaceSeparatedList(list); + // ABSENT is stored as an Identifier fragment but is a keyword, so it must not be + // bracketed or recased by the identifier options ('[ABSENT] ON NULL' is invalid). + GenerateWithoutIdentifierFormatting(() => GenerateSpaceSeparatedList(list)); GenerateSpace(); GenerateKeyword(TSqlTokenType.On); GenerateSpace(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GlobalFunctionTableReference.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GlobalFunctionTableReference.cs index 81af8f76..f0647e66 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GlobalFunctionTableReference.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GlobalFunctionTableReference.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(GlobalFunctionTableReference node) { - GenerateFragmentIfNotNull(node.Name); + // The global table-function name (e.g. STRING_SPLIT) is a built-in function name, not an + // object name. Bracketing it ("[STRING_SPLIT]") makes the parser read it as a user-defined + // function, so emit it without identifier formatting, matching FunctionCall's handling. + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.Name)); GenerateSpace(); GenerateParenthesisedCommaSeparatedList(node.Parameters, alwaysGenerateParenthses: true); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GotoStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GotoStatement.cs index 8a719840..34e41a43 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GotoStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GotoStatement.cs @@ -12,7 +12,11 @@ partial class SqlScriptGeneratorVisitor public override void ExplicitVisit(GoToStatement node) { GenerateKeyword(TSqlTokenType.GoTo); - GenerateSpaceAndFragmentIfNotNull(node.LabelName); + + // The label reference must not be bracketed or recased: labels cannot be delimited + // (GOTO [label] is invalid T-SQL) and the reference must keep matching the label + // declaration, which is emitted verbatim by LabelStatement. No effect under default options. + GenerateWithoutIdentifierFormatting(() => GenerateSpaceAndFragmentIfNotNull(node.LabelName)); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Identifier.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Identifier.cs index 96c1f69d..c6e100b4 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Identifier.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Identifier.cs @@ -3,6 +3,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ +using System; +using System.Collections.Generic; +using System.IO; using System.Text; using Microsoft.SqlServer.TransactSql.ScriptDom; @@ -10,19 +13,182 @@ namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator { partial class SqlScriptGeneratorVisitor { + // When true, the IdentifierCasing and IdentifierBracketing options are not applied and + // the identifier is emitted with its original casing and quoting. Used for contexts where + // transforming the identifier would change semantics or produce invalid T-SQL, such as + // function names (governed by a separate option) and GOTO label references (labels cannot + // be delimited and must continue to match their label declaration). + private bool _suppressIdentifierFormatting; + + // Lazily-created parser used to probe whether an identifier can safely drop its brackets + // under IdentifierBracketing.ExcludeBrackets. It uses the configured SqlVersion so the + // reserved-word list matches the target dialect. + private TSqlParser _identifierBracketProbeParser; + public override void ExplicitVisit(Identifier node) { - if (node.Value != null) + if (node.Value == null) + { + return; + } + + // Default behavior is preserved: when identifier formatting is suppressed (function + // names, GOTO labels) or both options are at their default (Preserve), the identifier is + // emitted exactly as before - same value, same quoting - with no casing or bracketing + // change. Only when an option is set to a non-default value is any transformation applied. + // + // Variable and parameter names are also emitted unchanged: they are unquoted Identifier + // fragments whose value starts with '@' (the AST keeps the '@'). They must never be + // bracketed or recased - '[@x]' is invalid T-SQL and the interaction rules exclude + // @variables. The check is limited to unquoted identifiers so a delimited object identifier + // like [@Name] still participates in IdentifierCasing/IdentifierBracketing. + // + // Empty values (e.g. omitted components of a multi-part name) are also emitted unchanged: + // bracketing an empty value would produce invalid '[]'. + bool isVariableName = node.QuoteType == QuoteType.NotQuoted + && node.Value.Length > 0 + && node.Value[0] == '@'; + + if (_suppressIdentifierFormatting || + node.Value.Length == 0 || + isVariableName || + (_options.IdentifierCasing == IdentifierCasing.Preserve && + _options.IdentifierBracketing == IdentifierBracketing.Preserve)) + { + EmitIdentifier(node.Value, node.QuoteType); + return; + } + + // Bracketing is resolved first, then casing is applied to the value, per the documented + // interaction rule (IdentifierCasing is applied after IdentifierBracketing). + QuoteType quoteType = ResolveIdentifierQuoteType(node); + string value = ScriptGeneratorSupporter.GetCasedString(node.Value, _options.IdentifierCasing); + + EmitIdentifier(value, quoteType); + } + + // Emits an identifier exactly the way the generator did before the IdentifierCasing and + // IdentifierBracketing options existed: unquoted values are written as-is, quoted values are + // re-encoded with their quote type. + private void EmitIdentifier(string value, QuoteType quoteType) + { + if (quoteType == QuoteType.NotQuoted) + { + GenerateIdentifierWithoutCheck(value); + } + else + { + GenerateQuotedIdentifier(value, quoteType); + } + } + + // Runs the given emit action with identifier casing/bracketing suppressed. Used for Identifier + // fragments that represent syntax keywords/options rather than object names - function names, + // GOTO labels, TRIM's LEADING/TRAILING/BOTH, JSON ABSENT/NULL ON NULL, and window + // IGNORE/RESPECT NULLS - which must never be bracketed or recased (e.g. '[ABSENT] ON NULL' is + // invalid). Has no effect under default options, where identifiers are emitted unchanged anyway. + private void GenerateWithoutIdentifierFormatting(Action emit) + { + bool previousSuppress = _suppressIdentifierFormatting; + _suppressIdentifierFormatting = true; + try + { + emit(); + } + finally + { + _suppressIdentifierFormatting = previousSuppress; + } + } + + private QuoteType ResolveIdentifierQuoteType(Identifier node) + { + switch (_options.IdentifierBracketing) + { + case IdentifierBracketing.IncludeBrackets: + // An empty value is an omitted component of a multi-part name (e.g. the missing + // schema in "db..t"), not an identifier to delimit. Bracketing it to "[]" is + // invalid T-SQL (SQL46010), so preserve it as an empty, unquoted component before + // returning SquareBracket. (ExplicitVisit already short-circuits empty values; this + // keeps ResolveIdentifierQuoteType correct on its own as well.) + return string.IsNullOrEmpty(node.Value) ? QuoteType.NotQuoted : QuoteType.SquareBracket; + case IdentifierBracketing.ExcludeBrackets: + // This option controls square brackets only, so preserve other quote types + // (a double-quoted identifier keeps its double quotes). + if (node.QuoteType == QuoteType.SquareBracket && CanOmitBrackets(node.Value)) + { + return QuoteType.NotQuoted; + } + return node.QuoteType; + case IdentifierBracketing.Preserve: + default: + return node.QuoteType; + } + } + + // Returns true if the unquoted identifier value is a valid regular identifier that is not a + // reserved word for the configured SqlVersion (and therefore does not require brackets). + // This is determined by re-lexing the value with the version-specific parser: a safe + // identifier lexes to exactly one Identifier token whose text matches the value. Reserved + // words lex to keyword tokens; special characters or spaces produce multiple tokens or errors. + // + // Known limitation: a few identifiers lex to an ordinary Identifier token yet are contextual + // keywords whose brackets are semantically required (for example a schema-qualified name that + // collides with the AI_GENERATE_CHUNKS relational operator). This method cannot see the + // surrounding grammar context, so it may report such an identifier as bracket-optional. This + // is an accepted, documented limitation of the opt-in ExcludeBrackets option. + private bool CanOmitBrackets(string value) + { + if (string.IsNullOrEmpty(value)) + { + return false; + } + + if (_identifierBracketProbeParser == null) + { + _identifierBracketProbeParser = TSqlParser.CreateParser(_options.SqlVersion, true); + } + + IList errors; + IList tokens; + using (StringReader reader = new StringReader(value)) + { + tokens = _identifierBracketProbeParser.GetTokenStream(reader, out errors); + } + + if (errors != null && errors.Count > 0) + { + return false; + } + + // Expect exactly one meaningful token (plus the trailing EndOfFile token). + TSqlParserToken identifierToken = null; + foreach (TSqlParserToken token in tokens) { - if (node.QuoteType == QuoteType.NotQuoted) + if (token.TokenType == TSqlTokenType.EndOfFile) { - GenerateIdentifierWithoutCheck(node.Value); + continue; } - else + if (identifierToken != null) { - GenerateQuotedIdentifier(node.Value, node.QuoteType); + // More than one token means this is not a bare identifier. + return false; } + identifierToken = token; + } + + if (identifierToken == null || + !string.Equals(identifierToken.Text, value, StringComparison.Ordinal)) + { + return false; } + + // Only omit brackets when the value lexes to a genuine Identifier token. Values that lex + // to keyword tokens (e.g. AI_GENERATE_CHUNKS, TIMESTAMP) may be accepted as an unquoted + // identifier in some positions (such as a column alias) yet be invalid unquoted in others + // (such as a function name), so it is not safe to strip their brackets. Keeping the + // brackets is always valid. + return identifierToken.TokenType == TSqlTokenType.Identifier; } private void GenerateQuotedIdentifier(string identifier, QuoteType quoteType) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertBulkColumnDefinition.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertBulkColumnDefinition.cs index 3927cfd9..f577bee0 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertBulkColumnDefinition.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertBulkColumnDefinition.cs @@ -11,7 +11,16 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(InsertBulkColumnDefinition node) { - GenerateFragmentIfNotNull(node.Column); + if (node.Column != null && node.Column.DataType == null) + { + // A column with no data type is the TIMESTAMP/rowversion shorthand; its name is the + // TIMESTAMP keyword and cannot be bracketed or recased. + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.Column)); + } + else + { + GenerateFragmentIfNotNull(node.Column); + } switch (node.NullNotNull) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcConvertSpecification.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcConvertSpecification.cs index ee23c0e1..b6e4eb2c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcConvertSpecification.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcConvertSpecification.cs @@ -11,7 +11,8 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(OdbcConvertSpecification node) { - GenerateFragmentIfNotNull(node.Identifier); + // The ODBC data-type name is a keyword Identifier fragment; do not bracket or recase it. + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.Identifier)); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcFunctionCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcFunctionCall.cs index b05ac54d..f1ae7117 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcFunctionCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OdbcFunctionCall.cs @@ -13,7 +13,8 @@ public override void ExplicitVisit(OdbcFunctionCall node) { GenerateSymbol(TSqlTokenType.LeftCurly); GenerateSpaceAndIdentifier(CodeGenerationSupporter.Fn); - GenerateSpaceAndFragmentIfNotNull(node.Name); + // The ODBC function name is a keyword Identifier fragment; do not bracket or recase it. + GenerateWithoutIdentifierFormatting(() => GenerateSpaceAndFragmentIfNotNull(node.Name)); if (node.ParametersUsed) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OpenRowsetColumnDefinition.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OpenRowsetColumnDefinition.cs index c8692e22..f0f61703 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OpenRowsetColumnDefinition.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OpenRowsetColumnDefinition.cs @@ -14,12 +14,9 @@ public override void ExplicitVisit(OpenRowsetColumnDefinition node) GenerateSpaceAndFragmentIfNotNull(node.DataType); - if (node.Collation != null) - { - GenerateSpace(); - GenerateSymbol(TSqlTokenType.Collate); - GenerateSpaceAndFragmentIfNotNull(node.Collation); - } + // Collation names cannot be delimited or recased; GenerateSpaceAndCollation suppresses + // identifier formatting for them. + GenerateSpaceAndCollation(node.Collation); if (node.ColumnOrdinal != null) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs index 5791a6cd..36c072b7 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs @@ -18,7 +18,9 @@ public override void ExplicitVisit(OverClause node) if (windowNameExists && !windowSpecExist) { - GenerateSpaceAndFragmentIfNotNull(node.WindowName); + // An unparenthesized "OVER window_name" reference must be a plain identifier; it + // cannot be bracketed or recased. (Inside "OVER (window_name ...)" it may be.) + GenerateWithoutIdentifierFormatting(() => GenerateSpaceAndFragmentIfNotNull(node.WindowName)); } else { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Permission.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Permission.cs index fd076fdd..7fd304b9 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Permission.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Permission.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(Permission node) { - GenerateSpaceSeparatedList(node.Identifiers); + // Permission names (SELECT, ALTER, ANY, COLUMN, ...) are keyword Identifier fragments and + // must not be bracketed or recased by the identifier options. The column list below is a + // real object-name list and is still transformed. + GenerateWithoutIdentifierFormatting(() => GenerateSpaceSeparatedList(node.Identifiers)); if (node.Columns != null && node.Columns.Count > 0) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs index 5d0ef28c..19de7755 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs @@ -36,6 +36,9 @@ public override void ExplicitVisit(QualifiedJoin node) GenerateNewLineOrSpace(_options.NewLineBeforeJoinClause); + // Emit any pending gap comments before JOIN keywords + EmitPendingGapComments(); + GenerateQualifiedJoinType(node.QualifiedJoinType); if (node.JoinHint != JoinHint.None) @@ -48,10 +51,28 @@ public override void ExplicitVisit(QualifiedJoin node) //MarkClauseBodyAlignmentWhenNecessary(_options.NewlineBeforeJoinClause); - NewLine(); + // Both new options default to true, which reproduces the original formatting exactly: + // a newline after the JOIN keyword, then a newline before ON (with no extra indentation). + GenerateNewLineOrSpace(_options.NewLineAfterJoinKeyword); GenerateFragmentIfNotNull(node.SecondTableReference); - NewLine(); + if (_options.NewLineBeforeOnClause) + { + NewLine(); + + // Opt-in refinement only: when the table source is kept on the JOIN line + // (NewLineAfterJoinKeyword = false), indent ON one level so it reads as a child of + // the JOIN. This branch never runs with the default options, so the default output + // is unchanged. + if (!_options.NewLineAfterJoinKeyword) + { + Indent(); + } + } + else + { + GenerateSpace(); + } GenerateKeyword(TSqlTokenType.On); GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs index 91d9bf81..7797f9cd 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs @@ -11,13 +11,67 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(SelectScalarExpression node) { - GenerateFragmentIfNotNull(node.Expression); + if (node.ColumnName != null && UseEqualsSignForColumnAlias(node)) + { + GenerateFragmentIfNotNull(node.ColumnName); + MarkColumnAliasEqualSignAlignmentWhenNecessary(); + GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); + GenerateSpaceAndFragmentIfNotNull(node.Expression); + } + else + { + GenerateFragmentIfNotNull(node.Expression); - if (node.ColumnName != null) + if (node.ColumnName != null) + { + GenerateSpaceAndKeyword(TSqlTokenType.As); + GenerateSpaceAndFragmentIfNotNull(node.ColumnName); + } + } + } + + // Determines whether a column alias should be rendered as "alias = expression" + // (as opposed to "expression AS alias") based on the ColumnAliasStyle option. + private bool UseEqualsSignForColumnAlias(SelectScalarExpression node) + { + // The "alias = expression" form is only valid in a SELECT projection list. + // OUTPUT, OUTPUT INTO and RECEIVE reuse SelectScalarExpression but only accept + // "expression AS alias", so the equals-sign form must never be emitted there. + if (!_inSelectProjection) { - GenerateSpaceAndKeyword(TSqlTokenType.As); - GenerateSpaceAndFragmentIfNotNull(node.ColumnName); + return false; } + + switch (_options.ColumnAliasStyle) + { + case ColumnAliasStyle.EqualsSign: + return true; + case ColumnAliasStyle.Preserve: + return WasColumnAliasWrittenAsEqualsSign(node); + case ColumnAliasStyle.AsKeyword: + default: + return false; + } + } + + // In the equals-sign form ("alias = expression") the alias appears before the + // expression in the source, so its token index is smaller. In the AS form + // ("expression AS alias" or "expression alias") the alias appears after the + // expression. Fragments that were not parsed (built programmatically) have no + // token positions and are treated as AS-keyword style. + private static bool WasColumnAliasWrittenAsEqualsSign(SelectScalarExpression node) + { + // The caller only invokes this when ColumnName is set; a missing Expression is only + // possible for a malformed, non-parsed fragment and has no equals-sign form to preserve. + if (node?.Expression == null) + { + return false; + } + + int? aliasIndex = node?.ColumnName?.FirstTokenIndex; + int expressionIndex = node.Expression.FirstTokenIndex; + + return aliasIndex >= 0 && expressionIndex >= 0 && aliasIndex < expressionIndex; } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SetClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SetClause.cs index 06708bf6..e0271943 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SetClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SetClause.cs @@ -33,15 +33,63 @@ protected void GenerateSetClauses(IList setClauses, AlignmentPoint al Indent(); } + bool leadingComma = _options.MultilineSetClauseItems && _options.CommaPlacement == CommaPlacement.Leading; + + if (!leadingComma) + { + // Default / trailing behavior: unchanged from the original implementation so the + // generated output is identical when CommaPlacement is Trailing (the default). + GenerateKeyword(TSqlTokenType.Set); + + MarkClauseBodyAlignmentWhenNecessary(true, alignmentPoint); + + GenerateSpace(); + + AlignmentPoint setItems = new AlignmentPoint(); + MarkAndPushAlignmentPoint(setItems); + GenerateCommaSeparatedList(setClauses, _options.MultilineSetClauseItems); + PopAlignmentPoint(); + return; + } + + // Leading comma placement (opt-in). Anchor the newlines produced between SET items at + // the start of the SET clause (rather than at the item column). This lets leading + // commas be right-aligned so they end just before the aligned item column, mirroring + // the SELECT list, while the item column itself is established by the setItems + // alignment point marked on every item. Pushing a single alignment point also keeps + // the '=' sign alignment points (resolved by name within this scope) shared across all + // items. + AlignmentPoint clauseStart = new AlignmentPoint(); + MarkAndPushAlignmentPoint(clauseStart); + GenerateKeyword(TSqlTokenType.Set); MarkClauseBodyAlignmentWhenNecessary(true, alignmentPoint); GenerateSpace(); - AlignmentPoint setItems = new AlignmentPoint(); - MarkAndPushAlignmentPoint(setItems); - GenerateCommaSeparatedList(setClauses, _options.MultilineSetClauseItems); + AlignmentPoint items = new AlignmentPoint(); + bool firstItem = true; + foreach (SetClause setClause in setClauses) + { + if (firstItem) + { + Mark(items); + firstItem = false; + } + else + { + NewLine(); + GenerateRightAlignedCommaSeparator(); + + // Each multi-line item starts a new line, so re-mark the item alignment point + // to keep continuation items aligned under the first item. + Mark(items); + } + + GenerateFragmentIfNotNull(setClause); + } + PopAlignmentPoint(); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs index d82b3651..519d5941 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs @@ -28,6 +28,9 @@ public override void ExplicitVisit(UnqualifiedJoin node) { GenerateFragmentIfNotNull(node.FirstTableReference); + // Emit any pending gap comments before JOIN keywords + EmitPendingGapComments(); + List generators = GetValueForEnumKey(_unqualifiedJoinTypeGenerators, node.UnqualifiedJoinType); if (generators != null) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UseFederationStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UseFederationStatement.cs index 0f7428a0..c01dbaad 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UseFederationStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UseFederationStatement.cs @@ -21,7 +21,9 @@ public override void ExplicitVisit(UseFederationStatement node) } else { - GenerateSpaceAndFragmentIfNotNull(node.FederationName); + // The federation name must be a plain identifier; it cannot be bracketed or recased. + // (The distribution name below is a normal identifier and is still transformed.) + GenerateWithoutIdentifierFormatting(() => GenerateSpaceAndFragmentIfNotNull(node.FederationName)); GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.DistributionName); GenerateSpaceAndSymbol(TSqlTokenType.EqualsSign); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs index 381c6271..df7b2f49 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs @@ -212,16 +212,26 @@ protected void GenerateCommaSeparatedList(IList list) where T : TSqlFragme // generate a comma-separated list protected void GenerateCommaSeparatedList(IList list, Boolean insertNewLine) where T : TSqlFragment { + Boolean leadingComma = insertNewLine && _options.CommaPlacement == CommaPlacement.Leading; GenerateList(list, delegate() { - GenerateSymbol(TSqlTokenType.Comma); - if (insertNewLine) + if (leadingComma) { NewLine(); + GenerateSymbol(TSqlTokenType.Comma); + GenerateLeadingCommaSpace(); } else { - GenerateSpace(); + GenerateSymbol(TSqlTokenType.Comma); + if (insertNewLine) + { + NewLine(); + } + else + { + GenerateSpace(); + } } }); } @@ -229,22 +239,42 @@ protected void GenerateCommaSeparatedList(IList list, Boolean insertNewLin // generate a comma-separated list protected void GenerateCommaSeparatedList(IList list, bool insertNewLine, bool indent, bool generateSpaces = true) where T : TSqlFragment { + Boolean leadingComma = insertNewLine && _options.CommaPlacement == CommaPlacement.Leading; GenerateList(list, delegate() { - GenerateSymbol(TSqlTokenType.Comma); - if (insertNewLine) + if (leadingComma) { NewLine(); if (indent) { - Indent(); + // Reserve the comma width inside the indentation so the item starts at the + // normal indentation column (not indentation + LeadingCommaWidth), keeping + // continuation items aligned with the first item. + int indentColumns = _options.IndentationSize; + Indent(indentColumns >= LeadingCommaWidth ? indentColumns - LeadingCommaWidth : 0); } + + GenerateSymbol(TSqlTokenType.Comma); + GenerateLeadingCommaSpace(); } - else if (generateSpaces) + else { - GenerateSpace(); - } + GenerateSymbol(TSqlTokenType.Comma); + if (insertNewLine) + { + NewLine(); + + if (indent) + { + Indent(); + } + } + else if (generateSpaces) + { + GenerateSpace(); + } + } }); } @@ -338,6 +368,24 @@ protected void GenerateFragmentList(IList list, ListGenerationOption optio } Boolean firstItem = true; + + // When leading comma placement is requested, the comma is emitted at the start of the + // next line (after the newline and indentation) rather than trailing the previous item. + Boolean leadingComma = option.Separator == ListGenerationOption.SeparatorType.Comma + && option.NewLineBeforeItems + && _options.CommaPlacement == CommaPlacement.Leading; + + Boolean pushedListNamedAlignmentScope = false; + if (option.NewLineBeforeItems && _options.PreserveComments) + { + // Isolate a list-level named-alignment-point scope so field alignment points (e.g. + // column-definition name/type/constraint) are shared across items in this list but do + // not leak into the enclosing scope and accidentally align across separate lists + // rendered later in the same parent scope. + PushNamedAlignmentScope(); + pushedListNamedAlignmentScope = true; + } + foreach (var item in list) { if (firstItem) // do we have to produce a new line before the first item? @@ -347,28 +395,89 @@ protected void GenerateFragmentList(IList list, ListGenerationOption optio { NewLine(); } - - firstItem = false; } else { - GenerateSeparator(option); - if (option.NewLineBeforeItems) + if (leadingComma) { NewLine(); } + else + { + GenerateSeparator(option); + if (option.NewLineBeforeItems) + { + NewLine(); + } + } } - for (int indentIterator = 0; indentIterator < option.MultipleIndentItems ; indentIterator++) - Indent(); + Boolean leadingCommaThisItem = leadingComma && !firstItem; + + if (!leadingCommaThisItem) + { + // Default behavior (unchanged): indent each configured level. The separator + // for this path is emitted above via GenerateSeparator, so nothing changes + // here when MultipleIndentItems is greater than 0. + for (int indentIterator = 0; indentIterator < option.MultipleIndentItems; indentIterator++) + Indent(); + } + else if (option.MultipleIndentItems >= 1) + { + // Leading comma placement in an indented list: reserve the comma width inside + // the indentation so the item stays at the normal list indentation column and + // the comma is indented LeadingCommaWidth characters fewer. + int listIndentColumns = option.MultipleIndentItems * _options.IndentationSize; + Indent(listIndentColumns >= LeadingCommaWidth ? listIndentColumns - LeadingCommaWidth : 0); + + GenerateSymbol(TSqlTokenType.Comma); + GenerateLeadingCommaSpace(); + } + else + { + // Leading comma placement in a keyword-aligned list (no fixed indentation, e.g. + // the SELECT column list): the comma is emitted as a right-aligned separator so + // it ends exactly before the aligned item column, keeping items aligned with + // the first element and the comma just before each of them. + GenerateRightAlignedCommaSeparator(); + } if (option.NewLineBeforeItems) { - // we only mark it for multiple lines Mark(items); + + // Only push alignment point for NewLine() restoration when comment preservation is enabled. + // This ensures NewLine() calls within items (e.g., from EmitCommentToken) can restore + // to the correct indented position, without affecting general formatting. + if (_options.PreserveComments) + { + AlignmentPoint itemScope = new AlignmentPoint(); + // Keep the current named-alignment-point scope so field alignment points + // (e.g. column-definition name/type/constraint) stay shared across items and + // continue to align across lines; the push only provides a newline-restoration + // point for comment-driven newlines within the item. + MarkAndPushAlignmentPointKeepingNameScope(itemScope); + + GenerateFragmentIfNotNull(item); + + PopAlignmentPoint(); + } + else + { + GenerateFragmentIfNotNull(item); + } + } + else + { + GenerateFragmentIfNotNull(item); } - GenerateFragmentIfNotNull(item); + firstItem = false; + } + + if (pushedListNamedAlignmentScope) + { + PopNamedAlignmentScope(); } // generate close parenthesis @@ -432,6 +541,23 @@ protected void GenerateSpace() _writer.AddToken(ScriptGeneratorSupporter.CreateWhitespaceToken(1)); } + // The number of columns a leading comma occupies: one column for the comma itself plus + // the configured number of trailing whitespace columns (default 1, i.e. 2 columns total). + private Int32 LeadingCommaWidth + { + // 1 is the comma itself + get { return 1 + _options.LeadingCommaSpaceCount; } + } + + // generate the whitespace that follows a leading comma (configurable width) + private void GenerateLeadingCommaSpace() + { + if (_options.LeadingCommaSpaceCount > 0) + { + _writer.AddToken(ScriptGeneratorSupporter.CreateWhitespaceToken(_options.LeadingCommaSpaceCount)); + } + } + // generate a keyword protected void GenerateKeyword(TSqlTokenType keywordId) { @@ -459,6 +585,13 @@ protected void GenerateSymbol(TSqlTokenType symbolId) GenerateKeyword(symbolId); } + // generate a comma-and-space separator that is right-aligned against the next alignment + // point (used for leading comma placement in keyword-aligned lists such as SELECT) + protected void GenerateRightAlignedCommaSeparator() + { + _writer.AddRightAlignedCommaSeparator(); + } + // generate a token for a given token type and text protected void GenerateToken(TSqlTokenType tokenType, String text) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs index a5136c96..b9890514 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.cs @@ -17,6 +17,7 @@ internal abstract partial class SqlScriptGeneratorVisitor : TSqlConcreteFragment protected const String SetClauseItemFirstEqualSign = "SetClauseItemFirstEqualSign"; protected const String SetClauseItemSecondEqualSign = "SetClauseItemSecondEqualSign"; protected const String InsertColumns = "InsertColumns"; + protected const String SelectColumnAliasEqualSign = "SelectColumnAliasEqualSign"; #endregion @@ -26,6 +27,14 @@ internal abstract partial class SqlScriptGeneratorVisitor : TSqlConcreteFragment protected ScriptWriter _writer; private Dictionary> _alignmentPointsForFragments; + // The alignment point used to vertically align the "=" signs of "alias = expression" + // column aliases for the SELECT list currently being rendered. Held as a field (rather + // than resolved by name through the writer's per-scope name map) so that it survives the + // per-item alignment scopes that GenerateFragmentList pushes when PreserveComments is + // enabled, allowing the "=" signs to align across all rows. Null outside a multiline, + // clause-body-aligned SELECT projection. Saved/restored around nested SELECT projections. + private AlignmentPoint _selectColumnAliasEqualSignAlignmentPoint; + #endregion #region constructor @@ -93,6 +102,30 @@ protected void MarkAndPushAlignmentPoint(AlignmentPoint ap) PushAlignmentPoint(ap); } + // Like MarkAndPushAlignmentPoint, but keeps the current named-alignment-point scope instead + // of starting a fresh one. Used when the pushed point exists only to restore indentation for + // comment-driven newlines and must not isolate named alignment points (e.g. column-definition + // field alignment) from the surrounding list, which would defeat cross-line alignment. + protected void MarkAndPushAlignmentPointKeepingNameScope(AlignmentPoint ap) + { + Mark(ap); + _writer.PushNewLineAlignmentPoint(ap, resetNameScope: false); + } + + // Isolates named alignment points created while rendering a list so they are shared among the + // list's items but do not leak into the enclosing scope (which would let separate lists in the + // same parent scope align against each other). Adds no alignment point at the current position + // and leaves newline restoration unchanged. + protected void PushNamedAlignmentScope() + { + _writer.PushNamedAlignmentScope(); + } + + protected void PopNamedAlignmentScope() + { + _writer.PopNamedAlignmentScope(); + } + protected AlignmentPoint FindOrCreateAlignmentPointByName(String apName) { return _writer.FindOrCreateAlignmentPoint(apName); diff --git a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml index 44853885..6225d168 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml +++ b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml @@ -14,6 +14,19 @@ Gets or sets the keyword casing option to use during script generation + + + + + + Gets or sets the casing applied to object identifiers during script generation. This does not affect keywords, string literals, function names, or variables. + + + + + + Gets or sets how square brackets are applied to object identifiers during script generation. IncludeBrackets wraps all identifiers in square brackets; ExcludeBrackets removes brackets from identifiers that do not require them (identifiers conflicting with reserved words for the configured SqlVersion or containing special characters retain their brackets). + Gets or sets the Sql version to generate script for @@ -21,7 +34,10 @@ Gets or sets the Sql engine type (All|Engine|Azure) to generate script for - Gets or sets the number of spaces to use when indenting text + Gets or sets the number of spaces to use when indenting text. In Tabs mode each tab is treated as this many columns wide when computing alignment, so the viewer's tab size must be set to this value for the generated output to appear aligned. + + + Gets or sets whether indentation is written using spaces or tab characters. In Tabs mode the generated alignment only lines up when the viewer's tab width (for example the editor's tab size) equals IndentationSize. This setting is ignored (indentation uses spaces) when CommaPlacement is Leading. IncludeSemicolons_Title @@ -46,6 +62,9 @@ Gets or sets a boolean indicating if comments from the original script should be preserved in the generated output + + Gets or sets a value indicating whether commas in a multi-line comma-separated list are placed at the end of the line (trailing) or at the start of the next line (leading). When set to Leading, the IndentationMode setting is ignored and indentation always uses spaces. + @@ -74,6 +93,12 @@ Gets or sets a boolean indicating if there should be a newline before the JOIN clause in a SELECT statement + + Gets or sets a boolean indicating if there should be a newline after the JOIN keyword (before the table source). When false, the table source is kept on the same line as the JOIN keyword. + + + Gets or sets a boolean indicating if there should be a newline before the ON keyword of a JOIN. When false, the ON keyword is kept on the same line as the table source. + Gets or sets a boolean indicating if there should be a newline before the OFFSET clause @@ -93,6 +118,12 @@ Gets or sets a boolean indicating if WHERE predicates (expressions separated by AND, and OR) should be written on multiple lines + + + + + Gets or sets a value indicating how column aliases in SELECT projections are rendered (AS keyword, equals sign, or preserved from the original script) + diff --git a/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs b/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs new file mode 100644 index 00000000..158ca0af --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs @@ -0,0 +1,577 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the ColumnAliasStyle script-generation option (AsKeyword / EqualsSign / Preserve). + // Kept in a dedicated file to avoid churn in ScriptGeneratorTests.cs. + [TestClass] + public class ColumnAliasStyleTests + { + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleDefaultIsAsKeyword() + { + Assert.AreEqual(ColumnAliasStyle.AsKeyword, new SqlScriptGeneratorOptions().ColumnAliasStyle); + } + + // --------------------------------------------------------------------------------------- + // SELECT-projection behavior: conversion between styles, '=' alignment, Preserve, and the + // pass-through cases where the option must leave a projection element unchanged. + // --------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignSelectProjectionRoundTrips() + { + string generated = Generate( + "SELECT a AS x, b AS y FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT x = a," + Environment.NewLine + + " y = b" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignSingleLineSelect() + { + // MultilineSelectElementsList == false exercises the single-line branch. + string generated = Generate( + "SELECT a AS x FROM t;", + new SqlScriptGeneratorOptions + { + ColumnAliasStyle = ColumnAliasStyle.EqualsSign, + MultilineSelectElementsList = false + }); + + string expected = + "SELECT x = a" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignLeavesSelectStarAndUnaliasedColumns() + { + // '*' (SelectStarExpression) and unaliased columns have no alias to convert. + string generated = Generate( + "SELECT *, a, b AS y FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT *," + Environment.NewLine + + " a," + Environment.NewLine + + " y = b" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignLeavesSelectSetVariable() + { + // 'SELECT @v = a' is a SelectSetVariable, not a SelectScalarExpression column alias, + // so the option must not alter it. + string generated = Generate( + "SELECT @v = a FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT @v = a" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleAsKeywordLeavesSelectSetVariable() + { + // 'SELECT @v = a' is a SelectSetVariable, not a SelectScalarExpression column alias, + // so AsKeyword must not rewrite it into 'a AS @v'. + string generated = Generate( + "SELECT @v = a FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.AsKeyword }); + + string expected = + "SELECT @v = a" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleAsKeywordConvertsFromEqualsSign() + { + // AsKeyword rewrites "alias = expression" into "expression AS alias". + string generated = Generate( + "SELECT x = a, y = bb FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.AsKeyword }); + + string expected = + "SELECT a AS x," + Environment.NewLine + + " bb AS y" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignConvertsFromAsKeyword() + { + // EqualsSign rewrites "expression AS alias" into "alias = expression" and aligns the + // '=' signs within the SELECT list when AlignClauseBodies is on (the default). + string generated = Generate( + "SELECT a AS col1, bb AS c FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT col1 = a," + Environment.NewLine + + " c = bb" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignConvertsDelimitedAndStringAliases() + { + // The alias (ColumnName) is an IdentifierOrValueExpression: it can be a delimited + // identifier or a string literal, both of which are valid on the left of '='. + string generated = Generate( + "SELECT a AS [My Col], b AS 'Str Alias' FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT [My Col] = a," + Environment.NewLine + + " 'Str Alias' = b" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignNoAlignment() + { + // With AlignClauseBodies off, EqualsSign still applies but the '=' signs are not padded. + string generated = Generate( + "SELECT a AS col1, bb AS c FROM t;", + new SqlScriptGeneratorOptions + { + ColumnAliasStyle = ColumnAliasStyle.EqualsSign, + AlignClauseBodies = false + }); + + string expected = + "SELECT col1 = a," + Environment.NewLine + + " c = bb" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignSingleLineList() + { + // With MultilineSelectElementsList off, the list stays on one line and no '=' alignment + // is performed. + string generated = Generate( + "SELECT a AS col1, bb AS c FROM t;", + new SqlScriptGeneratorOptions + { + ColumnAliasStyle = ColumnAliasStyle.EqualsSign, + MultilineSelectElementsList = false + }); + + string expected = + "SELECT col1 = a, c = bb" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignLeavesUnaliasedExpressionsUnchanged() + { + // Expressions without an explicit alias are not affected by the option. + string generated = Generate( + "SELECT a, b AS c FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT a," + Environment.NewLine + + " c = b" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignLeavesTableAliasUnchanged() + { + // Table aliases must remain AS-style regardless of ColumnAliasStyle. + string generated = Generate( + "SELECT t.a AS c FROM t AS t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT c = t.a" + Environment.NewLine + + "FROM t AS t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveKeepsEqualsSign() + { + // Preserve keeps the original equals-sign form. + string generated = Generate( + "SELECT col1 = a, c = bb FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + + string expected = + "SELECT col1 = a," + Environment.NewLine + + " c = bb" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveKeepsAsKeyword() + { + // Preserve keeps the original AS-keyword form. + string generated = Generate( + "SELECT a AS col1, bb AS c FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + + string expected = + "SELECT a AS col1," + Environment.NewLine + + " bb AS c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveMixedForms() + { + // Preserve keeps each column's original style independently. + string generated = Generate( + "SELECT col1 = a, bb AS c FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + + string expected = + "SELECT col1 = a," + Environment.NewLine + + " bb AS c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignNestedSubqueryAlignsIndependently() + { + // The outer and inner SELECT lists align their '=' signs independently. + string generated = Generate( + "SELECT longName = (SELECT x = 1), y = 2 FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT longName = (SELECT x = 1)," + Environment.NewLine + + " y = 2" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleAsKeywordConvertsFromEqualsSignInCommonTableExpression() + { + // The option applies to the SELECT list inside a CTE body, while the CTE's own column + // list "(alias1, alias2)" is a definition and must remain unchanged. + string generated = Generate( + "WITH cte (alias1, alias2) AS (SELECT alias1 = a, alias2 = bb FROM t) SELECT * FROM cte;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.AsKeyword }); + + string expected = + "WITH cte (alias1, alias2)" + Environment.NewLine + + "AS (SELECT a AS alias1," + Environment.NewLine + + " bb AS alias2" + Environment.NewLine + + " FROM t)" + Environment.NewLine + + "SELECT *" + Environment.NewLine + + "FROM cte;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignConvertsFromAsKeywordWithSubqueries() + { + // Converting AS -> '=' across a scalar subquery in the projection and a derived-table + // subquery in FROM. Each SELECT list aligns its '=' independently, and the derived + // table alias ("AS o") remains AS-style. + string generated = Generate( + "SELECT o.total AS grandTotal, (SELECT COUNT(*) FROM t2) AS cnt " + + "FROM (SELECT SUM(x) AS total FROM t1) AS o;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "SELECT grandTotal = o.total," + Environment.NewLine + + " cnt = (SELECT COUNT(*)" + Environment.NewLine + + " FROM t2)" + Environment.NewLine + + "FROM (SELECT total = SUM(x)" + Environment.NewLine + + " FROM t1) AS o;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveOnProgrammaticallyBuiltFragmentRendersAsKeyword() + { + // A fragment built in code has no source token positions, so Preserve cannot detect an + // original equals-sign form and falls back to AS-keyword rendering. + var scalar = new SelectScalarExpression + { + Expression = new ColumnReferenceExpression + { + MultiPartIdentifier = new MultiPartIdentifier { Identifiers = { new Identifier { Value = "a" } } } + }, + ColumnName = new IdentifierOrValueExpression { Identifier = new Identifier { Value = "x" } } + }; + + var query = new QuerySpecification(); + query.SelectElements.Add(scalar); + var select = new SelectStatement { QueryExpression = query }; + + var generator = new Sql170ScriptGenerator( + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + generator.GenerateScript(select, out string generated); + + string expected = "SELECT a AS x"; + + Assert.AreEqual(expected, generated); + } + + // --------------------------------------------------------------------------------------- + // Context-scoping tests: the "alias = expression" form is valid ONLY in a SELECT + // projection list. OUTPUT, OUTPUT INTO and RECEIVE reuse SelectScalarExpression but their + // grammar (outputClauseSelectColumn / receiveColumnSelectExpression) does NOT accept the + // equals-sign form, so ColumnAliasStyle must never rewrite aliases in those contexts. + // Generate() also re-parses the output, which is the key regression guard: before scoping, + // the generated "alias = expression" output could not be re-parsed in these contexts. + // --------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignDoesNotApplyToOutputClause() + { + string generated = Generate( + "DELETE dbo.T OUTPUT deleted.Id AS OldId;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "DELETE dbo.T" + Environment.NewLine + + "OUTPUT deleted.Id AS OldId;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignDoesNotApplyToOutputIntoClause() + { + string generated = Generate( + "DELETE dbo.T OUTPUT deleted.Id AS OldId INTO dbo.Removed (OldId);", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "DELETE dbo.T" + Environment.NewLine + + "OUTPUT deleted.Id AS OldId INTO dbo.Removed (OldId);" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveDoesNotApplyToOutputClause() + { + // OUTPUT can only ever be authored in AS form, so Preserve must round-trip it unchanged. + string generated = Generate( + "DELETE dbo.T OUTPUT deleted.Id AS OldId;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + + string expected = + "DELETE dbo.T" + Environment.NewLine + + "OUTPUT deleted.Id AS OldId;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignDoesNotApplyToReceiveStatement() + { + string generated = Generate( + "RECEIVE TOP (1) conversation_handle AS Handle FROM dbo.TargetQueue;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "RECEIVE TOP (1) conversation_handle AS Handle FROM dbo.TargetQueue;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignOutputAliasAndDerivedTableProjectionDoNotInterfere() + { + // A single statement mixes a non-projection OUTPUT alias (must stay AS) with a real + // derived-table projection (must convert). This exercises the save/restore of the + // in-projection flag: the derived-table SELECT sets it true and restores it, so the + // sibling OUTPUT column is never rewritten. + string generated = Generate( + "UPDATE t SET a = 1 OUTPUT inserted.a AS x " + + "FROM dbo.Target AS t INNER JOIN (SELECT v AS w FROM dbo.Src) AS d ON t.k = d.k;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }); + + string expected = + "UPDATE t" + Environment.NewLine + + "SET a = 1" + Environment.NewLine + + "OUTPUT inserted.a AS x" + Environment.NewLine + + "FROM dbo.Target AS t" + Environment.NewLine + + " INNER JOIN" + Environment.NewLine + + " (SELECT w = v" + Environment.NewLine + + " FROM dbo.Src) AS d" + Environment.NewLine + + " ON t.k = d.k;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignWithPreserveCommentsRepositionsInlineComment() + { + // Known limitation: converting "expr AS alias" -> "alias = expr" reorders the alias + // ahead of the expression. With PreserveComments on, a comment authored between the + // expression and the AS keyword has no faithful home in the reordered text, so it is + // preserved (never dropped) but repositioned to the start of the element. The output + // still round-trips (Generate() asserts it re-parses). + string generated = Generate( + "SELECT a /* mid */ AS x, bb AS y FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign, PreserveComments = true }); + + string expected = + "SELECT /* mid */" + Environment.NewLine + + " x = a," + Environment.NewLine + + " y = bb" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignWithPreserveCommentsAlignsEqualSignsAcrossRows() + { + // Regression: with PreserveComments on, GenerateFragmentList pushes a per-row alignment + // scope for each select element. The '=' alignment point must still be shared across + // rows so the '=' signs line up to the widest alias, exactly as when PreserveComments + // is off. (Aliases of different widths are required to observe the alignment.) + string generated = Generate( + "SELECT a AS col1, bb AS c FROM t;", + new SqlScriptGeneratorOptions + { + ColumnAliasStyle = ColumnAliasStyle.EqualsSign, + PreserveComments = true + }); + + string expected = + "SELECT col1 = a," + Environment.NewLine + + " c = bb" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveWithCommentsKeepsCommentInPlace() + { + // Preserve never reorders the alias and expression, so PreserveComments keeps inline + // comments exactly where they were authored (contrast with the EqualsSign conversion, + // which repositions them). + string generated = Generate( + "SELECT a /* mid */ AS x, bb AS y FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve, PreserveComments = true }); + + string expected = + "SELECT a /* mid */ AS x," + Environment.NewLine + + " bb AS y" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs b/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs new file mode 100644 index 00000000..61865b68 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs @@ -0,0 +1,1008 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System.Collections.Generic; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the IdentifierCasing and IdentifierBracketing script-generation options. + // Kept in a dedicated file to avoid churn in ScriptGeneratorTests.cs. + // + // The default option values (IdentifierCasing.Preserve and IdentifierBracketing.Preserve) leave + // generated script unchanged versus the previous formatter behavior. The two "DefaultIs..." tests + // pin the defaults, and TestDefaultOptionsArePureIdentity checks the default path is a no-op + // across every construct the change touches. + // + // Expected values follow the JoinClauseFormattingTests pattern: verbatim @"..." literals compared + // via the shared AssertGenerated helper (which normalizes line endings and trims). + // + // Work item: Formatter option: Identifier bracketing and casing + [TestClass] + public class IdentifierFormattingTests + { + // Builds options that toggle the identifier casing/bracketing under test while disabling + // unrelated multi-line/alignment formatting, so the expected literals stay focused on the + // identifier transformation itself. + private static SqlScriptGeneratorOptions MakeOptions(IdentifierCasing casing, IdentifierBracketing bracketing) + { + return new SqlScriptGeneratorOptions + { + IdentifierCasing = casing, + IdentifierBracketing = bracketing, + AlignColumnDefinitionFields = false, + AlignClauseBodies = false, + NewLineBeforeFromClause = false, + MultilineSelectElementsList = false, + }; + } + + // Parses with the given (version-specific) parser and generates with the matching generator, + // so the ExcludeBrackets reserved-word probe runs against that SqlVersion. Used to demonstrate + // version-specific bracketing behavior. + private static void AssertGeneratedWith( + TSqlParser parser, + SqlScriptGenerator generator, + string sql, + string expected) + { + TSqlFragment fragment = parser.Parse(new StringReader(sql), out IList errors); + Assert.AreEqual(0, errors.Count, "Input must parse without errors."); + + generator.GenerateScript(fragment, out string generated); + Assert.AreEqual(Normalize(expected).Trim(), Normalize(generated).Trim()); + } + + // ----------------------------------------------------------------------------------------- + // Defaults + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierCasingDefaultIsPreserve() + { + Assert.AreEqual(IdentifierCasing.Preserve, new SqlScriptGeneratorOptions().IdentifierCasing); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingDefaultIsPreserve() + { + Assert.AreEqual(IdentifierBracketing.Preserve, new SqlScriptGeneratorOptions().IdentifierBracketing); + } + + // With the default (Preserve/Preserve) options the identifier code path is a pure identity + // across every delimiter style and every construct the change touches (pre-bracketed, + // double-quoted, plain, @variable, schema-qualified + built-in function names, and a label). + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultOptionsArePureIdentity() + { + const string input = @" +GOTO MyLabel; +MyLabel: +SELECT [Bracketed], ""Quoted"", Plain, @Var, dbo.MyFunc(Col), LEN(Col2) FROM [My Tbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.Preserve); + const string expected = @" +GOTO MyLabel; + +MyLabel: + +SELECT [Bracketed], ""Quoted"", Plain, @Var, dbo.MyFunc(Col), LEN(Col2) FROM [My Tbl];"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // IdentifierCasing + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierCasingPreserveLeavesIdentifiersUnchanged() + { + const string input = "SELECT MyCol FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.Preserve); + const string expected = @"SELECT MyCol FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierCasingLowercase() + { + // Identifiers lowered; keywords stay uppercase (governed by KeywordCasing). + const string input = "SELECT MyCol FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT mycol FROM mytbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierCasingUppercase() + { + const string input = "SELECT MyCol FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Uppercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT MYCOL FROM MYTBL;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierCasingDoesNotAffectStringLiteralsOrVariables() + { + // Interaction rule: casing must not touch @variables or string literals. + const string input = "SELECT @MyVar, 'StrLit' FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT @MyVar, 'StrLit' FROM mytbl;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // IdentifierBracketing + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingIncludeBracketsWrapsAllIdentifiers() + { + const string input = "SELECT MyCol FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [MyCol] FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingIncludeBracketsWrapsMultiPartName() + { + const string input = "SELECT MySchema.MyTbl.MyCol FROM MySchema.MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [MySchema].[MyTbl].[MyCol] FROM [MySchema].[MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsRemovesUnnecessaryBrackets() + { + const string input = "SELECT [MyCol] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT MyCol FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsRetainsReservedWord() + { + // A reserved word (for the configured SqlVersion) must keep its brackets. + const string input = "SELECT [SELECT] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT [SELECT] FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsRetainsSpecialCharacters() + { + // An identifier containing a space must keep its brackets. + const string input = "SELECT [My Col] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT [My Col] FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingIncludeBracketsWrapsAliasDeclarationsAndReferences() + { + // The work item requires IncludeBrackets to wrap alias declarations and all references: + // the table alias (x), the column alias (a), and the references (t, c) are all bracketed. + const string input = "SELECT c AS a FROM t AS x;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [c] AS [a] FROM [t] AS [x];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingIncludeBracketsDoesNotDoubleBracket() + { + // Already-bracketed identifiers stay singly bracketed (no [[MyCol]]). + const string input = "SELECT [MyCol] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [MyCol] FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingIncludeBracketsEscapesClosingBracket() + { + // A closing bracket inside the identifier value must be escaped as ]] when bracketing. + const string input = "SELECT [a]]b] FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [a]]b] FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsRetainsEscapedClosingBracket() + { + // An identifier containing a closing bracket must keep (and re-escape) its brackets. + const string input = "SELECT [a]]b] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT [a]]b] FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsPreservesDoubleQuotedIdentifiers() + { + // ExcludeBrackets controls square brackets only, so double-quoted identifiers keep their + // double quotes - both the reserved word and the regular name are preserved. + const string input = "SELECT \"SELECT\" FROM \"MyTbl\";"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT ""SELECT"" FROM ""MyTbl"";"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsReservedWordIsVersionSpecific() + { + // The ExcludeBrackets reserved-word check honors the configured SqlVersion. PIVOT is a + // keyword starting with SQL Server 2005 but a regular identifier in SQL Server 2000 (80), + // so the same input keeps its brackets under 170 and drops them under 80. + const string input = "SELECT [PIVOT] FROM [MyTbl];"; + + // SQL Server 2000 (80): PIVOT is a regular identifier, so its brackets are removed. + AssertGeneratedWith( + new TSql80Parser(true), + new Sql80ScriptGenerator(MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets)), + input, + @"SELECT PIVOT FROM MyTbl;"); + + // SQL Server 2025 (170): PIVOT is a keyword, so it retains its brackets. + AssertGeneratedWith( + new TSql170Parser(true), + new Sql170ScriptGenerator(MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets)), + input, + @"SELECT [PIVOT] FROM MyTbl;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsLeavesUnquotedIdentifiersUntouched() + { + // Coverage: ExcludeBrackets on already-unquoted identifiers is a no-op (the probe is + // skipped for QuoteType.NotQuoted); the identifiers pass through unchanged. + const string input = "SELECT MyCol FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT MyCol FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsRetainsOpeningBracketSpecialChar() + { + // Coverage: a value containing an unescaped '[' cannot be re-lexed as a single identifier + // (it produces a lex error), so the probe reports it as needing brackets and they are kept. + const string input = "SELECT [a[b] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT [a[b] FROM MyTbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSuppressedFunctionNamePreservesOriginalBracketingAndCasing() + { + // Coverage: a bracketed function name exercises the suppressed + quoted emit path. Under + // IncludeBrackets + Uppercase the function name keeps its exact original form ([MyFunc]), + // while the schema, argument, and table are still bracketed and uppercased. + const string input = "SELECT dbo.[MyFunc](Col) FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Uppercase, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [DBO].[MyFunc]([COL]) FROM [MYTBL];"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction: casing is applied after bracketing + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingAndCasingCombined() + { + // ExcludeBrackets removes safe brackets, then Lowercase recases the value; the + // reserved word retains its brackets but is still recased. + const string input = "SELECT [SELECT], [MyCol] FROM [MyTbl];"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT [select], mycol FROM mytbl;"; + + AssertGenerated(input, options, expected); + } + + // ========================================================================================= + // GAP documentation + // + // The identifier options are applied centrally in ExplicitVisit(Identifier). The tests below + // document intentional boundaries and safe-choice behaviors that are NOT spelled out in the + // work item but are required to avoid generating invalid T-SQL or to keep the scope sane. + // ========================================================================================= + + // GAP-LABEL: GoToStatement.LabelName is an Identifier fragment, but T-SQL labels cannot be + // delimited (GOTO [x] is invalid) and the reference must keep matching the never-recased + // label declaration emitted by LabelStatement. Therefore identifier formatting is suppressed + // for label references: neither IncludeBrackets nor casing is applied. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapLabelIncludeBracketsDoesNotBracketLabel() + { + // The label declaration (MyLabel:) and the GOTO reference both stay unbracketed, while a + // regular identifier (MyCol) in the same batch is still wrapped in brackets. + const string input = @" +GOTO MyLabel; +MyLabel: +SELECT MyCol;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @" +GOTO MyLabel; + +MyLabel: + +SELECT [MyCol];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapLabelCasingDoesNotRecaseLabel() + { + const string input = "GOTO MyLabel;"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.Preserve); + const string expected = @"GOTO MyLabel;"; + + AssertGenerated(input, options, expected); + } + + // GAP-FUNC-SCOPE: Only the function's own name is excluded from formatting. A schema + // qualifier on a user-defined function (dbo in dbo.MyFunc) IS still transformed, because + // bracketing/recasing a schema is valid T-SQL. This documents the boundary of the + // "function names" exclusion (built-in/function-name casing is a separate future option). + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapFunctionNamePreservedButSchemaQualifierTransformed() + { + const string input = "SELECT dbo.MyFunc(MyCol) FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT dbo.MyFunc(mycol) FROM mytbl;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapBuiltInFunctionNamePreserved() + { + // A built-in function name (LEN) is left untouched while its argument identifier is recased. + const string input = "SELECT LEN(MyCol) FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT LEN(mycol) FROM mytbl;"; + + AssertGenerated(input, options, expected); + } + + // GAP-PASCAL: PascalCase reuses the existing GetPascalCase helper, which only capitalizes the + // first character of the whole value (not per word). A quoted multi-word identifier therefore + // becomes "[My col]", not "[My Col]". + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapPascalCaseOnlyCapitalizesFirstCharacter() + { + const string input = "SELECT [my col] FROM MYTBL;"; + var options = MakeOptions(IdentifierCasing.PascalCase, IdentifierBracketing.Preserve); + const string expected = @"SELECT [My col] FROM Mytbl;"; + + AssertGenerated(input, options, expected); + } + + // GAP-DQUOTE: IdentifierBracketing controls square brackets only. IncludeBrackets normalizes an + // identifier to square brackets (a double-quoted "MyCol" becomes [MyCol]); ExcludeBrackets + // removes square brackets only and preserves other quote types (a double-quoted "MyCol" stays + // "MyCol"). + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapDoubleQuotedIdentifierIncludeBracketsConvertsToSquareBrackets() + { + const string input = "SELECT \"MyCol\" FROM \"MyTbl\";"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [MyCol] FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapDoubleQuotedIdentifierExcludeBracketsPreservesQuoting() + { + const string input = "SELECT \"MyCol\" FROM \"MyTbl\";"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT ""MyCol"" FROM ""MyTbl"";"; + + AssertGenerated(input, options, expected); + } + + // GAP-VARIABLE: variable and parameter names are Identifier fragments whose value starts with + // '@'. They must never be bracketed ('[@x]' is invalid T-SQL) or recased (the interaction + // rules exclude @variables), so the options leave them untouched while surrounding object + // identifiers are still transformed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapVariableDeclarationIncludeBracketsDoesNotBracketVariable() + { + const string input = "DECLARE @MyVar INT;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"DECLARE @MyVar AS INT;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapVariableDeclarationCasingDoesNotRecaseVariable() + { + const string input = "DECLARE @MyVar INT;"; + var options = MakeOptions(IdentifierCasing.Uppercase, IdentifierBracketing.Preserve); + const string expected = @"DECLARE @MyVar AS INT;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapDelimitedAtNameIsTransformedAsObjectIdentifier() + { + // A delimited [@Name] is an object identifier (QuoteType.SquareBracket), not a variable, + // so - unlike an unquoted @variable - it still participates in the identifier options. + const string input = "SELECT [@Name] FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Uppercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT [@NAME] FROM MYTBL;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapTableVariableIncludeBracketsBracketsColumnsButNotVariable() + { + const string input = "DECLARE @MyTable TABLE (MyCol INT);"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @" +DECLARE @MyTable TABLE ( + [MyCol] INT);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapProcedureParameterIncludeBracketsBracketsProcNameButNotParameter() + { + const string input = "CREATE PROCEDURE MyProc @MyParam INT AS RETURN;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @" +CREATE PROCEDURE [MyProc] +@MyParam INT +AS +RETURN;"; + + AssertGenerated(input, options, expected); + } + + // GAP-TEMPTABLE: temp table names are Identifier fragments whose value starts with '#' (local) + // or '##' (global). Unlike @variables, bracketing them is valid T-SQL ([#Temp] is legal), so + // temp tables are intentionally NOT excluded: the options transform them like any other object + // identifier. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapLocalTempTableIncludeBracketsWrapsName() + { + const string input = "SELECT * FROM #Temp;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT * FROM [#Temp];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapLocalTempTableExcludeBracketsRemovesBrackets() + { + const string input = "SELECT * FROM [#Temp];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT * FROM #Temp;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapGlobalTempTableIncludeBracketsWrapsName() + { + const string input = "SELECT * FROM ##Temp;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT * FROM [##Temp];"; + + AssertGenerated(input, options, expected); + } + + // GAP-SYNTAX-KEYWORD: some syntax options are stored in the AST as Identifier fragments even + // though they are keywords (JSON ABSENT ON NULL, TRIM LEADING/TRAILING/BOTH, window + // IGNORE/RESPECT NULLS). They must never be bracketed or recased - e.g. "[ABSENT] ON NULL" is + // invalid T-SQL - so the options leave them untouched while real object identifiers around + // them are still transformed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapJsonAbsentOnNullNotBracketed() + { + const string input = "SELECT JSON_OBJECT('a':1 ABSENT ON NULL);"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT JSON_OBJECT('a':1 ABSENT ON NULL);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapTrimOptionNotBracketed() + { + const string input = "SELECT TRIM(LEADING ' ' FROM MyCol) FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT TRIM( LEADING ' ' FROM [MyCol]) FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapIgnoreNullsNotBracketed() + { + const string input = "SELECT LAST_VALUE(MyCol) IGNORE NULLS OVER (ORDER BY MyId) FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT LAST_VALUE([MyCol]) IGNORE NULLS OVER (ORDER BY [MyId]) FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + // GAP-COLLATE: a collation name is stored as an Identifier fragment but cannot be delimited + // (COLLATE [name] is invalid T-SQL) or recased, so the options leave it untouched while the + // surrounding column/table identifiers are still transformed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapCollationNameNotBracketed() + { + const string input = "SELECT MyCol COLLATE SQL_Latin1_General_CP1_CI_AS FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT [MyCol] COLLATE SQL_Latin1_General_CP1_CI_AS FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapCollationNameNotRecased() + { + const string input = "SELECT MyCol COLLATE SQL_Latin1_General_CP1_CI_AS FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Lowercase, IdentifierBracketing.Preserve); + const string expected = @"SELECT mycol COLLATE SQL_Latin1_General_CP1_CI_AS FROM mytbl;"; + + AssertGenerated(input, options, expected); + } + + // GAP-EMPTY-VALUE: an empty Identifier.Value must be returned unchanged for every casing. + // PascalCase would otherwise index str[0] and throw during script generation. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestEmptyIdentifierValueIsNotRecased() + { + Assert.AreEqual(string.Empty, ScriptGeneratorSupporter.GetCasedString(string.Empty, IdentifierCasing.PascalCase)); + Assert.AreEqual(string.Empty, ScriptGeneratorSupporter.GetCasedString(string.Empty, IdentifierCasing.Uppercase)); + Assert.AreEqual(string.Empty, ScriptGeneratorSupporter.GetCasedString(string.Empty, IdentifierCasing.Lowercase)); + Assert.AreEqual(string.Empty, ScriptGeneratorSupporter.GetCasedString(string.Empty, IdentifierCasing.Preserve)); + } + + // GAP-MULTIPART: an omitted component of a multi-part name (e.g. the missing schema in + // "db..t") is an Identifier fragment with an empty Value. IncludeBrackets must preserve it as + // an empty, unquoted component - bracketing it to "[]" produces invalid T-SQL (SQL46010). + // Present parts are still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapMultipartOmittedComponentNotBracketed() + { + const string input = "SELECT * FROM db..t;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT * FROM [db]..[t];"; + + AssertGenerated(input, options, expected); + } + + // GAP-MULTIPART (four-part): omitted parts in a server-qualified name are likewise preserved, + // whether the omitted part is in the middle or leading interior position. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapFourPartOmittedComponentsNotBracketed() + { + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + + AssertGenerated("SELECT * FROM srv.db..t;", options, @"SELECT * FROM [srv].[db]..[t];"); + AssertGenerated("SELECT * FROM srv..sch.t;", options, @"SELECT * FROM [srv]..[sch].[t];"); + } + + // ----------------------------------------------------------------------------------------- + // GAP-KEYWORD-POSITION: further Identifier fragments that hold keywords / syntax words rather + // than object names. Bracketing or recasing them produces invalid T-SQL, so the emit sites + // suppress identifier formatting for them while real object identifiers around them are still + // transformed. Each test asserts the complete generated script (AssertGenerated also reparses + // the output, which is the round-trip invariant each of these fixes restores). + // ----------------------------------------------------------------------------------------- + + // GAP-PERMISSION: permission names (ALTER, ANY, SCHEMA, ...) are Identifier fragments but are + // keywords - "GRANT [ALTER] [ANY] [SCHEMA]" is invalid. The grantee is still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapPermissionNamesNotBracketed() + { + const string input = "GRANT ALTER ANY SCHEMA TO user1;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"GRANT ALTER ANY SCHEMA TO [user1];"; + + AssertGenerated(input, options, expected); + } + + // GAP-PERMISSION (GRANT): Permission.Identifiers holds the syntax keyword SELECT, not an object + // name; "GRANT [SELECT]" is rejected by the parser. The securable and principal are bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapPermissionGrantSelectNotBracketed() + { + const string input = "GRANT SELECT ON OBJECT::dbo.t TO u;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"GRANT SELECT + ON OBJECT::[dbo].[t] TO [u];"; + + AssertGenerated(input, options, expected); + } + + // GAP-PERMISSION (DENY): same rule for the DENY variant. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapPermissionDenySelectNotBracketed() + { + const string input = "DENY SELECT ON OBJECT::dbo.t TO u;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"DENY SELECT + ON OBJECT::[dbo].[t] TO [u];"; + + AssertGenerated(input, options, expected); + } + + // GAP-PERMISSION (REVOKE): same rule for the REVOKE variant (the generator normalizes REVOKE + // ... FROM to REVOKE ... TO, which round-trips). + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapPermissionRevokeSelectNotBracketed() + { + const string input = "REVOKE SELECT ON OBJECT::dbo.t FROM u;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"REVOKE SELECT + ON OBJECT::[dbo].[t] TO [u];"; + + AssertGenerated(input, options, expected); + } + + // GAP-ODBC: the ODBC escape-function name and the ODBC data-type name are Identifier fragments + // holding keywords; "{ fn [convert] (...) }" / "[SQL_INTEGER]" are invalid. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapOdbcConvertNotBracketed() + { + const string input = "SELECT { fn convert(MyCol, SQL_INTEGER) } FROM MyTbl;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT { FN convert ([MyCol], SQL_INTEGER) } FROM [MyTbl];"; + + AssertGenerated(input, options, expected); + } + + // GAP-FEDERATION: the federation name must be a plain identifier ("USE FEDERATION [f1]" is + // invalid), but the distribution name is a normal identifier and is still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapFederationNameNotBracketed() + { + const string input = "use federation f1 (d1 = 20) with filtering=on, reset"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"USE FEDERATION f1 ([d1] = 20) WITH FILTERING = ON, RESET;"; + + AssertGenerated(input, options, expected); + } + + // GAP-WINDOW: an unparenthesized "OVER window_name" reference must be a plain identifier + // ("OVER [Win1]" is invalid), while the WINDOW clause definition name may be bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapWindowOverReferenceNotBracketed() + { + const string input = "SELECT Sum(c1) OVER Win1 FROM t1 WINDOW Win1 AS (PARTITION BY c1)"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"SELECT Sum([c1]) OVER Win1 FROM [t1] +WINDOW [Win1] AS (PARTITION BY [c1]);"; + + AssertGenerated(input, options, expected); + } + + // GAP-TIMESTAMP: the INSERT BULK timestamp/rowversion shorthand column has no data type and its + // name is the TIMESTAMP keyword ("([c2] CHAR, [TIMESTAMP])" is invalid); regular columns are + // still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapInsertBulkTimestampColumnNotBracketed() + { + const string input = "insert bulk dbo.t1 (c1 int not null, c2 char, timestamp)"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"INSERT BULK [dbo].[t1] ([c1] INT NOT NULL, [c2] CHAR, TIMESTAMP);"; + + AssertGenerated(input, options, expected); + } + + // GAP-PARTITION-COLLATE: the partition-function parameter collation is a collation name and + // cannot be delimited; the partition function name is still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapPartitionFunctionCollationNotBracketed() + { + const string input = "CREATE PARTITION FUNCTION myRangePF1 (char(10) COLLATE Estonian_CS_AS) AS RANGE RIGHT FOR VALUES (1)"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"CREATE PARTITION FUNCTION [myRangePF1](CHAR (10) COLLATE Estonian_CS_AS) + AS RANGE RIGHT + FOR VALUES (1);"; + + AssertGenerated(input, options, expected); + } + + // GAP-OPENROWSET-COLLATE: an OPENROWSET WITH column collation cannot be delimited; the column + // name is still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapOpenRowsetColumnCollationNotBracketed() + { + const string input = "select * from openrowset (bulk 'f1', format = 'CSV') with ([continent] varchar(100) collate latin1_general_bin2 2) as a;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT * FROM OPENROWSET (BULK 'f1', FORMAT = 'CSV') WITH ([continent] VARCHAR (100) COLLATE latin1_general_bin2 2) AS [a];"; + + AssertGenerated(input, options, expected); + } + + // GAP-FILETABLE-COLLATE: the FILETABLE_COLLATE_FILENAME option value is a collation name and + // cannot be delimited; the table name is still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapFileTableCollationValueNotBracketed() + { + const string input = "create table t1 as filetable with(filetable_collate_filename=Latin1_General_bin, filetable_directory=null)"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"CREATE TABLE [t1] AS FILETABLE +WITH (FILETABLE_COLLATE_FILENAME = Latin1_General_bin, FILETABLE_DIRECTORY = NULL);"; + + AssertGenerated(input, options, expected); + } + + // GAP-STOPLIST: "STOPLIST = SYSTEM" is a keyword option, not a stoplist name. The value is + // stored as an unquoted Identifier "SYSTEM"; bracketing it ("STOPLIST [SYSTEM]") makes the + // parser read it as a user-defined stoplist named SYSTEM, silently changing the meaning. The + // SYSTEM keyword must be preserved unbracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapFulltextStoplistSystemNotBracketed() + { + const string input = "ALTER FULLTEXT INDEX ON t SET STOPLIST = SYSTEM;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"ALTER FULLTEXT INDEX ON [t] SET STOPLIST SYSTEM;"; + + AssertGenerated(input, options, expected); + } + + // GAP-STOPLIST (user name): a real, user-defined stoplist name IS a normal identifier and is + // still bracketed under IncludeBrackets. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapFulltextStoplistUserNameBracketed() + { + const string input = "ALTER FULLTEXT INDEX ON t SET STOPLIST = MyStopList;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"ALTER FULLTEXT INDEX ON [t] SET STOPLIST [MyStopList];"; + + AssertGenerated(input, options, expected); + } + + // GAP-STOPLIST (CREATE): same rule on the CREATE FULLTEXT INDEX path (both paths share the + // StopListFullTextIndexOption emit site). + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapCreateFulltextStoplistSystemNotBracketed() + { + const string input = "CREATE FULLTEXT INDEX ON t (c) KEY INDEX i WITH STOPLIST = SYSTEM;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"CREATE FULLTEXT INDEX ON [t] + ([c]) + KEY INDEX [i] + WITH STOPLIST SYSTEM;"; + + AssertGenerated(input, options, expected); + } + + // GAP-TVF: built-in / global table-valued function names (STRING_SPLIT, OPENJSON, + // GENERATE_SERIES, ...) are stored on GlobalFunctionTableReference as Identifier names, but + // they are function names, not object names. Bracketing them ("[STRING_SPLIT]") makes the + // parser read them as user-defined functions, so they must stay unbracketed while a table + // alias is still bracketed. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapGlobalTableFunctionNameNotBracketed() + { + const string input = "SELECT * FROM STRING_SPLIT('a,b', ',') AS s;"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT * FROM STRING_SPLIT ('a,b', ',') AS [s];"; + + AssertGenerated(input, options, expected); + } + + // GAP-TVF (:: built-in): the "::function(...)" built-in table-function name + // (BuiltInFunctionTableReference) is likewise a function name, not an object name. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGapBuiltInTableFunctionNameNotBracketed() + { + const string input = "SELECT * FROM ::fn_helpcollations();"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = @"SELECT * FROM ::fn_helpcollations ();"; + + AssertGenerated(input, options, expected); + } + + // GAP-EXCLUDE-KEYWORD: ExcludeBrackets must keep brackets around a value that lexes to a + // keyword token (the reserved word KEY). Stripping them yields invalid T-SQL, so + // CanOmitBrackets only removes brackets from genuine Identifier tokens. The non-reserved + // table name loses its brackets as expected. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestExcludeBracketsKeepsBracketsAroundReservedKeyword() + { + const string input = "SELECT [key] FROM [t1];"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT [key] FROM t1;"; + + AssertGenerated(input, options, expected); + } + + // KNOWN LIMITATION (documented on IdentifierBracketing.ExcludeBrackets and CanOmitBrackets): + // AI_GENERATE_CHUNKS lexes as an ordinary identifier, so ExcludeBrackets removes the brackets + // that were forcing a regular table-valued-function parse. That changes semantics and the + // output does not round-trip, so this test uses AssertGeneratedWith (which does NOT reparse) + // to pin the accepted behavior. If ExcludeBrackets ever becomes context aware, update the + // expected value (it should then keep the brackets and reparse cleanly). + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestExcludeBracketsSpecialOperatorNameIsKnownLimitation() + { + const string input = "SELECT SOURCE FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS](SOURCE);"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + const string expected = @"SELECT SOURCE FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS(SOURCE);"; + + AssertGeneratedWith(new TSql170Parser(true), new Sql170ScriptGenerator(options), input, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/IndentationModeTests.cs b/Test/SqlDom/ScriptGenerator/IndentationModeTests.cs new file mode 100644 index 00000000..a86a0028 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/IndentationModeTests.cs @@ -0,0 +1,631 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // These tests verify the IndentationMode script generation option (Spaces vs Tabs). The + // expected constants are verbatim strings whose leading whitespace is real tab characters, so + // the expected output reads the same way it is written to the script. + [TestClass] + public class IndentationModeTests + { + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeDefaultIsSpaces() + { + Assert.AreEqual(IndentationMode.Spaces, new SqlScriptGeneratorOptions().IndentationMode); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsIndentsBlockBody() + { + // In Tabs mode the leading whitespace of every line is written with tab characters, + // and the gap between a clause keyword and its body is also a tab, so clause bodies + // line up on a tab stop. The SELECT-list and WHERE-predicate continuation lines round + // their indentation up to the same tab stop. + const string input = "BEGIN SELECT a, b FROM t WHERE a = 1 AND b = 2; END"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +BEGIN + SELECT a, + b + FROM t + WHERE a = 1 + AND b = 2; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsColumnDefinitionsSkipCommaPadding() + { + // The CREATE TABLE column definitions are indented with a tab and the gap between the + // column name and its data type is a tab. A column whose only remaining token is the + // comma is not padded to line up the commas, so the comma follows the data type directly. + const string input = "CREATE TABLE t (a INT, b NVARCHAR(10), c INT);"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +CREATE TABLE t ( + a INT, + b NVARCHAR (10), + c INT +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsColumnDefinitionsAlignConstraintsWithTabs() + { + // When columns have constraints, every column-definition field (name, data type, + // constraint) is aligned on a tab stop. The gaps between fields are rendered with tabs, + // and each field lines up on the next tab stop after the widest field in that column. + const string input = "CREATE TABLE t (a INT NOT NULL, b NVARCHAR(10) NULL, c INT DEFAULT 0);"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +CREATE TABLE t ( + a INT NOT NULL, + b NVARCHAR (10) NULL, + c INT DEFAULT 0 +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsColumnDefinitionsCascadeAlignFields() + { + // Robust cascade: with varying column-name and data-type widths, each field column is + // snapped to the next tab stop after the widest field to its left, and the snap of an + // earlier field is carried forward so later fields stay aligned across all rows. + const string input = "CREATE TABLE t (id INT NOT NULL, description NVARCHAR(200) NULL, x BIT DEFAULT 0);"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +CREATE TABLE t ( + id INT NOT NULL, + description NVARCHAR (200) NULL, + x BIT DEFAULT 0 +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsNestedBlocksUseMultipleTabs() + { + // Each nested indentation level adds one more tab character. + const string input = "CREATE PROCEDURE p AS BEGIN IF (1=1) BEGIN SELECT 1; END END"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +CREATE PROCEDURE p +AS +BEGIN + IF (1 = 1) + BEGIN + SELECT 1; + END +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsWithLeadingCommaFallsBackToSpaces() + { + // Interaction rule: leading-comma placement offsets the comma two columns before the + // alignment column using sub-indent-level spacing, which cannot be represented with tab + // characters. When both IndentationMode = Tabs and CommaPlacement = Leading are set, + // indentation falls back to spaces so the leading comma still aligns, and no tab + // character is ever emitted. + const string input = "BEGIN SELECT a, b FROM t WHERE a = 1 AND b = 2; END"; + + string tabsLeading = Generate(input, new SqlScriptGeneratorOptions + { + IndentationMode = IndentationMode.Tabs, + CommaPlacement = CommaPlacement.Leading + }); + + string spacesLeading = Generate(input, new SqlScriptGeneratorOptions + { + IndentationMode = IndentationMode.Spaces, + CommaPlacement = CommaPlacement.Leading + }); + + // Tabs mode is ignored under leading-comma placement: output is identical to spaces + // mode and contains no tab characters. + Assert.IsFalse(tabsLeading.Contains("\t"), "No tab characters should be emitted when CommaPlacement is Leading. Actual:\n" + tabsLeading); + Assert.AreEqual(spacesLeading, tabsLeading); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsViewColumnListUsesTabs() + { + // The CREATE VIEW column list is indented one tab per line, and the view's SELECT body + // uses tabs both for the clause-keyword gap and for the continuation lines of the + // select list. + const string input = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +CREATE VIEW v ( + a, + b, + c +) +AS +SELECT 1, + 2, + 3;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsClauseBodyUsesTab() + { + // The gap between a clause keyword and its body is rendered as a tab, so even a + // single-line SELECT places its body on a tab stop. + const string input = "SELECT 1;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsUpdateSetClauseAlignsWithTabs() + { + // The UPDATE SET items are indented with tabs and their "=" signs are aligned on a tab + // stop. The single-predicate WHERE clause has no alignment, so it keeps spaces. + const string input = "UPDATE t SET a = 1, b = 2, c = 3 WHERE d = 4;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +UPDATE t +SET a = 1, + b = 2, + c = 3 +WHERE d = 4;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsHonorsIndentationSize() + { + // The tab-stop math depends on IndentationSize: a clause body is placed on the first + // tab stop strictly past the widest keyword, so the number of tabs between a keyword + // and its body changes with the size, while each nested level is still exactly one tab. + // + // NOTE: unlike the other tests in this file, the two expected blocks below do NOT look + // aligned when the file is viewed with the usual 4-column tab width. Their tab runs are + // sized for IndentationSize 2 and 8, so they only line up when the editor's tab width is + // set to 2 (and 8) respectively - which is exactly the tab-width/IndentationSize coupling + // this test asserts. + const string input = "BEGIN SELECT a, b FROM t WHERE a = 1 AND b = 2; END"; + + // With a small tab width (2), the 5-6 character clause keywords need two tabs to clear + // the widest keyword, and the select-list / predicate continuations land five tabs in. + var optionsSize2 = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs, IndentationSize = 2 }; + const string expectedSize2 = +@" +BEGIN + SELECT a, + b + FROM t + WHERE a = 1 + AND b = 2; +END"; + + AssertGenerated(input, optionsSize2, expectedSize2); + + // With a wide tab width (8), a single tab already clears the widest keyword, so the + // clause gaps collapse to one tab and the continuations land two tabs in. + var optionsSize8 = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs, IndentationSize = 8 }; + const string expectedSize8 = +@" +BEGIN + SELECT a, + b + FROM t + WHERE a = 1 + AND b = 2; +END"; + + AssertGenerated(input, optionsSize8, expectedSize8); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsWithZeroIndentationSizeMatchesSpaces() + { + // IndentationSize = 0 means no tab can be emitted, so every tab path falls back to the + // space layout. Tabs mode must then produce exactly the same output as Spaces mode - + // including the column-definition layout for columns without constraints - and emit no + // tab characters at all. + foreach (string sql in new[] + { + "CREATE TABLE t (a INT NOT NULL, b INT, c INT DEFAULT 0);", + "BEGIN SELECT a, b FROM t WHERE a = 1 AND b = 2; END", + }) + { + string tabs = Generate(sql, new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs, IndentationSize = 0 }); + string spaces = Generate(sql, new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Spaces, IndentationSize = 0 }); + + Assert.AreEqual(spaces, tabs, "Tabs mode with IndentationSize 0 should match Spaces mode. SQL:\n" + sql); + Assert.IsFalse(tabs.Contains("\t"), "No tab characters should be emitted when IndentationSize is 0. SQL:\n" + sql); + } + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsRegenerationIsStable() + { + // Regenerating a script that was already produced in Tabs mode must reproduce it + // exactly (the generator normalizes whitespace, so tabs in the input do not perturb the + // output). This guards against round-trip instability. + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + + foreach (string sql in new[] + { + "BEGIN SELECT a, b FROM t WHERE a = 1 AND b = 2; END", + "CREATE TABLE t (a INT NOT NULL, b NVARCHAR(10) NULL, c INT DEFAULT 0);", + "UPDATE t SET a = 1, b = 2, c = 3 WHERE d = 4;", + }) + { + string first = Generate(sql, options); + string second = Generate(first, options); + Assert.AreEqual(first, second, "Tabs-mode output should be stable when regenerated. First:\n" + first); + } + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsSubqueryInWhereUsesTabs() + { + // A subquery nested in a WHERE predicate keeps aligning its own clause keywords with + // tabs; the inner clauses are indented past the outer predicate on tab stops. + const string input = "SELECT a FROM t WHERE a IN (SELECT b FROM u WHERE b > 1 AND c < 2);"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT a +FROM t +WHERE a IN (SELECT b + FROM u + WHERE b > 1 + AND c < 2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsDerivedTableUsesTabs() + { + // A derived table in FROM with its own GROUP BY: the inner query's clause keywords and + // select-list continuation are aligned with tabs, indented past the outer FROM. + const string input = "SELECT o.total FROM (SELECT SUM(x) AS total, y FROM t1 GROUP BY y) AS o WHERE o.total > 10;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT o.total +FROM (SELECT SUM(x) AS total, + y + FROM t1 + GROUP BY y) AS o +WHERE o.total > 10;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsWithoutClauseBodyAlignmentStillIndentsWithTabs() + { + // With AlignClauseBodies off, the clause keyword and its body are separated by a single + // space (no tab-stop snapping), but the structural indentation of each line is still + // written with tabs, and continuation lines still round up to a tab stop. + const string input = "BEGIN SELECT a, b FROM t WHERE a = 1 AND b = 2; END"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs, AlignClauseBodies = false }; + const string expected = +@" +BEGIN + SELECT a, + b + FROM t + WHERE a = 1 + AND b = 2; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsIndentsLeadingCommentWithTabs() + { + // The leading-whitespace-to-tabs pass also applies to a line that begins with a + // preserved comment: the comment is indented with a tab, not spaces. + const string input = "BEGIN /* c1 */ SELECT a FROM t; END"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs, PreserveComments = true }; + const string expected = +@" +BEGIN + /* c1 */ + SELECT a + FROM t; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsMultilineCommentDoesNotIndentFollowingContent() + { + // A multi-line block comment is a single token that CONTAINS newlines but ENDS with + // "*/", so the leading-whitespace-to-tabs pass must not treat content that follows it on + // the same line as a new line's indentation. Here the space in " + 2" after the comment + // must stay a space and not be converted into a tab. + const string input = "SELECT 1 /* a\r\nb */ + 2 FROM t;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs, PreserveComments = true }; + const string expected = +@" +SELECT 1 /* a +b */ + 2 +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsAlignsToWidestClauseKeyword() + { + // When a query mixes short and long clause keywords (SELECT/FROM vs GROUP BY/ORDER BY), + // every clause body is snapped to the same tab stop past the widest keyword, so the + // shorter keywords are followed by two tabs and the widest by one. + const string input = "SELECT a, b FROM t GROUP BY a, b HAVING COUNT(*) > 1 ORDER BY a;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT a, + b +FROM t +GROUP BY a, b +HAVING COUNT(*) > 1 +ORDER BY a;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStyleEqualsSignAlignsVaryingAliasAndColumnLengths() + { + // ColumnAliasStyle.EqualsSign in the default Spaces indentation mode: aliases and + // source expressions of differing lengths, with the '=' signs padded with spaces so + // they align to the widest alias. + const string input = "SELECT a AS shortName, bb AS x, ccc AS mediumAlias FROM t;"; + var options = new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.EqualsSign }; + const string expected = +@" +SELECT shortName = a, + x = bb, + mediumAlias = ccc +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsColumnAliasEqualsSignAlignsVaryingLengths() + { + // The same varying-length EqualsSign projection as the Spaces test above, but in Tabs + // mode: the leading indentation and the gaps that align the aliases and '=' signs are + // all rendered with tabs instead of padded spaces. + const string input = "SELECT a AS shortName, bb AS x, ccc AS mediumAlias FROM t;"; + var options = new SqlScriptGeneratorOptions + { + ColumnAliasStyle = ColumnAliasStyle.EqualsSign, + IndentationMode = IndentationMode.Tabs + }; + const string expected = +@" +SELECT shortName = a, + x = bb, + mediumAlias = ccc +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsMostRequestedJoinStyleUsesTabs() + { + // Most-requested JOIN style (NewLineAfterJoinKeyword = false, NewLineBeforeOnClause = + // true) in Tabs mode: the table source stays on the JOIN line and the ON keyword is + // placed one indentation level past the JOIN, written with tab characters. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x;"; + var options = new SqlScriptGeneratorOptions + { + IndentationMode = IndentationMode.Tabs, + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b + ON a.x = b.x;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsMultiPredicateOnWrapsWithTabs() + { + // Multi-predicate ON clause in Tabs mode: the ON keyword is one level past the JOIN and + // the wrapped AND predicate aligns under the first predicate, all using tab characters. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x AND a.y = b.y;"; + var options = new SqlScriptGeneratorOptions + { + IndentationMode = IndentationMode.Tabs, + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true, + MultilineWherePredicatesList = true + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b + ON a.x = b.x + AND a.y = b.y;"; + + AssertGenerated(input, options, expected); + } + + // --------------------------------------------------------------------------------------- + // Edge cases: empty / whitespace-only scripts and inputs padded with blank lines. The + // generator reparses the AST and re-emits normalized whitespace, so blank lines from the + // input never survive into the output, and Tabs mode never emits a tab for a line that has + // no structural indentation. + // --------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsEmptyScriptProducesEmptyOutput() + { + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + + AssertGenerated("", options, ""); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsWhitespaceOnlyScriptProducesEmptyOutput() + { + // A script that is nothing but spaces, tabs and blank lines produces no output at all - + // in particular, no stray tab characters. + const string input = " \r\n\t\r\n \t \r\n"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + + AssertGenerated(input, options, ""); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsCollapsesBlankLinesBetweenStatements() + { + // Many blank lines between two statements collapse to the single blank line implied by + // NumNewlinesAfterStatement. Both statements are single-line, so no tab is emitted for + // structural indentation (only the clause-keyword gap is a tab). + const string input = "SELECT 1;\r\n\r\n\r\n\r\n\r\nSELECT 2;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT 1; + +SELECT 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsBlankLinesWithinStatementAreNormalized() + { + // Blank lines sprinkled inside a single statement are discarded; the statement is + // reformatted with tab indentation as if the blank lines were never there. + const string input = "SELECT a,\r\n\r\n\r\nb\r\n\r\nFROM t\r\nWHERE x = 1;"; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT a, + b +FROM t +WHERE x = 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentationModeTabsExtraSpacesWithinStatementAreNormalized() + { + // Runs of extra spaces (leading, trailing and between tokens) are collapsed and the + // statement is re-emitted with tab indentation, producing the same output as the + // well-formatted equivalent. + const string input = " SELECT a, b FROM t WHERE x = 1; "; + var options = new SqlScriptGeneratorOptions { IndentationMode = IndentationMode.Tabs }; + const string expected = +@" +SELECT a, + b +FROM t +WHERE x = 1;"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs b/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs new file mode 100644 index 00000000..39ff4085 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs @@ -0,0 +1,259 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the NewLineAfterJoinKeyword and NewLineBeforeOnClause script-generation options that + // control how a QualifiedJoin (INNER/LEFT/RIGHT/FULL OUTER JOIN ... ON ...) is formatted. + [TestClass] + public class JoinClauseFormattingTests + { + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNewLineAfterJoinKeywordDefaultIsTrue() + { + Assert.AreEqual(true, new SqlScriptGeneratorOptions().NewLineAfterJoinKeyword); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNewLineBeforeOnClauseDefaultIsTrue() + { + Assert.AreEqual(true, new SqlScriptGeneratorOptions().NewLineBeforeOnClause); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultsReproduceOriginalJoinLayout() + { + // Defaults (NewLineAfterJoinKeyword = true, NewLineBeforeOnClause = true) must reproduce + // the original formatter output exactly: table source on its own line after the JOIN + // keyword, and ON on a new line aligned with the JOIN keyword (no extra indentation). + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x;"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +SELECT * +FROM a + INNER JOIN + b + ON a.x = b.x;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMostRequestedStyleTableSourceOnJoinLineOnNewLine() + { + // Most-requested style: table source kept on the JOIN line, ON on its own line indented + // one level from the JOIN keyword. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b + ON a.x = b.x;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBothFalseSingleLineJoin() + { + // Both options false: JOIN, table source and ON all stay on a single line. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = false + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b ON a.x = b.x;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTableSourceOnOwnLineOnKeptOnSameLine() + { + // Newline after JOIN keyword but ON kept on the same line as the table source. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = true, + NewLineBeforeOnClause = false + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN + b ON a.x = b.x;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultiPredicateOnWrapsWithMultilineWherePredicatesList() + { + // A multi-predicate ON wraps the AND predicate onto its own line, aligned under the + // first predicate, when MultilineWherePredicatesList is enabled (the same wrapping used + // for WHERE predicates). + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x AND a.y = b.y;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true, + MultilineWherePredicatesList = true + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b + ON a.x = b.x + AND a.y = b.y;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultiPredicateOnStaysInlineWhenMultilineDisabled() + { + // With MultilineWherePredicatesList disabled, a multi-predicate ON stays on a single line. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x AND a.y = b.y;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true, + MultilineWherePredicatesList = false + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b + ON a.x = b.x AND a.y = b.y;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestChainedJoinsEachOnIndentedOneLevel() + { + // Chained joins: each ON is indented one level from its JOIN, independently. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x INNER JOIN c ON b.y = c.y;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true + }; + const string expected = +@" +SELECT * +FROM a + INNER JOIN b + ON a.x = b.x + INNER JOIN c + ON b.y = c.y;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCrossJoinUnaffectedByNewOptions() + { + // CROSS JOIN has no ON clause (it is an UnqualifiedJoin), so the new options do not + // change its formatting. + const string input = "SELECT * FROM a CROSS JOIN b;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true + }; + const string expected = +@" +SELECT * +FROM a CROSS JOIN b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCrossApplyUnaffectedByNewOptions() + { + // CROSS APPLY has no ON clause either, so the new options leave it unchanged. + const string input = "SELECT * FROM a CROSS APPLY dbo.f(a.id) AS b;"; + var options = new SqlScriptGeneratorOptions + { + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true + }; + const string expected = +@" +SELECT * +FROM a CROSS APPLY dbo.f(a.id) AS b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestJoinInlineWithFirstTableSourceWhenNewLineBeforeJoinClauseFalse() + { + // When NewLineBeforeJoinClause is false, the JOIN keyword stays on the same line as the + // first table source; the new options still control the table source and ON placement. + const string input = "SELECT * FROM a INNER JOIN b ON a.x = b.x;"; + var options = new SqlScriptGeneratorOptions + { + NewLineBeforeJoinClause = false, + NewLineAfterJoinKeyword = false, + NewLineBeforeOnClause = true + }; + const string expected = +@" +SELECT * +FROM a INNER JOIN b + ON a.x = b.x;"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs new file mode 100644 index 00000000..a1c10ecc --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs @@ -0,0 +1,56 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System.Collections.Generic; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Shared helpers for script-generation option tests: generate a script from SQL with the given + // options and verify both the input and the generated output parse without errors. + internal static class ScriptGeneratorTestHelper + { + // Parses the input, generates a script with the given options (using the SQL-170 generator), + // asserts the input parses and the generated script reparses, and returns the generated script. + public static string Generate(string sql, SqlScriptGeneratorOptions options) + { + var parser = new TSql170Parser(true); + TSqlFragment fragment = parser.Parse(new StringReader(sql), out IList errors); + Assert.AreEqual(0, errors.Count, "Input must parse without errors."); + + var generator = new Sql170ScriptGenerator(options); + generator.GenerateScript(fragment, out string generated); + + AssertReparses(generated); + return generated; + } + + public static void AssertReparses(string sql) + { + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(sql), out IList errors); + Assert.AreEqual(0, errors.Count, "Generated script must reparse without errors. Actual:\n" + sql); + } + + // Normalizes line endings so verbatim expected constants compare equal regardless of the + // source file's line-ending style. + public static string Normalize(string value) + { + return value.Replace("\r\n", "\n").Replace("\r", "\n"); + } + + // Generates a script from the given SQL with the given options and asserts it equals the + // expected value. The expected literals typically start with a newline right after @" so the + // first SQL line lines up with the rest in source; Trim() removes that leading newline (and + // any trailing whitespace from the generated output) before comparing. + public static void AssertGenerated(string sql, SqlScriptGeneratorOptions options, string expected) + { + Assert.AreEqual(Normalize(expected).Trim(), Normalize(Generate(sql, options)).Trim()); + } + } +} diff --git a/Test/SqlDom/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs similarity index 61% rename from Test/SqlDom/ScriptGeneratorTests.cs rename to Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs index de29e542..fdaf7632 100644 --- a/Test/SqlDom/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs @@ -632,6 +632,124 @@ public void TestPreserveCommentsEnabled_SingleLineTrailing() $"Trailing comment should appear after SELECT. SELECT at {selectIndex}, comment at {commentIndex}"); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsDoesNotBreakColumnDefinitionAlignment() + { + // Regression: enabling PreserveComments must not defeat AlignColumnDefinitionFields. + // When there are no comments in the input, the generated script must be identical + // whether PreserveComments is on or off, and the column fields must stay aligned. + const string sql = + "CREATE TABLE dbo.t (id INT NOT NULL, long_column_name DECIMAL(10, 2) NULL, c VARCHAR(20) NOT NULL);"; + + const string expected = +@"CREATE TABLE dbo.t ( + id INT NOT NULL, + long_column_name DECIMAL (10, 2) NULL, + c VARCHAR (20) NOT NULL +);"; + + // Aligned output must be produced when PreserveComments is enabled (AssertGenerated also + // verifies the generated script reparses without errors)... + ScriptGeneratorTestHelper.AssertGenerated( + sql, + new SqlScriptGeneratorOptions { AlignColumnDefinitionFields = true, PreserveComments = true }, + expected); + + // ...and it must match the output produced with PreserveComments disabled (no comments present). + ScriptGeneratorTestHelper.AssertGenerated( + sql, + new SqlScriptGeneratorOptions { AlignColumnDefinitionFields = true, PreserveComments = false }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsKeepsColumnDefinitionAlignmentWithTrailingComments() + { + // Each column has a trailing '--' comment. With PreserveComments enabled the comments + // must be preserved and the column definition fields must remain aligned. + const string sql = +@"CREATE TABLE dbo.t ( + id INT NOT NULL, -- the identifier + long_column_name DECIMAL(10, 2) NULL, -- a decimal value + c VARCHAR(20) NOT NULL -- a string +);"; + + const string expected = +@"CREATE TABLE dbo.t ( + id INT NOT NULL, -- the identifier + long_column_name DECIMAL (10, 2) NULL, -- a decimal value + c VARCHAR (20) NOT NULL -- a string +);"; + + // AssertGenerated also verifies the generated script (comments included) reparses cleanly. + ScriptGeneratorTestHelper.AssertGenerated( + sql, + new SqlScriptGeneratorOptions { AlignColumnDefinitionFields = true, PreserveComments = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsColumnAlignmentIsIsolatedPerTable() + { + // Two CREATE TABLE column lists are rendered in the same enclosing scope. Each table's + // column fields must align only against that table's own columns; the wide column names + // in the first table must not widen the (independently aligned) second table. + const string sql = +@"CREATE TABLE dbo.wide (a_very_long_column_name INT NOT NULL, b INT NULL); +CREATE TABLE dbo.t (x INT NOT NULL, y INT NULL);"; + + const string expected = +@"CREATE TABLE dbo.wide ( + a_very_long_column_name INT NOT NULL, + b INT NULL +); + +CREATE TABLE dbo.t ( + x INT NOT NULL, + y INT NULL +);"; + + ScriptGeneratorTestHelper.AssertGenerated( + sql, + new SqlScriptGeneratorOptions { AlignColumnDefinitionFields = true, PreserveComments = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsMultilineViewColumnsWithEmptyAlignmentScope() + { + // CREATE VIEW generates its multiline column list without first pushing an enclosing + // alignment point, so the list-level named scope is pushed while the newline-restoration + // stack is empty. This exercises the null newline-point path (PushNamedAlignmentScope + // reusing "no current point", and the null guard in NewLine): it must not throw and must + // still emit each column on its own line with PreserveComments enabled. + const string sql = "CREATE VIEW dbo.v (col1, long_column_name, c) AS SELECT 1, 2, 3;"; + + const string expected = +@"CREATE VIEW dbo.v ( + col1, + long_column_name, + c +) +AS +SELECT 1, + 2, + 3;"; + + ScriptGeneratorTestHelper.AssertGenerated( + sql, + new SqlScriptGeneratorOptions { MultilineViewColumnsList = true, PreserveComments = true }, + expected); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] @@ -1219,18 +1337,56 @@ FROM users u Assert.AreEqual(0, reparseErrors.Count, "Generated SQL should reparse without errors. Actual: " + generatedSql); - // Comments preceding their JOIN in source should appear before the - // matching JOIN keyword in output where a natural newline separates - // the prior clause from the next JOIN. + // CRITICAL ASSERTIONS: Comments must appear BEFORE their JOIN keywords + // and NOT be on the same line as the previous table reference + + // Find the comment for INNER JOIN int innerJoinCommentIdx = generatedSql.IndexOf("-- Join to get user orders"); int innerJoinIdx = generatedSql.IndexOf("INNER JOIN", StringComparison.OrdinalIgnoreCase); - int leftJoinCommentIdx = generatedSql.IndexOf("/* Left join for optional address */"); - int leftJoinIdx = generatedSql.IndexOf("LEFT", StringComparison.OrdinalIgnoreCase); - + Assert.IsTrue(innerJoinCommentIdx >= 0, "INNER JOIN comment must exist"); Assert.IsTrue(innerJoinCommentIdx < innerJoinIdx, - $"INNER JOIN comment should appear before INNER JOIN. Comment at {innerJoinCommentIdx}, JOIN at {innerJoinIdx}"); + $"INNER JOIN comment MUST appear before INNER JOIN keyword. Comment at {innerJoinCommentIdx}, JOIN at {innerJoinIdx}. Generated SQL:\n{generatedSql}"); + + // Ensure comment is on its own line BEFORE INNER JOIN, not trailing after "users u" + string beforeInnerJoinComment = generatedSql.Substring(0, innerJoinCommentIdx); + int lastNewlineBeforeComment = Math.Max( + beforeInnerJoinComment.LastIndexOf("\n"), + beforeInnerJoinComment.LastIndexOf("\r") + ); + string lineBeforeComment = lastNewlineBeforeComment >= 0 + ? beforeInnerJoinComment.Substring(lastNewlineBeforeComment).Trim() + : beforeInnerJoinComment.Trim(); + + Assert.IsFalse(lineBeforeComment.Contains("users") && lineBeforeComment.Contains("--"), + $"Comment should NOT be trailing on the 'users u' line. Line before comment: '{lineBeforeComment}'. Generated SQL:\n{generatedSql}"); + + // Verify there's a newline between the comment and INNER JOIN + string betweenCommentAndJoin = generatedSql.Substring( + innerJoinCommentIdx + "-- Join to get user orders".Length, + innerJoinIdx - (innerJoinCommentIdx + "-- Join to get user orders".Length) + ); + Assert.IsTrue(betweenCommentAndJoin.Contains("\n") || betweenCommentAndJoin.Contains("\r"), + $"There must be a newline between comment and INNER JOIN. Text between: '{betweenCommentAndJoin}'. Generated SQL:\n{generatedSql}"); + + // Same checks for LEFT JOIN comment + int leftJoinCommentIdx = generatedSql.IndexOf("/* Left join for optional address */"); + int leftJoinIdx = generatedSql.IndexOf("LEFT JOIN", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(leftJoinCommentIdx >= 0, "LEFT JOIN comment must exist"); Assert.IsTrue(leftJoinCommentIdx < leftJoinIdx, - $"LEFT JOIN comment should appear before LEFT JOIN. Comment at {leftJoinCommentIdx}, JOIN at {leftJoinIdx}"); + $"LEFT JOIN comment MUST appear before LEFT JOIN keyword. Comment at {leftJoinCommentIdx}, JOIN at {leftJoinIdx}. Generated SQL:\n{generatedSql}"); + + // Verify comment is on its own line, not trailing after previous JOIN + string beforeLeftJoinComment = generatedSql.Substring(0, leftJoinCommentIdx); + int lastNewlineBeforeLeftComment = Math.Max( + beforeLeftJoinComment.LastIndexOf("\n"), + beforeLeftJoinComment.LastIndexOf("\r") + ); + string lineBeforeLeftComment = lastNewlineBeforeLeftComment >= 0 + ? beforeLeftJoinComment.Substring(lastNewlineBeforeLeftComment).Trim() + : beforeLeftJoinComment.Trim(); + + Assert.IsFalse(lineBeforeLeftComment.Contains("JOIN") && lineBeforeLeftComment.Contains("/*"), + $"Comment should NOT be trailing on the previous JOIN line. Line before comment: '{lineBeforeLeftComment}'. Generated SQL:\n{generatedSql}"); } [TestMethod] @@ -1409,16 +1565,42 @@ UNION ALL Assert.IsTrue(generatedSql.Contains("/* Combine with archived users */"), "UNION block comment should be preserved. Actual: " + generatedSql); - // Verify position: comments should appear at correct positions relative to queries + // CRITICAL ASSERTIONS: Comments must appear BEFORE UNION keyword + // and NOT be on the same line as the previous SELECT statement + int firstQueryCommentIdx = generatedSql.IndexOf("-- First query: active users"); int firstSelectIdx = generatedSql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase); int unionCommentIdx = generatedSql.IndexOf("/* Combine with archived users */"); int unionIdx = generatedSql.IndexOf("UNION", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(firstQueryCommentIdx >= 0, "First query comment must exist"); Assert.IsTrue(firstQueryCommentIdx < firstSelectIdx, - $"First query comment should appear before first SELECT. Comment at {firstQueryCommentIdx}, SELECT at {firstSelectIdx}"); + $"First query comment MUST appear before first SELECT. Comment at {firstQueryCommentIdx}, SELECT at {firstSelectIdx}. Generated SQL:\n{generatedSql}"); + + Assert.IsTrue(unionCommentIdx >= 0, "UNION comment must exist"); Assert.IsTrue(unionCommentIdx < unionIdx, - $"UNION comment should appear before UNION. Comment at {unionCommentIdx}, UNION at {unionIdx}"); + $"UNION comment MUST appear before UNION keyword. Comment at {unionCommentIdx}, UNION at {unionIdx}. Generated SQL:\n{generatedSql}"); + + // Ensure UNION comment is on its own line BEFORE UNION, not trailing after previous SELECT + string beforeUnionComment = generatedSql.Substring(0, unionCommentIdx); + int lastNewlineBeforeUnionComment = Math.Max( + beforeUnionComment.LastIndexOf("\n"), + beforeUnionComment.LastIndexOf("\r") + ); + string lineBeforeUnionComment = lastNewlineBeforeUnionComment >= 0 + ? beforeUnionComment.Substring(lastNewlineBeforeUnionComment).Trim() + : beforeUnionComment.Trim(); + + Assert.IsFalse(lineBeforeUnionComment.Contains("SELECT") && lineBeforeUnionComment.Contains("/*"), + $"UNION comment should NOT be trailing on the previous SELECT line. Line before comment: '{lineBeforeUnionComment}'. Generated SQL:\n{generatedSql}"); + + // Verify there's a newline between the comment and UNION keyword + string betweenCommentAndUnion = generatedSql.Substring( + unionCommentIdx + "/* Combine with archived users */".Length, + unionIdx - (unionCommentIdx + "/* Combine with archived users */".Length) + ); + Assert.IsTrue(betweenCommentAndUnion.Contains("\n") || betweenCommentAndUnion.Contains("\r"), + $"There must be a newline between comment and UNION. Text between: '{betweenCommentAndUnion}'. Generated SQL:\n{generatedSql}"); } [TestMethod] @@ -1732,6 +1914,87 @@ public void TestPreserveComments_LeadingCommentAfterGoBatch() Assert.AreEqual(0, reparseErrors.Count, "Generated SQL must reparse. Actual: " + generatedSql); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveCommentsEnabled_MultipleCommentsInTableDefinition() + { + var sqlWithComments = @"CREATE TABLE dbo.VETask +( +Id INT, +TaskNo INT, +Status INT, +--IsActive BIT NOT NULL CONSTRAINT DF_VETask_IsActive DEFAULT 1 +CONSTRAINT PK_VETask PRIMARY KEY CLUSTERED (Id), +--CONSTRAINT UQ_VETask_TaskNo UNIQUE (TaskNo) +INDEX IX_VETask_Status NONCLUSTERED (Status) +);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sqlWithComments), out var errors); + + Assert.AreEqual(0, errors.Count, "Input SQL should parse without errors"); + + var generatorOptions = new SqlScriptGeneratorOptions + { + PreserveComments = true + }; + var generator = new Sql170ScriptGenerator(generatorOptions); + generator.GenerateScript(fragment, out var generatedSql); + + // CRITICAL ASSERTIONS: Comments must NOT merge with previous lines + // and CONSTRAINT must NOT merge with "Status INT" line + + // 1. Comment should NOT be trailing on Status INT line + Assert.IsFalse(generatedSql.Contains("Status INT --IsActive"), + "Comment should NOT be trailing on Status INT line (no comma)"); + Assert.IsFalse(generatedSql.Contains("Status INT, --IsActive"), + "Comment should NOT be trailing on Status INT line (with comma)"); + Assert.IsFalse(generatedSql.Contains("Status INT, --IsActive"), + "Comment should NOT be trailing on Status INT line (with comma and space)"); + + // 2. CONSTRAINT must NOT be on the same line as Status INT + Assert.IsFalse(generatedSql.Contains("Status INT CONSTRAINT"), + $"CONSTRAINT keyword must NOT merge with Status INT line. Generated SQL:\n{generatedSql}"); + Assert.IsFalse(generatedSql.Contains("Status INT, CONSTRAINT"), + $"CONSTRAINT keyword must NOT be on same line as Status INT (with comma). Generated SQL:\n{generatedSql}"); + + // 3. Comment must appear BEFORE CONSTRAINT on its own line + int commentIdx = generatedSql.IndexOf("--IsActive BIT NOT NULL"); + int constraintIdx = generatedSql.IndexOf("CONSTRAINT PK_VETask", StringComparison.OrdinalIgnoreCase); + + Assert.IsTrue(commentIdx >= 0, "Comment for IsActive column must exist"); + Assert.IsTrue(constraintIdx >= 0, "CONSTRAINT PK_VETask must exist"); + Assert.IsTrue(commentIdx < constraintIdx, + $"Comment must appear BEFORE CONSTRAINT. Comment at {commentIdx}, CONSTRAINT at {constraintIdx}. Generated SQL:\n{generatedSql}"); + + // 4. Verify Status INT is on a separate line from the comment + int statusIdx = generatedSql.IndexOf("Status INT", StringComparison.OrdinalIgnoreCase); + Assert.IsTrue(statusIdx >= 0, "Status INT column must exist"); + + // Extract the line containing "Status INT" + int lineStartIdx = statusIdx; + while (lineStartIdx > 0 && generatedSql[lineStartIdx - 1] != '\n' && generatedSql[lineStartIdx - 1] != '\r') + { + lineStartIdx--; + } + int lineEndIdx = statusIdx; + while (lineEndIdx < generatedSql.Length && generatedSql[lineEndIdx] != '\n' && generatedSql[lineEndIdx] != '\r') + { + lineEndIdx++; + } + string statusLine = generatedSql.Substring(lineStartIdx, lineEndIdx - lineStartIdx).Trim(); + + Assert.IsFalse(statusLine.Contains("--"), + $"Status INT line must NOT contain the comment. Actual line: '{statusLine}'. Generated SQL:\n{generatedSql}"); + Assert.IsFalse(statusLine.Contains("CONSTRAINT"), + $"Status INT line must NOT contain CONSTRAINT keyword. Actual line: '{statusLine}'. Generated SQL:\n{generatedSql}"); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generatedSql), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, $"Generated SQL must reparse without errors. Generated SQL:\n{generatedSql}"); + } + + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] @@ -1983,5 +2246,953 @@ public void TestPreserveComments_RealWorldXmlModifyBatchFromDocs() } #endregion + + #region CommaPlacement + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementDefaultIsTrailing() + { + Assert.AreEqual(CommaPlacement.Trailing, new SqlScriptGeneratorOptions().CommaPlacement); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSelectList() + { + var sql = "SELECT a, b, c FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading + }); + generator.GenerateScript(fragment, out var generated); + + // Leading comma style for a keyword-aligned list: the columns stay aligned with the + // first element and each comma is placed two columns before them. + string expected = + "SELECT a" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingSelectList() + { + var sql = "SELECT a, b, c FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing + }); + generator.GenerateScript(fragment, out var generated); + + // Trailing comma style (default): the comma is placed at the end of each line. + string expected = + "SELECT a," + Environment.NewLine + + " b," + Environment.NewLine + + " c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingParenthesizedList() + { + var sql = "CREATE TABLE t (a INT, b INT, c INT);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading + }); + generator.GenerateScript(fragment, out var generated); + + // Leading comma style in a parenthesized (CREATE TABLE) column list. + // Elements stay at the list indentation level (4); the comma is indented two + // characters fewer (column 2), per the CommaPlacement=Leading rule. + string expected = + "CREATE TABLE t (" + Environment.NewLine + + " a INT" + Environment.NewLine + + " , b INT" + Environment.NewLine + + " , c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingParenthesizedList() + { + var sql = "CREATE TABLE t (a INT, b INT, c INT);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing + }); + generator.GenerateScript(fragment, out var generated); + + // Trailing comma style (default) in a parenthesized (CREATE TABLE) column list: + // each comma follows the element on the same line and the elements stay at the + // list indentation level (4). + string expected = + "CREATE TABLE t (" + Environment.NewLine + + " a INT," + Environment.NewLine + + " b INT," + Environment.NewLine + + " c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertTargets() + { + // The INSERT column target list is always emitted as a single-line parenthesized + // list (via GenerateParenthesisedCommaSeparatedList), and CommaPlacement only affects + // multi-line lists. MultilineInsertTargetsList is not consumed by the INSERT visitor, + // so the targets stay on one line and CommaPlacement = Leading has no visual effect: + // the output is identical to the trailing case below. + var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertTargetsList = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "INSERT INTO t (a, b, c)" + Environment.NewLine + + "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingInsertTargets() + { + // Same output as the leading case: because the INSERT target list renders on a + // single line (CommaPlacement only affects multi-line lists, and + // MultilineInsertTargetsList is not consumed here), leading and trailing placement + // produce identical text. + var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineInsertTargetsList = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "INSERT INTO t (a, b, c)" + Environment.NewLine + + "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertSources() + { + // The INSERT source (VALUES) row list is a multi-line comma-separated list, so + // CommaPlacement = Leading places each continuation row's comma at the start of its + // line. (The rows are not aligned under the first row: this list is emitted via the + // newline comma-list path, so continuation rows begin at column 0.) + var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertSourcesList = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "INSERT INTO t (a, b, c)" + Environment.NewLine + + "VALUES (1, 2, 3)" + Environment.NewLine + + ", (4, 5, 6)" + Environment.NewLine + + ", (7, 8, 9);" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingInsertSources() + { + // The INSERT source (VALUES) row list with CommaPlacement = Trailing (default): + // each row's comma follows it at the end of the line. + var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineInsertSourcesList = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "INSERT INTO t (a, b, c)" + Environment.NewLine + + "VALUES (1, 2, 3)," + Environment.NewLine + + "(4, 5, 6)," + Environment.NewLine + + "(7, 8, 9);" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingViewColumns() + { + // The CREATE VIEW column list is a parenthesized, indented list (like CREATE TABLE): + // with CommaPlacement = Leading the columns stay at the list indentation level (4) + // and each comma is indented two characters fewer (column 2). The SELECT list in the + // view body is keyword-aligned, so its leading commas sit two columns before the + // aligned expression column. + var sql = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineViewColumnsList = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "CREATE VIEW v (" + Environment.NewLine + + " a" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + ")" + Environment.NewLine + + "AS" + Environment.NewLine + + "SELECT 1" + Environment.NewLine + + " , 2" + Environment.NewLine + + " , 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingViewColumns() + { + // Trailing comma style (default): the CREATE VIEW column list keeps each comma on the + // element's line at the list indentation level (4), and the SELECT list in the view + // body places each comma at the end of its line. + var sql = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineViewColumnsList = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "CREATE VIEW v (" + Environment.NewLine + + " a," + Environment.NewLine + + " b," + Environment.NewLine + + " c" + Environment.NewLine + + ")" + Environment.NewLine + + "AS" + Environment.NewLine + + "SELECT 1," + Environment.NewLine + + " 2," + Environment.NewLine + + " 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSetClauseItems() + { + // The UPDATE SET item list is keyword-aligned: with CommaPlacement = Leading the items + // stay aligned with the first item and each comma is placed two columns before them + // (the '=' signs remain aligned via a separate alignment point), matching the SELECT + // list behavior. + var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSetClauseItems = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "UPDATE t" + Environment.NewLine + + "SET a = 1" + Environment.NewLine + + " , b = 2" + Environment.NewLine + + " , c = 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingSetClauseItems() + { + // Trailing comma style (default): the UPDATE SET items stay aligned with the first + // item and each comma follows the item at the end of its line. + var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineSetClauseItems = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "UPDATE t" + Environment.NewLine + + "SET a = 1," + Environment.NewLine + + " b = 2," + Environment.NewLine + + " c = 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSingleColumnHasNoComma() + { + // A list with a single element must never emit a comma regardless of placement. + var sql = "SELECT a FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading + }); + generator.GenerateScript(fragment, out var generated); + + // A list with a single element must never emit a comma regardless of placement. + string expected = + "SELECT a" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingWithPreserveCommentsDoesNotAbsorbComma() + { + // Interaction rule (FeedbackTicket 3016816 "SQL Formatter reformats leading + // commas to invalid SQL"): with + // CommaPlacement = Leading and PreserveComments = true, a line comment trailing + // an element must not cause the following comma to land on the comment line + // (which would comment out the comma). The comma belongs on the next element's line. + var sql = + "SELECT col1, -- first column" + Environment.NewLine + + " col2, -- second column" + Environment.NewLine + + " col3" + Environment.NewLine + + "FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + PreserveComments = true + }); + generator.GenerateScript(fragment, out var generated); + + // The full generated script: each line comment stays on its element's line, and the + // leading comma is placed at the start of the next element's line (before a column, + // never before a comment), so the comment is never commented out and the script + // reparses cleanly. + string expected = + "SELECT col1 -- first column" + Environment.NewLine + + " , col2 -- second column" + Environment.NewLine + + " , col3" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + // The generated script must reparse cleanly. + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingWithPreserveCommentsKeepsCommentsAfterComma() + { + // Counterpart to TestCommaPlacementLeadingWithPreserveCommentsDoesNotAbsorbComma + // (FeedbackTicket 3016816 "SQL Formatter reformats leading commas to invalid SQL"). With + // CommaPlacement = Trailing (default) and PreserveComments = true, each trailing comma + // stays on the element's line and its line comment follows the comma, so the generated + // script still reparses cleanly. + var sql = + "SELECT col1, -- first column" + Environment.NewLine + + " col2, -- second column" + Environment.NewLine + + " col3" + Environment.NewLine + + "FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + PreserveComments = true + }); + generator.GenerateScript(fragment, out var generated); + + // The full generated script: the trailing comma stays on the element's line and its + // line comment follows the comma on that same line, so the script reparses cleanly. + string expected = + "SELECT col1, -- first column" + Environment.NewLine + + " col2, -- second column" + Environment.NewLine + + " col3" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + // The generated script must reparse cleanly. + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + // ---- Interaction rule: CommaPlacement = Leading has no visual effect when the + // ---- corresponding Multiline* option is false (the list stays on a single line). + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSelectListMultilineFalse() + { + // With MultilineSelectElementsList = false the SELECT list is emitted on a single + // line, so CommaPlacement = Leading has no visual effect (commas remain inline). + var sql = "SELECT a, b, c FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSelectElementsList = false + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "SELECT a, b, c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingViewColumnsMultilineFalse() + { + // With MultilineViewColumnsList = false the VIEW column list is emitted as a single + // parenthesized line, so CommaPlacement = Leading has no visual effect there. (The + // SELECT body still honors leading placement via MultilineSelectElementsList, which + // defaults to true.) + var sql = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineViewColumnsList = false, + MultilineSelectElementsList = false + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "CREATE VIEW v (a, b, c)" + Environment.NewLine + + "AS" + Environment.NewLine + + "SELECT 1, 2, 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSetClauseItemsMultilineFalse() + { + // With MultilineSetClauseItems = false the UPDATE SET item list is emitted on a + // single line, so CommaPlacement = Leading has no visual effect (commas remain + // inline). + var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSetClauseItems = false + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "UPDATE t" + Environment.NewLine + + "SET a = 1, b = 2, c = 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertTargetsMultilineFalse() + { + // The INSERT target list is always emitted on a single line, so CommaPlacement = + // Leading has no visual effect regardless of MultilineInsertTargetsList. + var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertTargetsList = false + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "INSERT INTO t (a, b, c)" + Environment.NewLine + + "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertSourcesMultilineFalse() + { + // The INSERT source (VALUES) row list is always emitted multi-line (the generator + // does not gate it on MultilineInsertSourcesList), so setting that option to false + // does NOT collapse it to one line: CommaPlacement = Leading still applies to the + // row separators. + var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertSourcesList = false + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "INSERT INTO t (a, b, c)" + Environment.NewLine + + "VALUES (1, 2, 3)" + Environment.NewLine + + ", (4, 5, 6)" + Environment.NewLine + + ", (7, 8, 9);" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingParenthesizedListAlwaysMultiline() + { + // The CREATE TABLE column list has no single-line toggle: it is always emitted + // multi-line. There is therefore no "Multiline = false" state for it, so + // CommaPlacement = Leading always applies (comma at indent - 2). + var sql = "CREATE TABLE t (a INT, b INT, c INT);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "CREATE TABLE t (" + Environment.NewLine + + " a INT" + Environment.NewLine + + " , b INT" + Environment.NewLine + + " , c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingIndentedOptionList() + { + // The WITH-parameter list of CREATE COLUMN MASTER KEY is generated through the indented + // multi-line comma-list path (GenerateCommaSeparatedList with insertNewLine and indent + // both true). With CommaPlacement = Leading the leading comma is emitted at the start + // of the next parameter's (indented) line. + var sql = "CREATE COLUMN MASTER KEY CMK1 WITH (KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE', KEY_PATH = 'some/path');"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading + }); + generator.GenerateScript(fragment, out var generated); + + // The continuation parameter's comma is emitted at the start of its (indented) line + // via the 4-arg GenerateCommaSeparatedList leading branch. The comma width is reserved + // inside the indentation, so the parameter stays aligned with the first parameter and + // the leading comma sits in the reserved columns before it. + string expected = + "CREATE COLUMN MASTER KEY CMK1" + Environment.NewLine + + "WITH (" + Environment.NewLine + + " KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE'" + Environment.NewLine + + " , KEY_PATH = 'some/path'" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSetClauseItemsIndented() + { + // With IndentSetClause = true the SET keyword is indented; CommaPlacement = Leading + // still aligns the items and places each comma two columns before them. + var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSetClauseItems = true, + IndentSetClause = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "UPDATE t" + Environment.NewLine + + " SET a = 1" + Environment.NewLine + + " , b = 2" + Environment.NewLine + + " , c = 3;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingCreateTableWithComments() + { + // PreserveComments + CommaPlacement.Leading in an indented (CREATE TABLE) column list: + // each trailing line comment stays on its column's line and the leading comma is + // emitted at the start of the next column's line (comma at indent - 2). Verifies the + // comment/comma-skip fix in the indent-based leading path, not just the SELECT list. + var sql = + "CREATE TABLE t (a INT, -- first" + Environment.NewLine + + "b INT, -- second" + Environment.NewLine + + "c INT);"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + PreserveComments = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "CREATE TABLE t (" + Environment.NewLine + + " a INT -- first" + Environment.NewLine + + " , b INT -- second" + Environment.NewLine + + " , c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingWithBlockCommentTrailingElement() + { + // PreserveComments + CommaPlacement.Leading with a block comment trailing an element. + // Block comments are emitted inline (a different path than the deferred '--' comments), + // so this confirms leading placement is not broken by an inline block comment. + var sql = "SELECT a /* note */, b, c FROM t;"; + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + PreserveComments = true + }); + generator.GenerateScript(fragment, out var generated); + + string expected = + "SELECT a /* note */" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + Assert.AreEqual(expected, generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSpaceCountZero() + { + // LeadingCommaSpaceCount = 0: the comma occupies a single column (no trailing space). + // Items stay aligned with the first element; only the comma column shifts. + const string selectSql = "SELECT a, b, c FROM t;"; + const string tableSql = "CREATE TABLE t (a INT, b INT, c INT);"; + + // Keyword-aligned list (SELECT): comma ends immediately before the aligned column. + string expectedSelect = + "SELECT a" + Environment.NewLine + + " ,b" + Environment.NewLine + + " ,c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + // Indented list (CREATE TABLE): elements stay at indentation column 4; the comma is + // indented one column fewer (column 3) so the comma+item still occupy 4 columns. + string expectedTable = + "CREATE TABLE t (" + Environment.NewLine + + " a INT" + Environment.NewLine + + " ,b INT" + Environment.NewLine + + " ,c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + + AssertLeadingCommaSpaceCount(0, selectSql, expectedSelect); + AssertLeadingCommaSpaceCount(0, tableSql, expectedTable); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSpaceCountOne() + { + // LeadingCommaSpaceCount = 1 (the default): comma + one space, occupying 2 columns. + const string selectSql = "SELECT a, b, c FROM t;"; + const string tableSql = "CREATE TABLE t (a INT, b INT, c INT);"; + + string expectedSelect = + "SELECT a" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + string expectedTable = + "CREATE TABLE t (" + Environment.NewLine + + " a INT" + Environment.NewLine + + " , b INT" + Environment.NewLine + + " , c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + + AssertLeadingCommaSpaceCount(1, selectSql, expectedSelect); + AssertLeadingCommaSpaceCount(1, tableSql, expectedTable); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSpaceCountTwo() + { + // LeadingCommaSpaceCount = 2: comma + two spaces, occupying 3 columns. + const string selectSql = "SELECT a, b, c FROM t;"; + const string tableSql = "CREATE TABLE t (a INT, b INT, c INT);"; + + string expectedSelect = + "SELECT a" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + // Elements stay at indentation column 4; the comma is indented three columns fewer + // (column 1) so the comma plus its two trailing spaces still occupy 4 columns. + string expectedTable = + "CREATE TABLE t (" + Environment.NewLine + + " a INT" + Environment.NewLine + + " , b INT" + Environment.NewLine + + " , c INT" + Environment.NewLine + + ");" + Environment.NewLine + Environment.NewLine; + + AssertLeadingCommaSpaceCount(2, selectSql, expectedSelect); + AssertLeadingCommaSpaceCount(2, tableSql, expectedTable); + } + + // Generates the given SQL with CommaPlacement.Leading and the specified leading-comma space + // count, asserts the generated script matches the expectation, and that it reparses cleanly. + private static void AssertLeadingCommaSpaceCount(int spaceCount, string sql, string expected) + { + var parser = new TSql170Parser(true); + var fragment = parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count); + + var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + LeadingCommaSpaceCount = spaceCount + }); + generator.GenerateScript(fragment, out var generated); + + Assert.AreEqual(expected, generated, + "LeadingCommaSpaceCount=" + spaceCount + " produced unexpected output. Actual:\n" + generated); + + var reparser = new TSql170Parser(true); + reparser.Parse(new StringReader(generated), out var reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); + } + + #endregion } } diff --git a/Test/SqlDom/UTSqlScriptDom.csproj b/Test/SqlDom/UTSqlScriptDom.csproj index c4ade393..44ebc9ca 100644 --- a/Test/SqlDom/UTSqlScriptDom.csproj +++ b/Test/SqlDom/UTSqlScriptDom.csproj @@ -12,6 +12,7 @@ + diff --git a/release-notes/180/180.59.2.md b/release-notes/180/180.59.2.md new file mode 100644 index 00000000..7aac6281 --- /dev/null +++ b/release-notes/180/180.59.2.md @@ -0,0 +1,34 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.59.2 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* None + +#### .NET Framework +#### .NET Core + +### New Features +* Adds formatter options for identifier casing and identifier bracketing. + +### Fixed +* Fixes SQL formatter indentation after comments. +* Adds CommaPlacement option for script generation formatting. +* Adds ColumnAliasStyle option for script generation. +* Adds IndentationMode option (spaces or tabs) for script generation. +* Adds JOIN formatting options: NewLineAfterJoinKeyword and NewLineBeforeOnClause. +* Fixes PreserveComments preventing AlignColumnDefinitionFields behavior in script generation. +* Adds IdentifierCasing and IdentifierBracketing formatter options. + +### Changes +* None + +### Known Issues +* None \ No newline at end of file From 01aa17bfa32f25f1b1084b72c2e6a1a92b44633a Mon Sep 17 00:00:00 2001 From: allancascante Date: Mon, 3 Aug 2026 13:37:45 -0600 Subject: [PATCH 37/45] Sync repos: Release 180.78.1 (#220) Co-authored-by: Allan Cascante --- .../SqlServer/ClauseBodyAlignment.cs | 29 + .../SqlServer/ScriptGenerator/ScriptWriter.cs | 38 + ...SqlScriptGeneratorVisitor.CommonPhrases.cs | 113 ++- ...eratorVisitor.ExternalFunctionStatement.cs | 14 +- .../SqlScriptGeneratorVisitor.FromClause.cs | 7 +- ...tGeneratorVisitor.FunctionStatementBody.cs | 8 +- ...SqlScriptGeneratorVisitor.GroupByClause.cs | 7 +- .../SqlScriptGeneratorVisitor.HavingClause.cs | 11 +- .../SqlScriptGeneratorVisitor.InPredicate.cs | 13 +- ...lScriptGeneratorVisitor.InsertStatement.cs | 12 +- ...ptGeneratorVisitor.ListGenerationOption.cs | 19 +- ...qlScriptGeneratorVisitor.MergeStatement.cs | 12 +- ...SqlScriptGeneratorVisitor.OrderByClause.cs | 7 +- ...GeneratorVisitor.ProcedureStatementBody.cs | 6 +- ...riptGeneratorVisitor.QuerySpecification.cs | 43 +- ...SqlScriptGeneratorVisitor.StatementList.cs | 3 + .../SqlScriptGeneratorVisitor.TSqlBatch.cs | 8 +- .../SqlScriptGeneratorVisitor.WhereClause.cs | 20 +- .../Settings/SqlScriptGeneratorOptions.xml | 17 +- .../ClauseBodyAlignmentTests.cs | 887 ++++++++++++++++++ .../InValuesListFormattingTests.cs | 346 +++++++ .../InsertTargetsListFormattingTests.cs | 486 ++++++++++ .../ProcedureParametersFormattingTests.cs | 437 +++++++++ .../ScriptGenerator/ScriptGeneratorTests.cs | 48 +- .../SeparatingSemiColonTests.cs | 490 ++++++++++ release-notes/180/180.78.1.md | 31 + 26 files changed, 3047 insertions(+), 65 deletions(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ClauseBodyAlignment.cs create mode 100644 Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/ProcedureParametersFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/SeparatingSemiColonTests.cs create mode 100644 release-notes/180/180.78.1.md diff --git a/SqlScriptDom/ScriptDom/SqlServer/ClauseBodyAlignment.cs b/SqlScriptDom/ScriptDom/SqlServer/ClauseBodyAlignment.cs new file mode 100644 index 00000000..05fcf691 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ClauseBodyAlignment.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents how the body of a clause (the part after FROM, WHERE, GROUP BY, etc.) is laid out + /// relative to its keyword. + /// + public enum ClauseBodyAlignment + { + /// + /// Keep the body on the keyword's line and line all clause bodies up under a shared column + /// past the widest keyword (the classic "rivers of whitespace" style). + /// + Aligned, + + /// + /// Put the body on its own new line, indented one level ( / + /// IndentationSize) past the keyword, so nesting grows one step per level instead of drifting + /// right as keywords get wider. When this value is used, the AlignClauseBodies setting is + /// ignored. + /// + Indented + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs index 07e46282..347feaa2 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptWriter.cs @@ -93,6 +93,44 @@ public void NewLine() } } + // Returns true if the most recently added meaningful token is a semicolon, ignoring any + // trailing whitespace, newlines and alignment points. Used to avoid emitting a redundant + // separating semicolon when the previous statement already ended with one. + public Boolean LastMeaningfulTokenIsSemicolon() + { + for (Int32 index = _scriptWriterElements.Count - 1; index >= 0; --index) + { + ScriptWriterElement element = _scriptWriterElements[index]; + + if (element.ElementType == ScriptWriterElementType.NewLine || + element.ElementType == ScriptWriterElementType.AlignmentPoint) + { + continue; + } + + TokenWrapper tokenWrapper = element as TokenWrapper; + if (tokenWrapper != null) + { + TSqlTokenType tokenType = tokenWrapper.Token.TokenType; + + // Skip trailing comments so a semicolon emitted before them is still detected; + // otherwise the caller would append the separator into the comment text. + if (tokenType == TSqlTokenType.WhiteSpace || + tokenType == TSqlTokenType.SingleLineComment || + tokenType == TSqlTokenType.MultilineComment) + { + continue; + } + + return tokenType == TSqlTokenType.Semicolon; + } + + return false; + } + + return false; + } + public void Indent(Int32 size) { AddSpace(size); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs index ef8e600e..5004cc2c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs @@ -315,11 +315,18 @@ protected void GenerateNewLineOrSpace(Boolean newline) } } - // mark an alignment point for clause body if it's configured so at a new line + // Mark the shared cross-clause "river" alignment point for a clause body, when the current + // options call for it. + // + // ClauseBodyAlignment.Indented never uses the river: a clause body either moves onto its own + // indented line (see GenerateClauseBodyStart) or stays on the keyword line separated by a + // single space. Marking in that mode would re-introduce the river padding the Indented layout + // deliberately drops, so the mode is part of the guard below instead of being repeated by + // every caller. Every other case - including the default (Aligned) - is unchanged. protected void MarkClauseBodyAlignmentWhenNecessary(Boolean newline, AlignmentPoint ap) { - // If we didn't put a newline in, don't align, even if AlignClauseBodies is on - if (newline && _options.AlignClauseBodies) + // If we didn't put a newline in, don't align, even if AlignClauseBodies is on. + if (newline && _options.AlignClauseBodies && _options.ClauseBodyAlignment != ClauseBodyAlignment.Indented) { #if !PIMODLANGUAGE Debug.Assert(ap != null, "Alignment point should not be null"); @@ -331,6 +338,29 @@ protected void MarkClauseBodyAlignmentWhenNecessary(Boolean newline, AlignmentPo } } + // Handle the transition from a clause keyword to its body when the body would start on a new + // line (newline == true). + // + // Default (Aligned) mode: this is a pass-through - it marks the shared clause-body alignment + // point exactly as before (via MarkClauseBodyAlignmentWhenNecessary) and returns false, so the + // caller emits the usual separating space. The combination is identical to the original + // "MarkClauseBodyAlignmentWhenNecessary(...); GenerateSpace();" pair, so the default output + // does not change. + // + // Indented mode: the body is broken onto its own line, indented one level, and this returns + // true so the caller skips the separating space. + protected Boolean GenerateClauseBodyStart(Boolean newline, AlignmentPoint ap) + { + if (newline && _options.ClauseBodyAlignment == ClauseBodyAlignment.Indented) + { + NewLineAndIndent(); + return true; + } + + MarkClauseBodyAlignmentWhenNecessary(newline, ap); + return false; + } + protected void MarkInsertColumnsAlignmentPointWhenNecessary(AlignmentPoint ap) { #if !PIMODLANGUAGE @@ -400,6 +430,53 @@ protected void GenerateQueryExpressionInParentheses(QueryExpression queryExpress GenerateSymbol(TSqlTokenType.RightParenthesis); } + // Emits the parameter list for a CREATE/ALTER PROCEDURE or FUNCTION statement. + // + // The default (MultilineProcedureParametersList == false) is intentionally the existing, + // unchanged behavior: all parameters are written on a single line - function parameters in + // parentheses, procedure parameters without. Multi-line output (one parameter per line, + // indented one level from the procedure/function name) is strictly opt-in via the option. + // CommaPlacement is honored by the underlying list generation when multi-line is enabled. + protected void GenerateProcedureOrFunctionParameters(IList parameters, bool parenthesized) + { + bool hasParameters = parameters != null && parameters.Count > 0; + + // Default path: unchanged single-line behavior. Taken whenever the option is off (its + // default) or there is nothing to spread across multiple lines. + if (!_options.MultilineProcedureParametersList || !hasParameters) + { + if (parenthesized) + { + NewLine(); + GenerateParenthesisedCommaSeparatedList(parameters); + if (!hasParameters) + { + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateSpaceAndSymbol(TSqlTokenType.RightParenthesis); + } + } + else if (hasParameters) + { + NewLine(); + GenerateCommaSeparatedList(parameters); + } + + return; + } + + // Opt-in path: one parameter per line, indented one level. + if (parenthesized) + { + ListGenerationOption option = ListGenerationOption.CreateOptionFromFormattingConfig(_options); + GenerateFragmentList(parameters, option); + } + else + { + // The option produces its own leading new line before the first parameter. + GenerateFragmentList(parameters, ListGenerationOption.MultipleLineProcedureParameterOption); + } + } + // True while rendering a SELECT projection list (QuerySpecification.SelectElements). // Restricts the "alias = expression" ColumnAliasStyle form to real SELECT projections, // because OUTPUT, OUTPUT INTO and RECEIVE reuse SelectScalarExpression but do not @@ -508,6 +585,36 @@ protected void GenerateSemiColonWhenNecessary(TSqlStatement node) } } + // Some statements must be preceded by a semicolon terminator to be valid in SQL Server: + // statements that begin with a WITH clause (common table expression / XMLNAMESPACES) and + // the THROW statement. When such a statement follows a statement that was not already + // terminated with a semicolon (for example an IF / BEGIN...END / WHILE / TRY...CATCH block, + // whose generated form ends with END and no terminator), the required separating semicolon + // is emitted so the generated script is valid for SQL Server, which enforces the terminator + // even though ScriptDom's own parser is lenient. + protected void GenerateSeparatingSemiColonWhenNecessary(TSqlStatement previous, TSqlStatement next) + { + if (previous != null && + next != null && + _generateSemiColon && + StatementRequiresPrecedingSemiColon(next) && + _writer.LastMeaningfulTokenIsSemicolon() == false) + { + GenerateSymbol(TSqlTokenType.Semicolon); + } + } + + private static Boolean StatementRequiresPrecedingSemiColon(TSqlStatement statement) + { + if (statement is ThrowStatement) + { + return true; + } + + StatementWithCtesAndXmlNamespaces statementWithCtes = statement as StatementWithCtesAndXmlNamespaces; + return statementWithCtes != null && statementWithCtes.WithCtesAndXmlNamespaces != null; + } + /// /// Generates a statement fragment with semicolon placed before any trailing comments. /// This prevents semicolons from being appended after single-line comments (-- style), diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs index 8ab01c63..d51f8869 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ExternalFunctionStatement.cs @@ -35,8 +35,18 @@ private void GenerateExternalFunctionStatementBody(ExternalFunctionStatement nod GenerateSpaceAndFragmentIfNotNull(node.Name); if (node.Parameters != null && node.Parameters.Count > 0) { - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(node.Parameters); + if (_options.MultilineProcedureParametersList) + { + // Opt-in: one parameter per line, indented one level. + ListGenerationOption option = ListGenerationOption.CreateOptionFromFormattingConfig(_options); + GenerateFragmentList(node.Parameters, option); + } + else + { + // Default: unchanged single-line, parenthesized parameter list. + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.Parameters); + } } if (node.ReturnType != null) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs index 41d4daef..c7c2fc6c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs @@ -29,9 +29,10 @@ protected void GenerateFromClause(FromClause fromClause, AlignmentPoint clauseBo GenerateKeyword(TSqlTokenType.From); - MarkClauseBodyAlignmentWhenNecessary(_options.NewLineBeforeFromClause, clauseBody); - - GenerateSpace(); + if (!GenerateClauseBodyStart(_options.NewLineBeforeFromClause, clauseBody)) + { + GenerateSpace(); + } AlignmentPoint fromItems = new AlignmentPoint(); MarkAndPushAlignmentPoint(fromItems); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionStatementBody.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionStatementBody.cs index b3c03f29..83083266 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionStatementBody.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionStatementBody.cs @@ -52,13 +52,7 @@ protected void GenerateFunctionStatementBody(FunctionStatementBody node) GenerateSpaceAndFragmentIfNotNull(node.Name); // parameters - NewLine(); - GenerateParenthesisedCommaSeparatedList(node.Parameters); - if (node.Parameters == null || node.Parameters.Count == 0) - { - GenerateSymbol(TSqlTokenType.LeftParenthesis); - GenerateSpaceAndSymbol(TSqlTokenType.RightParenthesis); - } + GenerateProcedureOrFunctionParameters(node.Parameters, parenthesized: true); // RETURNS NewLine(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs index 389ebbcb..d3d73987 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs @@ -22,9 +22,10 @@ public override void ExplicitVisit(GroupByClause node) } AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); - MarkClauseBodyAlignmentWhenNecessary(_options.NewLineBeforeGroupByClause, clauseBody); - - GenerateSpace(); + if (!GenerateClauseBodyStart(_options.NewLineBeforeGroupByClause, clauseBody)) + { + GenerateSpace(); + } GenerateCommaSeparatedList(node.GroupingSpecifications); if (node.GroupByOption != GroupByOption.None) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs index bfc3bb38..c2b3bfe9 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs @@ -17,9 +17,14 @@ public override void ExplicitVisit(HavingClause node) GenerateKeyword(TSqlTokenType.Having); AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); - MarkClauseBodyAlignmentWhenNecessary(_options.NewLineBeforeHavingClause, clauseBody); - - GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); + if (GenerateClauseBodyStart(_options.NewLineBeforeHavingClause, clauseBody)) + { + GenerateFragmentIfNotNull(node.SearchCondition); + } + else + { + GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); + } PopAlignmentPoint(); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InPredicate.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InPredicate.cs index 11e67fc1..dba4c497 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InPredicate.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InPredicate.cs @@ -22,8 +22,17 @@ public override void ExplicitVisit(InPredicate node) if (node.Values.Count > 0) { - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(node.Values); + if (_options.MultilineInValuesList) + { + ListGenerationOption option = ListGenerationOption.CreateOptionFromFormattingConfig(_options); + + GenerateFragmentList(node.Values, option); + } + else + { + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.Values); + } } GenerateSpaceAndFragmentIfNotNull(node.Subquery); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs index 65779630..45957598 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs @@ -66,8 +66,16 @@ public override void ExplicitVisit(InsertSpecification node) if (node.Columns.Count > 0) { MarkInsertColumnsAlignmentPointWhenNecessary(insertColumns); - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(node.Columns); + if (_options.MultilineInsertTargetsList) + { + ListGenerationOption option = ListGenerationOption.CreateOptionFromFormattingConfig(_options); + GenerateFragmentList(node.Columns, option); + } + else + { + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.Columns); + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs index fef0ebe3..2fbb9c26 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs @@ -32,7 +32,7 @@ internal enum SeparatorType public Boolean NewLineBeforeItems { get; set; } public int MultipleIndentItems { get; set; } - public static ListGenerationOption MultipleLineSelectElementOption = new ListGenerationOption() + public static readonly ListGenerationOption MultipleLineSelectElementOption = new ListGenerationOption() { Parenthesised = false, AlwaysGenerateParenthesis = false, @@ -45,6 +45,23 @@ internal enum SeparatorType MultipleIndentItems = 0, }; + // Non-parenthesized, one-item-per-line list indented a single level. Used for + // CREATE/ALTER PROCEDURE parameters, which (unlike function parameters) are not wrapped + // in parentheses. The leading new line is produced by the option itself + // (NewLineBeforeFirstItem), so callers must not emit their own new line first. + public static readonly ListGenerationOption MultipleLineProcedureParameterOption = new ListGenerationOption() + { + Parenthesised = false, + AlwaysGenerateParenthesis = false, + IndentParentheses = false, + AlignParentheses = false, + + Separator = SeparatorType.Comma, + NewLineBeforeFirstItem = true, + NewLineBeforeItems = true, + MultipleIndentItems = 1, + }; + public static ListGenerationOption CreateOptionFromFormattingConfig(SqlScriptGeneratorOptions formatting) { ListGenerationOption option = new ListGenerationOption(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.MergeStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.MergeStatement.cs index 67c855c0..20e497a8 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.MergeStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.MergeStatement.cs @@ -115,8 +115,16 @@ public override void ExplicitVisit(InsertMergeAction node) AddAlignmentPointForFragment(node.Source, clauseBody); if (node.Columns.Count > 0) { - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(node.Columns); + if (_options.MultilineInsertTargetsList) + { + ListGenerationOption option = ListGenerationOption.CreateOptionFromFormattingConfig(_options); + GenerateFragmentList(node.Columns, option); + } + else + { + GenerateSpace(); + GenerateParenthesisedCommaSeparatedList(node.Columns); + } } if (node.Source != null) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs index 90627187..c74949e7 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs @@ -18,9 +18,10 @@ public override void ExplicitVisit(OrderByClause node) GenerateSpaceAndKeyword(TSqlTokenType.By); AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); - MarkClauseBodyAlignmentWhenNecessary(_options.NewLineBeforeOrderByClause, clauseBody); - - GenerateSpace(); + if (!GenerateClauseBodyStart(_options.NewLineBeforeOrderByClause, clauseBody)) + { + GenerateSpace(); + } GenerateCommaSeparatedList(node.OrderByElements); PopAlignmentPoint(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ProcedureStatementBody.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ProcedureStatementBody.cs index db09332a..e0728105 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ProcedureStatementBody.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ProcedureStatementBody.cs @@ -18,11 +18,7 @@ protected void GenerateProcedureStatementBody(ProcedureStatementBody node) // name GenerateSpaceAndFragmentIfNotNull(node.ProcedureReference); - if (node.Parameters != null && node.Parameters.Count > 0) - { - NewLine(); - GenerateCommaSeparatedList(node.Parameters); - } + GenerateProcedureOrFunctionParameters(node.Parameters, parenthesized: false); GenerateCommaSeparatedWithClause(node.Options, false, false); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QuerySpecification.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QuerySpecification.cs index 5edb52f3..52792500 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QuerySpecification.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QuerySpecification.cs @@ -27,29 +27,56 @@ protected void GenerateQuerySpecification(QuerySpecification node, AlignmentPoin GenerateKeyword(TSqlTokenType.Select); + // The select list cannot go through GenerateClauseBodyStart because any DISTINCT/TOP + // modifiers are emitted between the keyword and the list: the river has to be marked + // right after SELECT, while the indented line break only happens after the modifiers. + bool indentSelectList = _options.ClauseBodyAlignment == ClauseBodyAlignment.Indented; + MarkClauseBodyAlignmentWhenNecessary(true, clauseBody); GenerateUniqueRowFilter(node.UniqueRowFilter, true); GenerateSpaceAndFragmentIfNotNull(node.TopRowFilter); - GenerateSpace(); + // In Indented mode the select list starts on its own line, one level in, while any + // DISTINCT/TOP modifiers stay on the SELECT line. Every other (including the default + // Aligned) case falls through to the original "GenerateSpace()", so the default is unchanged. + if (indentSelectList) + { + NewLineAndIndent(); + } + else + { + GenerateSpace(); + } GenerateSelectElementsList(node.SelectElements); if (intoClause != null) { NewLine(); GenerateKeyword(TSqlTokenType.Into); - MarkClauseBodyAlignmentWhenNecessary(true, clauseBody); - GenerateSpaceAndFragmentIfNotNull(intoClause); + if (GenerateClauseBodyStart(true, clauseBody)) + { + GenerateFragmentIfNotNull(intoClause); + } + else + { + GenerateSpaceAndFragmentIfNotNull(intoClause); + } } if (filegroupClause != null) { NewLine(); GenerateKeyword(TSqlTokenType.On); - MarkClauseBodyAlignmentWhenNecessary(true, clauseBody); - GenerateSpaceAndFragmentIfNotNull(filegroupClause); + if (GenerateClauseBodyStart(true, clauseBody)) + { + GenerateFragmentIfNotNull(filegroupClause); + } + else + { + GenerateSpaceAndFragmentIfNotNull(filegroupClause); + } } GenerateFromClause(node.FromClause, clauseBody); @@ -100,8 +127,10 @@ protected void GenerateQuerySpecification(QuerySpecification node, AlignmentPoin { NewLine(); GenerateKeyword(TSqlTokenType.For); - MarkClauseBodyAlignmentWhenNecessary(true, clauseBody); - GenerateSpace(); + if (!GenerateClauseBodyStart(true, clauseBody)) + { + GenerateSpace(); + } AlignmentPoint forBody = new AlignmentPoint(); MarkAndPushAlignmentPoint(forBody); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs index 4c872987..1cdbb2fa 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.StatementList.cs @@ -15,6 +15,7 @@ public override void ExplicitVisit(StatementList node) if (node.Statements != null) { Boolean first = true; + TSqlStatement previous = null; foreach (TSqlStatement statement in node.Statements) { if (first) @@ -23,6 +24,7 @@ public override void ExplicitVisit(StatementList node) } else { + GenerateSeparatingSemiColonWhenNecessary(previous, statement); for (var i = 0; i < _options.NumNewlinesAfterStatement; i++) { NewLine(); @@ -30,6 +32,7 @@ public override void ExplicitVisit(StatementList node) } GenerateStatementWithSemiColon(statement); + previous = statement; } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs index 04205900..a5ed633c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs @@ -11,10 +11,16 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(TSqlBatch node) { - foreach (TSqlStatement statement in node.Statements) + for (int index = 0; index < node.Statements.Count; index++) { + TSqlStatement statement = node.Statements[index]; GenerateStatementWithSemiColon(statement); + if (index + 1 < node.Statements.Count) + { + GenerateSeparatingSemiColonWhenNecessary(statement, node.Statements[index + 1]); + } + if (statement is TSqlStatementSnippet == false) { NewLine(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs index 1f5644c4..2e222117 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs @@ -18,15 +18,29 @@ public override void ExplicitVisit(WhereClause node) AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); - MarkClauseBodyAlignmentWhenNecessary(_options.NewLineBeforeWhereClause, clauseBody); + bool indented = GenerateClauseBodyStart(_options.NewLineBeforeWhereClause, clauseBody); if (node.SearchCondition != null) { - GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); + if (indented) + { + GenerateFragmentIfNotNull(node.SearchCondition); + } + else + { + GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); + } } else { - GenerateSpaceAndKeyword(TSqlTokenType.Current); + if (indented) + { + GenerateKeyword(TSqlTokenType.Current); + } + else + { + GenerateSpaceAndKeyword(TSqlTokenType.Current); + } GenerateSpaceAndKeyword(TSqlTokenType.Of); GenerateSpaceAndFragmentIfNotNull(node.Cursor); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml index 6225d168..e8b6bd1c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml +++ b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml @@ -107,8 +107,13 @@ + + + + Gets or sets how a clause body (the part after FROM, WHERE, GROUP BY, etc.) is laid out. Aligned keeps the body on the keyword's line, lining all clause bodies up under a shared column past the widest keyword. Indented puts the body on its own new line, one indent level (IndentationSize) past the keyword, so nesting grows one step per level instead of drifting right. When Indented, AlignClauseBodies is ignored. + - Gets or sets a boolean indicating if the bodies of FROM, WHERE, GROUP BY, etc. clauses should be aligned + Gets or sets whether clause bodies are padded to line up under a shared column. Only applies when ClauseBodyAlignment is Aligned: true pads to the aligned column, false uses a single space after the keyword. Ignored when ClauseBodyAlignment is Indented. @@ -118,6 +123,9 @@ Gets or sets a boolean indicating if WHERE predicates (expressions separated by AND, and OR) should be written on multiple lines + + Gets or sets a boolean indicating if the values in an IN (values) predicate should be listed as a multi-line list. When false, the IN list is written on a single line. + @@ -148,13 +156,18 @@ - + Gets or sets a boolean indicating if the INSERT column targets list should be spread across multiple lines Gets or sets a boolean indicating if the INSERT column sources list should be spread across multiple lines + + + Gets or sets a boolean indicating if procedure and function parameters should be listed on separate lines. When false (the default), all parameters are written on a single line, preserving the previous script-generation behavior. When true, each parameter is placed on its own line, indented one level from the procedure or function name. CommaPlacement applies to the parameter list. AlignColumnDefinitionFields does not apply to procedure or function parameters. + + Gets or sets a boolean indicating if a newline should be placed before an open parenthesis when writing a multi-line list in parenthesis diff --git a/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs b/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs new file mode 100644 index 00000000..7de4b8dd --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs @@ -0,0 +1,887 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the ClauseBodyAlignment script-generation option, which controls how the body of a + // clause (the part after FROM, WHERE, GROUP BY, etc.) is laid out: Aligned (the classic + // keyword-width "rivers of whitespace" style) or Indented (each body on its own line, one indent + // level past the keyword, so nesting grows linearly instead of drifting right). + // + // Work item: Formatter option: Indentation vs alignment (ClauseBodyAlignment) + [TestClass] + public class ClauseBodyAlignmentTests + { + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestClauseBodyAlignmentDefaultIsAligned() + { + Assert.AreEqual(ClauseBodyAlignment.Aligned, new SqlScriptGeneratorOptions().ClauseBodyAlignment); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedIgnoresAlignClauseBodies() + { + // When Indented, AlignClauseBodies has no effect: both settings produce the same output. + const string input = "SELECT a FROM t WHERE b = 1;"; + var alignOn = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented, AlignClauseBodies = true }; + var alignOff = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented, AlignClauseBodies = false }; + + Assert.AreEqual(Normalize(Generate(input, alignOn)), Normalize(Generate(input, alignOff))); + } + + // --- Basic SELECT / FROM / WHERE --------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedMatchesLegacyRiverLayout() + { + // Aligned mode reproduces the existing keyword-width "river" alignment. + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a +FROM t +WHERE b = 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedPutsEachClauseBodyOnItsOwnLine() + { + // Indented mode drops each clause body onto its own line, one indent level past the keyword. + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a +FROM + t +WHERE + b = 1;"; + + AssertGenerated(input, options, expected); + } + + // --- Multi-column SELECT list ------------------------------------------------------------ + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedMultiColumnSelectList() + { + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a, + b, + c +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedMultiColumnSelectList() + { + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a, + b, + c +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + // --- DISTINCT / TOP stay on the SELECT line ---------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedKeepsDistinctAndTopOnSelectLine() + { + const string input = "SELECT DISTINCT TOP 5 a FROM t;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT DISTINCT TOP 5 a +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedKeepsDistinctAndTopOnSelectLine() + { + const string input = "SELECT DISTINCT TOP 5 a FROM t;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT DISTINCT TOP 5 + a +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + // --- GROUP BY / HAVING / ORDER BY -------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedGroupByAndHaving() + { + const string input = "SELECT a, COUNT(*) FROM t GROUP BY a HAVING COUNT(*) > 1 ORDER BY a;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a, + COUNT(*) +FROM t +GROUP BY a +HAVING COUNT(*) > 1 +ORDER BY a;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedGroupByAndHaving() + { + const string input = "SELECT a, COUNT(*) FROM t GROUP BY a HAVING COUNT(*) > 1 ORDER BY a;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a, + COUNT(*) +FROM + t +GROUP BY + a +HAVING + COUNT(*) > 1 +ORDER BY + a;"; + + AssertGenerated(input, options, expected); + } + + // --- Nested derived table (the motivating case: linear growth vs. rightward drift) ------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedNestedDerivedTable() + { + // Aligned pushes the inner query to the right of the outer FROM keyword; Indented (below) + // adds a single fixed level per nesting instead. + const string input = "SELECT o.a FROM (SELECT x AS a FROM t1 WHERE x > 0) AS o WHERE o.a < 10;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT o.a +FROM (SELECT x AS a + FROM t1 + WHERE x > 0) AS o +WHERE o.a < 10;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedNestedDerivedTableGrowsLinearly() + { + const string input = "SELECT o.a FROM (SELECT x AS a FROM t1 WHERE x > 0) AS o WHERE o.a < 10;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + o.a +FROM + (SELECT + x AS a + FROM + t1 + WHERE + x > 0) AS o +WHERE + o.a < 10;"; + + AssertGenerated(input, options, expected); + } + + // --- UNION ------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedUnion() + { + const string input = "SELECT a FROM t1 UNION SELECT b FROM t2;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a +FROM t1 +UNION +SELECT b +FROM t2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedUnion() + { + const string input = "SELECT a FROM t1 UNION SELECT b FROM t2;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a +FROM + t1 +UNION +SELECT + b +FROM + t2;"; + + AssertGenerated(input, options, expected); + } + + // --- Common table expression ------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedCommonTableExpression() + { + const string input = "WITH c AS (SELECT a FROM t) SELECT a FROM c;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +WITH c +AS (SELECT a + FROM t) +SELECT a +FROM c;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedCommonTableExpression() + { + const string input = "WITH c AS (SELECT a FROM t) SELECT a FROM c;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +WITH c +AS (SELECT + a + FROM + t) +SELECT + a +FROM + c;"; + + AssertGenerated(input, options, expected); + } + + // --- Subquery in WHERE ------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedSubqueryInWhere() + { + const string input = "SELECT a FROM t WHERE x IN (SELECT id FROM u);"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a +FROM t +WHERE x IN (SELECT id + FROM u);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedSubqueryInWhere() + { + const string input = "SELECT a FROM t WHERE x IN (SELECT id FROM u);"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a +FROM + t +WHERE + x IN (SELECT + id + FROM + u);"; + + AssertGenerated(input, options, expected); + } + + // --- Custom indentation size ------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedIgnoresCustomIndentationSize() + { + // Aligned uses keyword width, not IndentationSize, so the size setting has no effect here: + // the output is identical to the default-IndentationSize layout. + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned, IndentationSize = 2 }; + const string expected = +@" +SELECT a +FROM t +WHERE b = 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedHonorsCustomIndentationSize() + { + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented, IndentationSize = 2 }; + const string expected = +@" +SELECT + a +FROM + t +WHERE + b = 1;"; + + AssertGenerated(input, options, expected); + } + + // --- DELETE ... WHERE -------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedDeleteWhereClause() + { + const string input = "DELETE FROM t WHERE x = 1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +DELETE t +WHERE x = 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedDeleteWhereClause() + { + const string input = "DELETE FROM t WHERE x = 1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +DELETE t +WHERE + x = 1;"; + + AssertGenerated(input, options, expected); + } + + // --- UPDATE ------------------------------------------------------------------------------ + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedUpdateStatement() + { + const string input = "UPDATE t SET a = 1 WHERE b = 2;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +UPDATE t +SET a = 1 +WHERE b = 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedUpdateStatement() + { + const string input = "UPDATE t SET a = 1 WHERE b = 2;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +UPDATE t +SET a = 1 +WHERE + b = 2;"; + + AssertGenerated(input, options, expected); + } + + // --- SELECT ... INTO --------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedSelectInto() + { + const string input = "SELECT a INTO t2 FROM t1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a +INTO t2 +FROM t1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedSelectInto() + { + const string input = "SELECT a INTO t2 FROM t1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a +INTO + t2 +FROM + t1;"; + + AssertGenerated(input, options, expected); + } + + // --- WHERE CURRENT OF -------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedWhereCurrentOf() + { + const string input = "DELETE FROM t WHERE CURRENT OF c;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +DELETE t +WHERE CURRENT OF c;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWhereCurrentOf() + { + const string input = "DELETE FROM t WHERE CURRENT OF c;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +DELETE t +WHERE + CURRENT OF c;"; + + AssertGenerated(input, options, expected); + } + + // --- SELECT ... INTO ... ON filegroup ---------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedSelectIntoOnFilegroup() + { + const string input = "SELECT c1 INTO t2 ON fg FROM t1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT c1 +INTO t2 +ON fg +FROM t1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedSelectIntoOnFilegroup() + { + const string input = "SELECT c1 INTO t2 ON fg FROM t1;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + c1 +INTO + t2 +ON + fg +FROM + t1;"; + + AssertGenerated(input, options, expected); + } + + // --- JOIN with ON (does the ON search condition follow the clause-body option?) ---------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedInnerJoin() + { + const string input = "SELECT a.x FROM a INNER JOIN b ON a.id = b.id WHERE a.x > 0;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a.x +FROM a + INNER JOIN + b + ON a.id = b.id +WHERE a.x > 0;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedInnerJoin() + { + const string input = "SELECT a.x FROM a INNER JOIN b ON a.id = b.id WHERE a.x > 0;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a.x +FROM + a + INNER JOIN + b + ON a.id = b.id +WHERE + a.x > 0;"; + + AssertGenerated(input, options, expected); + } + + // --- JOIN with ON, NewLineBeforeJoinClause = false and NewLineBeforeOnClause = false ------ + // (both the JOIN keyword and the ON search condition stay on the table-source line) --------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedInnerJoinNoNewLineBeforeJoin() + { + const string input = "SELECT a.x FROM a INNER JOIN b ON a.id = b.id WHERE a.x > 0;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned, NewLineBeforeJoinClause = false, NewLineBeforeOnClause = false }; + const string expected = +@" +SELECT a.x +FROM a INNER JOIN + b ON a.id = b.id +WHERE a.x > 0;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedInnerJoinNoNewLineBeforeJoin() + { + const string input = "SELECT a.x FROM a INNER JOIN b ON a.id = b.id WHERE a.x > 0;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented, NewLineBeforeJoinClause = false, NewLineBeforeOnClause = false }; + const string expected = +@" +SELECT + a.x +FROM + a INNER JOIN + b ON a.id = b.id +WHERE + a.x > 0;"; + + AssertGenerated(input, options, expected); + } + + // --- NewLineBeforeXxxClause = false (the clause body stays on the keyword line) ----------- + // Indented only moves a clause body onto its own line when that clause is configured to + // start on a new line. With the NewLineBefore* options off, FROM/WHERE keep their bodies + // inline exactly as in Aligned mode. The SELECT list has no NewLineBefore* option of its + // own, so it still breaks onto its own line. + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedNewLineBeforeClauseOptionsDisabled() + { + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Aligned, + NewLineBeforeFromClause = false, + NewLineBeforeWhereClause = false + }; + const string expected = @" +SELECT a FROM t WHERE b = 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedNewLineBeforeClauseOptionsDisabled() + { + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + NewLineBeforeFromClause = false, + NewLineBeforeWhereClause = false + }; + const string expected = @" +SELECT + a FROM t WHERE b = 1;"; + + AssertGenerated(input, options, expected); + } + + // --- AlignClauseBodies = false in Aligned mode ------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedWithAlignClauseBodiesDisabled() + { + // With AlignClauseBodies off, Aligned falls back to a single space after each keyword + // instead of padding to the shared column. The SELECT list still aligns under its own + // first item, which is a separate alignment point. + const string input = "SELECT a, b FROM t WHERE c = 1;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Aligned, + AlignClauseBodies = false + }; + const string expected = +@" +SELECT a, + b +FROM t +WHERE c = 1;"; + + AssertGenerated(input, options, expected); + } + + // --- MultilineSelectElementsList = false -------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWithSingleLineSelectElementsList() + { + // The select list stays on one line but is still indented one level under SELECT. + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + MultilineSelectElementsList = false + }; + const string expected = +@" +SELECT + a, b, c +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + // --- Interaction with IndentationMode.Tabs ------------------------------------------------ + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWithTabsIndentation() + { + // The indent that Indented adds is emitted through the normal indentation path, so it + // is rendered with tab characters when IndentationMode is Tabs. The expected constant + // below contains real tab characters. + const string input = "SELECT a FROM t WHERE b = 1;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + IndentationMode = IndentationMode.Tabs + }; + const string expected = +@" +SELECT + a +FROM + t +WHERE + b = 1;"; + + AssertGenerated(input, options, expected); + } + + // --- Interaction with CommaPlacement.Leading --------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWithLeadingCommas() + { + // Leading commas reserve their width inside the indent, so every select item still + // starts at the same column as the first one. + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + CommaPlacement = CommaPlacement.Leading + }; + const string expected = +@" +SELECT + a + , b + , c +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + // --- OFFSET/FETCH is not a clause body and stays inline ---------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedOffsetFetchIsNotIndented() + { + // ORDER BY is a clause body and indents; the OFFSET/FETCH clause that follows it is + // not part of clause-body handling and keeps its existing inline layout. + const string input = "SELECT a FROM t ORDER BY a OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a +FROM + t +ORDER BY + a +OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;"; + + AssertGenerated(input, options, expected); + } + + // --- FOR clause -------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedForClause() + { + const string input = "SELECT a FROM t FOR XML AUTO;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT a +FROM t +FOR XML AUTO;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedForClause() + { + // The FOR clause body is treated like any other clause body, so it moves onto its own + // indented line rather than staying on the FOR line. + const string input = "SELECT a FROM t FOR XML AUTO;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a +FROM + t +FOR + XML AUTO;"; + + AssertGenerated(input, options, expected); + } + } +} + diff --git a/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs new file mode 100644 index 00000000..0a76defc --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs @@ -0,0 +1,346 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the MultilineInValuesList script-generation option, which controls whether the + // values in an IN (values) predicate are written on a single line (default) or on multiple + // lines. Kept in a dedicated file to avoid churn in ScriptGeneratorTests.cs. + // + // Work item: Formatter option: IN (values) list width + [TestClass] + public class InValuesListFormattingTests + { + // Builds options that isolate the IN-list layout: clause bodies are not aligned and clauses + // are not broken onto their own lines, so the surrounding statement stays on one line and the + // expectations focus on the IN (values) list itself. + private static SqlScriptGeneratorOptions MakeOptions(bool multilineInValuesList) + { + return new SqlScriptGeneratorOptions + { + MultilineInValuesList = multilineInValuesList, + AlignClauseBodies = false, + NewLineBeforeFromClause = false, + NewLineBeforeWhereClause = false, + MultilineSelectElementsList = false, + MultilineWherePredicatesList = false, + }; + } + + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineInValuesListDefaultIsFalse() + { + Assert.IsFalse(new SqlScriptGeneratorOptions().MultilineInValuesList); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsInListOnSingleLine() + { + // With the option at its default (false) the IN list stays on a single line. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(false); + const string expected = @"SELECT * FROM t WHERE x IN (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Multi-line layout + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTrailingCommaPutsEachValueOnItsOwnLine() + { + // With the option enabled and the default (trailing) comma placement, each value is + // written on its own line with a trailing comma. The list is aligned under the WHERE + // clause body, with each value indented one level (4) past the closing parenthesis. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1, + 2, + 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineLeadingCommaPlacement() + { + // CommaPlacement = Leading applies within the IN list: values sit at the list + // indentation level and each comma is indented two characters fewer. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1 + , 2 + , 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNewLineBeforeOpenParenthesis() + { + // NewLineBeforeOpenParenthesisInMultilineList moves the open parenthesis onto its own line. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + options.NewLineBeforeOpenParenthesisInMultilineList = true; + const string expected = @" +SELECT * FROM t WHERE x IN + ( + 1, + 2, + 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNoNewLineBeforeCloseParenthesis() + { + // NewLineBeforeCloseParenthesisInMultilineList = false keeps the close parenthesis on the + // same line as the last value. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + options.NewLineBeforeCloseParenthesisInMultilineList = false; + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1, + 2, + 3);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Variants and edge cases + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineAppliesToNotIn() + { + // The option also governs a negated (NOT IN) list. + const string input = "SELECT * FROM t WHERE x NOT IN (1, 2, 3);"; + var options = MakeOptions(true); + const string expected = @" +SELECT * FROM t WHERE x NOT IN ( + 1, + 2, + 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineSingleValueStillWraps() + { + // A single-value IN list wraps too (consistent with the parenthesized-list behavior used + // for column lists). + const string input = "SELECT * FROM t WHERE x IN (1);"; + var options = MakeOptions(true); + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineDoesNotAffectSubqueryInPredicate() + { + // An IN (subquery) predicate has no value list, so the option must not change it. + const string input = "SELECT * FROM t WHERE x IN (SELECT id FROM u);"; + var options = MakeOptions(true); + const string expected = @"SELECT * FROM t WHERE x IN (SELECT id FROM u);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineWrapsStringAndExpressionValues() + { + // Values can be arbitrary scalar expressions (string literals, columns), not just integers. + const string input = "SELECT * FROM t WHERE x IN ('a', 'b', c);"; + var options = MakeOptions(true); + const string expected = @" +SELECT * FROM t WHERE x IN ( + 'a', + 'b', + c + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineAppliesInDeleteWhereClause() + { + // The option applies wherever an IN (values) predicate appears, not only in SELECT. The + // list aligns under this statement's (shorter) WHERE clause body. + const string input = "DELETE FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + const string expected = @" +DELETE t WHERE x IN ( + 1, + 2, + 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineOnlyAffectsInListWhenOtherListsAreDefault() + { + // Isolation: enabling MultilineInValuesList on top of otherwise-default options wraps the + // IN list, while every other list keeps its own default behavior. Here the SELECT column + // list still wraps because MultilineSelectElementsList defaults to true, independently of + // this option. + const string input = "SELECT a, b FROM t WHERE x IN (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions { MultilineInValuesList = true }; + const string expected = @" +SELECT a, + b +FROM t +WHERE x IN ( + 1, + 2, + 3 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Indentation and multiple contexts + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineHonorsCustomIndentationSize() + { + // Teams that use a 2-space indent should see the wrapped IN values indented by that + // amount (IndentationSize) past the list's alignment level, not the default 4. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + options.IndentationSize = 2; + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1, + 2, + 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineHonorsTabIndentation() + { + // With IndentationMode = Tabs the wrapped IN values are indented with tab characters. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3);"; + var options = MakeOptions(true); + options.IndentationMode = IndentationMode.Tabs; + // The wrapped values are indented with tab characters (the literal tabs in the lines below). + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1, + 2, + 3 + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineAppliesInCheckConstraint() + { + // The option applies to DDL too: a CHECK constraint whose predicate is an IN (values) + // list wraps the values just like a DML WHERE clause. + const string input = "ALTER TABLE t ADD CONSTRAINT ck CHECK (x IN (1, 2, 3));"; + var options = MakeOptions(true); + const string expected = @" +ALTER TABLE t + ADD CONSTRAINT ck CHECK (x IN ( + 1, + 2, + 3 + ));"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineWrapsMultipleInListsIndependently() + { + // A realistic query filtering on two IN lists joined by AND: each list wraps on its own, + // and the surrounding predicate layout is preserved. + const string input = "SELECT * FROM t WHERE x IN (1, 2, 3) AND y IN (4, 5, 6);"; + var options = MakeOptions(true); + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1, + 2, + 3 + ) AND y IN ( + 4, + 5, + 6 + );"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs new file mode 100644 index 00000000..0b8250f3 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs @@ -0,0 +1,486 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the MultilineInsertTargetsList script-generation option, which controls whether the + // INSERT column target list (the parenthesized list of columns after the target table) is + // written one column per line (true) as a multi-line parenthesized list - like the + // CREATE TABLE / VIEW column lists - or collapsed onto a single line (false, the default). The + // option only affects the INSERT target list; the INSERT source (VALUES / SELECT / EXECUTE) is + // unaffected. + [TestClass] + public class InsertTargetsListFormattingTests + { + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineInsertTargetsListDefaultIsFalse() + { + // The default preserves the historical single-line INSERT target list output. + Assert.AreEqual(false, new SqlScriptGeneratorOptions().MultilineInsertTargetsList); + } + + // ----------------------------------------------------------------------------------------- + // VALUES source + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSingleLineTargetsIsDefault() + { + // With default options the target list stays on a single line (unchanged behavior). + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +INSERT INTO t (a, b, c) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWhenEnabled() + { + // When the option is enabled each target column is placed on its own line inside the + // parentheses. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a, + b, + c +) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSingleLineTargetsWhenDisabled() + { + // With the option off the target list collapses onto a single line. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = false }; + const string expected = +@" +INSERT INTO t (a, b, c) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSingleTargetMultiline() + { + // A single-column target list is still spread onto its own line when the option is on. + const string input = "INSERT INTO t (a) VALUES (1);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a +) +VALUES (1);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNoTargetsUnaffected() + { + // An INSERT with no column target list is unaffected by the option. + const string input = "INSERT INTO t VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +INSERT INTO t +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNoTargetsUnaffectedWhenDisabled() + { + // The same INSERT with no target list is identical whether the option is on or off. + const string input = "INSERT INTO t VALUES (1, 2, 3);"; + var on = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + var off = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = false }; + + Assert.AreEqual(Normalize(Generate(input, on)), Normalize(Generate(input, off))); + } + + // ----------------------------------------------------------------------------------------- + // SELECT source + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithSelectSource() + { + // The multi-line target list works the same way when the source is a SELECT. + const string input = "INSERT INTO t (a, b) SELECT x, y FROM s;"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a, + b +) +SELECT x, + y +FROM s;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSingleLineTargetsWithSelectSourceWhenDisabled() + { + const string input = "INSERT INTO t (a, b) SELECT x, y FROM s;"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = false }; + const string expected = +@" +INSERT INTO t (a, b) +SELECT x, + y +FROM s;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Comma placement + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommaMultilineTargets() + { + // With CommaPlacement = Leading each column's comma is emitted at the start of its line, + // indented two characters fewer than the column. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true, CommaPlacement = CommaPlacement.Leading }; + const string expected = +@" +INSERT INTO t ( + a + , b + , c +) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingCommaMultilineTargets() + { + // With CommaPlacement = Trailing (default) each column's comma follows it. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true, CommaPlacement = CommaPlacement.Trailing }; + const string expected = +@" +INSERT INTO t ( + a, + b, + c +) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Parenthesis placement options + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsNewLineBeforeOpenParenthesis() + { + // NewLineBeforeOpenParenthesisInMultilineList moves the opening parenthesis to its own + // line for the multi-line target list. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions + { + MultilineInsertTargetsList = true, + NewLineBeforeOpenParenthesisInMultilineList = true, + }; + const string expected = +@" +INSERT INTO t +( + a, + b, + c +) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsNewLineBeforeCloseParenthesisDisabled() + { + // With NewLineBeforeCloseParenthesisInMultilineList off the closing parenthesis stays on + // the same line as the last column. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions + { + MultilineInsertTargetsList = true, + NewLineBeforeCloseParenthesisInMultilineList = false, + }; + const string expected = +@" +INSERT INTO t ( + a, + b, + c) +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction with other INSERT clauses / sources + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithOutputClause() + { + // The multi-line target list renders correctly when an OUTPUT clause follows it. + const string input = "INSERT INTO t (a, b) OUTPUT inserted.a, inserted.b VALUES (1, 2);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a, + b +) +OUTPUT inserted.a, inserted.b +VALUES (1, 2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithOutputIntoClause() + { + // The multi-line target list renders correctly when an OUTPUT ... INTO clause follows it. + const string input = "INSERT INTO t (a, b) OUTPUT inserted.a INTO @log VALUES (1, 2);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a, + b +) +OUTPUT inserted.a INTO @log +VALUES (1, 2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithExecuteSource() + { + // The multi-line target list works when the source is an EXECUTE statement. + const string input = "INSERT INTO t (a, b) EXEC('select 1, 2');"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a, + b +) +EXECUTE ('select 1, 2');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithTopRowFilter() + { + // A TOP row filter before the target table does not interfere with the multi-line list. + const string input = "INSERT TOP (5) INTO t (a, b) SELECT x, y FROM s;"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT TOP (5) INTO t ( + a, + b +) +SELECT x, + y +FROM s;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithCommonTableExpression() + { + // A leading WITH common table expression does not interfere with the multi-line list. + const string input = "WITH c AS (SELECT 1 x, 2 y) INSERT INTO t (a, b) SELECT x, y FROM c;"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +WITH c +AS (SELECT 1 AS x, + 2 AS y) +INSERT INTO t ( + a, + b +) +SELECT x, + y +FROM c;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithMultiRowValues() + { + // Only the target list is affected; a multi-row VALUES source is left as-is. + const string input = "INSERT INTO t (a, b) VALUES (1, 2), (3, 4);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +INSERT INTO t ( + a, + b +) +VALUES (1, 2), +(3, 4);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // MERGE ... WHEN NOT MATCHED THEN INSERT + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMergeInsertTargetsSingleLineIsDefault() + { + // The INSERT action of a MERGE keeps its target list single-line by default (unchanged + // behavior), just like a top-level INSERT. + const string input = "MERGE INTO t USING s ON t.id = s.id WHEN NOT MATCHED THEN INSERT (a, b, c) VALUES (s.a, s.b, s.c);"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +MERGE INTO t + +USING s ON t.id = s.id +WHEN NOT MATCHED THEN INSERT (a, b, c) VALUES (s.a, s.b, s.c);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMergeInsertTargetsMultilineWhenEnabled() + { + // The INSERT action of a MERGE honors MultilineInsertTargetsList, spreading its target + // list one column per line - parity with the top-level INSERT statement. + const string input = "MERGE INTO t USING s ON t.id = s.id WHEN NOT MATCHED THEN INSERT (a, b, c) VALUES (s.a, s.b, s.c);"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +MERGE INTO t + +USING s ON t.id = s.id +WHEN NOT MATCHED THEN INSERT ( + a, + b, + c +) VALUES (s.a, s.b, s.c);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMergeInsertTargetsMultilineRealWorld() + { + // A realistic MERGE with an aliased target/source and UPDATE / INSERT / DELETE actions: + // only the INSERT action's target list is spread onto multiple lines. + const string input = + "MERGE INTO dbo.Target AS tgt USING dbo.Source AS src ON tgt.Id = src.Id " + + "WHEN MATCHED THEN UPDATE SET tgt.Name = src.Name, tgt.Amount = src.Amount " + + "WHEN NOT MATCHED BY TARGET THEN INSERT (Id, Name, Amount) VALUES (src.Id, src.Name, src.Amount) " + + "WHEN NOT MATCHED BY SOURCE THEN DELETE;"; + var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; + const string expected = +@" +MERGE INTO dbo.Target + AS tgt +USING dbo.Source AS src ON tgt.Id = src.Id +WHEN MATCHED THEN UPDATE +SET tgt.Name = src.Name, + tgt.Amount = src.Amount +WHEN NOT MATCHED BY TARGET THEN INSERT ( + Id, + Name, + Amount +) VALUES (src.Id, src.Name, src.Amount) +WHEN NOT MATCHED BY SOURCE THEN DELETE;"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/ProcedureParametersFormattingTests.cs b/Test/SqlDom/ScriptGenerator/ProcedureParametersFormattingTests.cs new file mode 100644 index 00000000..1f50dcc9 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/ProcedureParametersFormattingTests.cs @@ -0,0 +1,437 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using System.Collections.Generic; +using System.IO; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the MultilineProcedureParametersList script-generation option, which controls + // whether CREATE/ALTER PROCEDURE and CREATE/ALTER FUNCTION parameters are written one per line + // (true) or collapsed onto a single line (false, the default). The default preserves the + // existing single-line behavior; multi-line output is opt-in. Procedure parameters are not + // wrapped in parentheses; function parameters are. + // + // Work item: Formatter option: Procedure/function parameters across multiple lines + [TestClass] + public class ProcedureParametersFormattingTests + { + // Options that opt in to the multi-line parameter layout, leaving everything else at default. + private static SqlScriptGeneratorOptions Multiline() + { + return new SqlScriptGeneratorOptions { MultilineProcedureParametersList = true }; + } + + // Generates a script for CREATE/ALTER EXTERNAL FUNCTION syntax, which is parsed and emitted + // by the Fabric DW parser/generator. Asserts the input parses and the output reparses. + private static string GenerateFabricDW(string sql, SqlScriptGeneratorOptions options) + { + var parser = new TSqlFabricDWParser(true); + TSqlFragment fragment = parser.Parse(new StringReader(sql), out IList errors); + Assert.AreEqual(0, errors.Count, "Input must parse without errors."); + + var generator = new SqlFabricDWScriptGenerator(options); + generator.GenerateScript(fragment, out string generated); + + var reparser = new TSqlFabricDWParser(true); + reparser.Parse(new StringReader(generated), out IList reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated script must reparse without errors. Actual:\n" + generated); + return generated; + } + + // ----------------------------------------------------------------------------------------- + // Default: the option is off, so existing single-line behavior is preserved. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineProcedureParametersListDefaultIsFalse() + { + Assert.AreEqual(false, new SqlScriptGeneratorOptions().MultilineProcedureParametersList); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestProcedureDefaultKeepsParametersOnSingleLine() + { + // Default options must reproduce the previous behavior: all parameters on one line. + const string input = "CREATE PROCEDURE p1 @a INT, @b INT AS SELECT 1;"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +CREATE PROCEDURE p1 +@a INT, @b INT +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionDefaultKeepsParametersOnSingleLine() + { + // Default options must reproduce the previous behavior: parameters on one parenthesized line. + const string input = "CREATE FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +CREATE FUNCTION dbo.f +(@a INT, @b INT) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestProcedureNoParametersUnaffected() + { + const string input = "CREATE PROCEDURE p1 AS SELECT 1;"; + var options = Multiline(); + const string expected = +@" +CREATE PROCEDURE p1 +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionNoParametersUnaffected() + { + const string input = "CREATE FUNCTION dbo.f () RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + const string expected = +@" +CREATE FUNCTION dbo.f +( ) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // CREATE PROCEDURE with the option enabled (parameters are not parenthesized) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestProcedureMultilineWhenEnabled() + { + const string input = "CREATE PROCEDURE p1 @a INT, @b INT AS SELECT 1;"; + var options = Multiline(); + const string expected = +@" +CREATE PROCEDURE p1 + @a INT, + @b INT +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestProcedureSingleParameterMultilineWhenEnabled() + { + const string input = "CREATE PROCEDURE p1 @a INT AS SELECT 1;"; + var options = Multiline(); + const string expected = +@" +CREATE PROCEDURE p1 + @a INT +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestProcedureMultilineLeadingComma() + { + const string input = "CREATE PROCEDURE p1 @a INT, @b INT AS SELECT 1;"; + var options = Multiline(); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = +@" +CREATE PROCEDURE p1 + @a INT + , @b INT +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCreateOrAlterProcedureMultilineWhenEnabled() + { + const string input = "CREATE OR ALTER PROCEDURE p1 @a INT, @b INT AS SELECT 1;"; + var options = Multiline(); + const string expected = +@" +CREATE OR ALTER PROCEDURE p1 + @a INT, + @b INT +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // CREATE FUNCTION with the option enabled (parameters are parenthesized) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionMultilineWhenEnabled() + { + const string input = "CREATE FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + const string expected = +@" +CREATE FUNCTION dbo.f ( + @a INT, + @b INT +) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionMultilineLeadingComma() + { + const string input = "CREATE FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = +@" +CREATE FUNCTION dbo.f ( + @a INT + , @b INT +) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlterFunctionMultilineWhenEnabled() + { + const string input = "ALTER FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + const string expected = +@" +ALTER FUNCTION dbo.f ( + @a INT, + @b INT +) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // AlignColumnDefinitionFields must not affect procedure/function parameters + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignColumnDefinitionFieldsDoesNotAffectParameters() + { + const string input = "CREATE PROCEDURE p1 @a INT, @bbbbb NVARCHAR (20) AS SELECT 1;"; + var options = Multiline(); + options.AlignColumnDefinitionFields = true; + const string expected = +@" +CREATE PROCEDURE p1 + @a INT, + @bbbbb NVARCHAR (20) +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Parameter modifiers and parenthesis-placement interactions (multi-line enabled) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestProcedureMultilinePreservesParameterModifiers() + { + // Each per-line parameter must retain its full modifiers (default value, OUTPUT, cursor). + const string input = "CREATE PROCEDURE p1 @a INT = 5 OUTPUT, @c CURSOR VARYING OUTPUT AS SELECT 1;"; + var options = Multiline(); + const string expected = +@" +CREATE PROCEDURE p1 + @a INT=5 OUTPUT, + @c CURSOR VARYING OUTPUT +AS +SELECT 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionMultilineNewLineBeforeOpenParenthesis() + { + // NewLineBeforeOpenParenthesisInMultilineList moves the '(' onto its own line for the + // parenthesized (function) parameter list. + const string input = "CREATE FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + options.NewLineBeforeOpenParenthesisInMultilineList = true; + const string expected = +@" +CREATE FUNCTION dbo.f +( + @a INT, + @b INT +) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionMultilineNoNewLineBeforeCloseParenthesis() + { + // NewLineBeforeCloseParenthesisInMultilineList = false keeps ')' on the last parameter's line. + const string input = "CREATE FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + options.NewLineBeforeCloseParenthesisInMultilineList = false; + const string expected = +@" +CREATE FUNCTION dbo.f ( + @a INT, + @b INT) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCreateOrAlterFunctionMultilineWhenEnabled() + { + const string input = "CREATE OR ALTER FUNCTION dbo.f (@a INT, @b INT) RETURNS INT AS BEGIN RETURN 1; END"; + var options = Multiline(); + const string expected = +@" +CREATE OR ALTER FUNCTION dbo.f ( + @a INT, + @b INT +) +RETURNS INT +AS +BEGIN + RETURN 1; +END"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // CREATE/ALTER EXTERNAL FUNCTION (Fabric DW; parameters are parenthesized) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestExternalFunctionDefaultKeepsParametersOnSingleLine() + { + const string input = "CREATE FUNCTION dbo.fn (@x INT, @y NVARCHAR (50)) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn;"; + var options = new SqlScriptGeneratorOptions(); + string generated = GenerateFabricDW(input, options); + + const string expected = +@"CREATE FUNCTION dbo.fn (@x INT, @y NVARCHAR (50)) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn;"; + + Assert.AreEqual(Normalize(expected).Trim(), Normalize(generated).Trim()); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestExternalFunctionMultilineWhenEnabled() + { + const string input = "CREATE FUNCTION dbo.fn (@x INT, @y NVARCHAR (50)) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn;"; + var options = Multiline(); + string generated = GenerateFabricDW(input, options); + + const string expected = +@"CREATE FUNCTION dbo.fn ( + @x INT, + @y NVARCHAR (50) +) RETURNS INT AS EXTERNAL FUNCTION mySet.myFn;"; + + Assert.AreEqual(Normalize(expected).Trim(), Normalize(generated).Trim()); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs index fdaf7632..a153791d 100644 --- a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs @@ -2385,11 +2385,10 @@ public void TestCommaPlacementTrailingParenthesizedList() [SqlStudioTestCategory(Category.UnitTest)] public void TestCommaPlacementLeadingInsertTargets() { - // The INSERT column target list is always emitted as a single-line parenthesized - // list (via GenerateParenthesisedCommaSeparatedList), and CommaPlacement only affects - // multi-line lists. MultilineInsertTargetsList is not consumed by the INSERT visitor, - // so the targets stay on one line and CommaPlacement = Leading has no visual effect: - // the output is identical to the trailing case below. + // With MultilineInsertTargetsList = true the INSERT column target list is emitted as a + // multi-line parenthesized list (like CREATE TABLE / VIEW columns): each column on its + // own line indented one level. CommaPlacement = Leading places each column's comma at + // the start of its line (indented two characters fewer than the column). var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; var parser = new TSql170Parser(true); var fragment = parser.Parse(new StringReader(sql), out var errors); @@ -2403,7 +2402,11 @@ public void TestCommaPlacementLeadingInsertTargets() generator.GenerateScript(fragment, out var generated); string expected = - "INSERT INTO t (a, b, c)" + Environment.NewLine + + "INSERT INTO t (" + Environment.NewLine + + " a" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + ")" + Environment.NewLine + "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; Assert.AreEqual(expected, generated); @@ -2417,10 +2420,9 @@ public void TestCommaPlacementLeadingInsertTargets() [SqlStudioTestCategory(Category.UnitTest)] public void TestCommaPlacementTrailingInsertTargets() { - // Same output as the leading case: because the INSERT target list renders on a - // single line (CommaPlacement only affects multi-line lists, and - // MultilineInsertTargetsList is not consumed here), leading and trailing placement - // produce identical text. + // With MultilineInsertTargetsList = true and CommaPlacement = Trailing (default) the + // INSERT column target list is emitted multi-line with each column on its own line and + // its comma trailing the column. var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; var parser = new TSql170Parser(true); var fragment = parser.Parse(new StringReader(sql), out var errors); @@ -2434,7 +2436,11 @@ public void TestCommaPlacementTrailingInsertTargets() generator.GenerateScript(fragment, out var generated); string expected = - "INSERT INTO t (a, b, c)" + Environment.NewLine + + "INSERT INTO t (" + Environment.NewLine + + " a," + Environment.NewLine + + " b," + Environment.NewLine + + " c" + Environment.NewLine + + ")" + Environment.NewLine + "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; Assert.AreEqual(expected, generated); @@ -2451,7 +2457,9 @@ public void TestCommaPlacementLeadingInsertSources() // The INSERT source (VALUES) row list is a multi-line comma-separated list, so // CommaPlacement = Leading places each continuation row's comma at the start of its // line. (The rows are not aligned under the first row: this list is emitted via the - // newline comma-list path, so continuation rows begin at column 0.) + // newline comma-list path, so continuation rows begin at column 0.) The target column + // list is emitted multi-line because MultilineInsertTargetsList is explicitly enabled + // (it is no longer the default). var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; var parser = new TSql170Parser(true); var fragment = parser.Parse(new StringReader(sql), out var errors); @@ -2460,12 +2468,17 @@ public void TestCommaPlacementLeadingInsertSources() var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading, - MultilineInsertSourcesList = true + MultilineInsertSourcesList = true, + MultilineInsertTargetsList = true }); generator.GenerateScript(fragment, out var generated); string expected = - "INSERT INTO t (a, b, c)" + Environment.NewLine + + "INSERT INTO t (" + Environment.NewLine + + " a" + Environment.NewLine + + " , b" + Environment.NewLine + + " , c" + Environment.NewLine + + ")" + Environment.NewLine + "VALUES (1, 2, 3)" + Environment.NewLine + ", (4, 5, 6)" + Environment.NewLine + ", (7, 8, 9);" + Environment.NewLine + Environment.NewLine; @@ -2482,7 +2495,9 @@ public void TestCommaPlacementLeadingInsertSources() public void TestCommaPlacementTrailingInsertSources() { // The INSERT source (VALUES) row list with CommaPlacement = Trailing (default): - // each row's comma follows it at the end of the line. + // each row's comma follows it at the end of the line. The target column list stays + // on a single line because MultilineInsertTargetsList is left at its default (false), + // exercising the common case of enabling only the source list. var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; var parser = new TSql170Parser(true); var fragment = parser.Parse(new StringReader(sql), out var errors); @@ -2891,7 +2906,8 @@ public void TestCommaPlacementLeadingInsertSourcesMultilineFalse() // The INSERT source (VALUES) row list is always emitted multi-line (the generator // does not gate it on MultilineInsertSourcesList), so setting that option to false // does NOT collapse it to one line: CommaPlacement = Leading still applies to the - // row separators. + // row separators. The target column list stays on a single line because + // MultilineInsertTargetsList is left at its default (false). var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; var parser = new TSql170Parser(true); var fragment = parser.Parse(new StringReader(sql), out var errors); diff --git a/Test/SqlDom/ScriptGenerator/SeparatingSemiColonTests.cs b/Test/SqlDom/ScriptGenerator/SeparatingSemiColonTests.cs new file mode 100644 index 00000000..dba9f17a --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/SeparatingSemiColonTests.cs @@ -0,0 +1,490 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the separating-semicolon behavior of the script generator. SQL Server requires the + // statement that precedes a statement beginning with a WITH clause (a common table expression or + // XMLNAMESPACES) or a THROW statement to be terminated with a semicolon. The generator does not + // append a semicolon to block statements (IF / BEGIN...END / WHILE / TRY...CATCH), so when such a + // block is followed by a CTE or THROW the generator injects the required separating semicolon so + // the generated script is valid for SQL Server. + [TestClass] + public class SeparatingSemiColonTests + { + // ----------------------------------------------------------------------------------------- + // CTE following a block + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterBeginEndBlockGetsSeparatingSemicolon() + { + const string input = +@"DECLARE @x INT; +IF @x IS NULL BEGIN SELECT 1; END +;WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT; + +IF @x IS NULL + BEGIN + SELECT 1; + END; + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterIfStatementWithoutBlockHasNoDoubleSemicolon() + { + // The IF's then-statement already ends with its own semicolon, so no additional + // separating semicolon is injected (no "SELECT 0;;"). + const string input = +@"DECLARE @x INT; +IF @x IS NULL SELECT 0 +;WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT; + +IF @x IS NULL + SELECT 0; + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterWhileBlockGetsSeparatingSemicolon() + { + const string input = +@"DECLARE @x INT = 0; +WHILE @x < 1 BEGIN SET @x = @x + 1; END +;WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT = 0; + +WHILE @x < 1 + BEGIN + SET @x = @x + 1; + END; + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterTryCatchBlockGetsSeparatingSemicolon() + { + const string input = +@"BEGIN TRY SELECT 1; END TRY BEGIN CATCH SELECT 2; END CATCH +;WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +BEGIN TRY + SELECT 1; +END TRY +BEGIN CATCH + SELECT 2; +END CATCH; + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestXmlNamespacesAfterBeginEndBlockGetsSeparatingSemicolon() + { + // A WITH XMLNAMESPACES statement (the other kind of statement that begins with WITH) + // requires the same preceding semicolon as a common table expression. + const string input = +@"DECLARE @x INT; +IF @x IS NULL BEGIN SELECT 1; END +WITH XMLNAMESPACES ('uri' AS ns) SELECT 1 AS c"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT; + +IF @x IS NULL + BEGIN + SELECT 1; + END; + +WITH XMLNAMESPACES ('uri' AS ns) +SELECT 1 AS c;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteInsertAfterBeginEndBlockGetsSeparatingSemicolon() + { + // A common table expression can feed any DML statement, not just SELECT. Here the CTE + // feeds an INSERT that follows a block, so the separating semicolon is still required. + const string input = +@"DECLARE @x INT; +IF @x IS NULL BEGIN SELECT 1; END +WITH cte AS (SELECT 1 AS c) INSERT INTO t (c) SELECT c FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT; + +IF @x IS NULL + BEGIN + SELECT 1; + END; + +WITH cte +AS (SELECT 1 AS c) +INSERT INTO t (c) +SELECT c +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterIfElseBlockGetsSeparatingSemicolon() + { + // The IF statement ends with the ELSE branch's END (no terminator), so a CTE that + // follows the whole IF...ELSE still needs the separating semicolon. + const string input = +@"DECLARE @x INT; +IF @x = 1 BEGIN SELECT 1; END ELSE BEGIN SELECT 2; END +WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT; + +IF @x = 1 + BEGIN + SELECT 1; + END +ELSE + BEGIN + SELECT 2; + END; + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // THROW following a block + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestThrowAfterBeginEndBlockGetsSeparatingSemicolon() + { + const string input = +@"DECLARE @x INT; +IF @x IS NULL BEGIN SELECT 1; END +;THROW 50001, 'e', 1"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT; + +IF @x IS NULL + BEGIN + SELECT 1; + END; + +THROW 50001, 'e', 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestThrowAfterWhileBlockGetsSeparatingSemicolon() + { + const string input = +@"DECLARE @x INT = 0; +WHILE @x < 1 BEGIN SET @x = @x + 1; END +THROW 50001, 'e', 1"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @x AS INT = 0; + +WHILE @x < 1 + BEGIN + SET @x = @x + 1; + END; + +THROW 50001, 'e', 1;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Cases that must NOT get an extra semicolon + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterTerminatedStatementHasNoDoubleSemicolon() + { + // The preceding SELECT already ends with a semicolon, so no separating semicolon is added. + const string input = +@"SELECT 1 +;WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +SELECT 1; + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestThrowAfterTerminatedStatementHasNoDoubleSemicolon() + { + // The preceding SELECT already ends with a semicolon, so no separating semicolon is + // added before the THROW. + const string input = +@"SELECT 1 +;THROW 50001, 'e', 1"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +SELECT 1; + +THROW 50001, 'e', 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAsFirstStatementHasNoLeadingSemicolon() + { + const string input = "WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Nested statement list (inside a procedure body) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterBlockInsideProcedureBodyGetsSeparatingSemicolon() + { + // The input intentionally omits the semicolon before WITH. ScriptDom's parser is lenient + // and accepts this, and the block statement's AST does not carry a terminator, so the + // generator is responsible for injecting the semicolon SQL Server requires. (A leading + // semicolon in the input would be discarded during parsing, so its presence or absence in + // the input does not affect the generated output.) + const string input = +@"CREATE PROCEDURE p @x INT AS BEGIN +IF @x IS NULL BEGIN SELECT 1; END +WITH cte AS (SELECT 1 AS c) SELECT * FROM cte +END"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +CREATE PROCEDURE p +@x INT +AS +BEGIN + IF @x IS NULL + BEGIN + SELECT 1; + END; + WITH cte + AS (SELECT 1 AS c) + SELECT * + FROM cte; +END"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Original reported repro: THROW inside a BEGIN...END block, followed by a CTE after the + // block. Without the injected separating semicolon, SQL Server rejects the generated script + // with error 319 ("Incorrect syntax near the keyword 'WITH'"). + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOriginalReproThrowInBlockFollowedByCteGetsSeparatingSemicolon() + { + const string input = +@"declare @ClientID varchar(100) = '' +IF @ClientID IS NULL +BEGIN +;THROW 50001, 'Client with PolicyID ''0001'' not found.', 1; +END +;WITH cte +AS (SELECT 1 AS Column1) +select * from cte"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +DECLARE @ClientID AS VARCHAR (100) = ''; + +IF @ClientID IS NULL + BEGIN + THROW 50001, 'Client with PolicyID ''0001'' not found.', 1; + END; + +WITH cte +AS (SELECT 1 AS Column1) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterTerminatedStatementWithTrailingCommentHasNoDoubleSemicolon() + { + // With PreserveComments on, the previous statement's terminating semicolon is followed + // by a trailing single-line comment. The separator scan must look past the comment and + // detect the semicolon, so no redundant semicolon is written into the comment text. + const string input = +@"SELECT 1; -- keep me +WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions { PreserveComments = true }; + const string expected = +@"SELECT 1; -- keep me + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterTerminatedStatementWithTrailingBlockCommentHasNoDoubleSemicolon() + { + // Same as the single-line case but with a trailing multi-line comment, exercising the + // MultilineComment branch of the separator scan. + const string input = +@"SELECT 1; /* keep me */ +WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions { PreserveComments = true }; + const string expected = +@"SELECT 1; /* keep me */ + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterBlockWithTrailingCommentGetsSeparatingSemicolon() + { + // A block ends with END (no terminator) and carries a trailing comment. The separator + // scan must look past the comment, find END (not a semicolon), and inject the required + // semicolon so the following CTE is valid, without corrupting the comment. + const string input = +@"DECLARE @x INT; +IF @x IS NULL BEGIN SELECT 1; END -- trailing note +WITH cte AS (SELECT 1 AS c) SELECT * FROM cte"; + var options = new SqlScriptGeneratorOptions { PreserveComments = true }; + const string expected = +@"DECLARE @x AS INT; + +IF @x IS NULL + BEGIN + SELECT 1; + END; -- trailing note + +WITH cte +AS (SELECT 1 AS c) +SELECT * +FROM cte;"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/release-notes/180/180.78.1.md b/release-notes/180/180.78.1.md new file mode 100644 index 00000000..f30a2d4b --- /dev/null +++ b/release-notes/180/180.78.1.md @@ -0,0 +1,31 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.78.1 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* None + +#### .NET Framework +#### .NET Core + +### New Features +* Adds MultilineInValuesList formatter option for IN (values) predicates. +* Adds ClauseBodyAlignment script generation option (Aligned or Indented). +* Adds MultilineProcedureParametersList formatter option for procedure and function parameters. +* Adds MultilineInsertTargetsList formatter option for INSERT and MERGE targets. + +### Fixed +* Injects a separating semicolon before CTE WITH and before THROW after block statements. + +### Changes +* None + +### Known Issues +* None From b583737682dbb1682b97d0ac5a5261dc94279b8d Mon Sep 17 00:00:00 2001 From: allancascante Date: Fri, 28 Aug 2026 09:32:36 -0600 Subject: [PATCH 38/45] Sync Repos: Release 180.102.0 (#230) * Fix INSERT VALUES alignment * Add configurable batch newline options * Fix CREATE DATABASE COLLATE option ordering * Add multiline WITH and OPTION formatting * Add Fabric DW GROUP BY ALL and ORDER BY ALL support * Fix SPARSE before MASKED column parsing (#216) * Add block statement terminator option * Add trailing GO preservation option * Add built-in function casing option * Add multiline query clause formatting options * Add configurable leading comma spacing * Fix nested function formatting with parameter comments * Adding release notes for 180.102.0 --------- Co-authored-by: Allan Cascante --- SqlScriptDom/Parser/TSql/Ast.xml | 3 + SqlScriptDom/Parser/TSql/OptionsHelper.cs | 20 + SqlScriptDom/Parser/TSql/TSql100.g | 4 + SqlScriptDom/Parser/TSql/TSql110.g | 8 + SqlScriptDom/Parser/TSql/TSql120.g | 11 + SqlScriptDom/Parser/TSql/TSql130.g | 16 + SqlScriptDom/Parser/TSql/TSql140.g | 16 + SqlScriptDom/Parser/TSql/TSql150.g | 16 + SqlScriptDom/Parser/TSql/TSql160.g | 16 + SqlScriptDom/Parser/TSql/TSql170.g | 16 + SqlScriptDom/Parser/TSql/TSql180.g | 16 + SqlScriptDom/Parser/TSql/TSql80.g | 6 +- SqlScriptDom/Parser/TSql/TSql90.g | 4 + SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 91 +- .../SqlServer/BuiltInFunctionCasing.cs | 42 + .../ScriptGeneratorSupporter.cs | 32 + .../SqlScriptGeneratorOptions.LeadingComma.cs | 26 - ...ratorVisitor.AiAnalyzeSentimentFunction.cs | 5 +- ...riptGeneratorVisitor.AiClassifyFunction.cs | 5 +- ...criptGeneratorVisitor.AiExtractFunction.cs | 5 +- ...ptGeneratorVisitor.AiFixGrammarFunction.cs | 5 +- ...torVisitor.AiGenerateEmbeddingsFunction.cs | 5 +- ...ratorVisitor.AiGenerateResponseFunction.cs | 5 +- ...iptGeneratorVisitor.AiSummarizeFunction.cs | 5 +- ...iptGeneratorVisitor.AiTranslateFunction.cs | 5 +- ...iptGeneratorVisitor.AlterIndexStatement.cs | 4 +- ...ratorVisitor.AlterTableRebuildStatement.cs | 3 +- ...lScriptGeneratorVisitor.BackupStatement.cs | 3 +- ...eneratorVisitor.BooleanBinaryExpression.cs | 21 +- ...tGeneratorVisitor.BuiltInFunctionCasing.cs | 80 ++ .../SqlScriptGeneratorVisitor.CastCall.cs | 5 +- ...riptGeneratorVisitor.CoalesceExpression.cs | 5 +- .../SqlScriptGeneratorVisitor.Comments.cs | 12 + ...SqlScriptGeneratorVisitor.CommonPhrases.cs | 41 +- ...lScriptGeneratorVisitor.ComputeFunction.cs | 9 +- .../SqlScriptGeneratorVisitor.ConvertCall.cs | 5 +- ...ptGeneratorVisitor.CreateIndexStatement.cs | 3 +- ...isitor.CreateSelectiveXmlIndexStatement.cs | 3 +- .../SqlScriptGeneratorVisitor.FunctionCall.cs | 286 +++- ...SqlScriptGeneratorVisitor.GroupByClause.cs | 21 +- .../SqlScriptGeneratorVisitor.HavingClause.cs | 5 +- .../SqlScriptGeneratorVisitor.IifCall.cs | 5 +- ...lScriptGeneratorVisitor.InsertStatement.cs | 19 +- ...eratorVisitor.InvokeExternalApiFunction.cs | 5 +- ...ptGeneratorVisitor.ListGenerationOption.cs | 20 + ...ScriptGeneratorVisitor.NullIfExpression.cs | 5 +- ...qlScriptGeneratorVisitor.OptimizerHints.cs | 7 +- ...SqlScriptGeneratorVisitor.OrderByClause.cs | 32 +- .../SqlScriptGeneratorVisitor.OverClause.cs | 9 +- .../SqlScriptGeneratorVisitor.ParseCall.cs | 5 +- ...ScriptGeneratorVisitor.RestoreStatement.cs | 3 +- .../SqlScriptGeneratorVisitor.TSEqualCall.cs | 5 +- .../SqlScriptGeneratorVisitor.TSqlBatch.cs | 6 +- .../SqlScriptGeneratorVisitor.TSqlScript.cs | 24 +- .../SqlScriptGeneratorVisitor.TableHints.cs | 3 +- .../SqlScriptGeneratorVisitor.TryCastCall.cs | 5 +- ...qlScriptGeneratorVisitor.TryConvertCall.cs | 5 +- .../SqlScriptGeneratorVisitor.TryParseCall.cs | 5 +- .../SqlScriptGeneratorVisitor.Utils.cs | 48 +- ...riptGeneratorVisitor.ValuesInsertSource.cs | 67 +- .../SqlScriptGeneratorVisitor.WhereClause.cs | 7 +- ...ScriptGeneratorVisitor.WindowDefinition.cs | 9 +- ...lScriptGeneratorVisitor.WithOptionsList.cs | 92 ++ .../Settings/SqlScriptGeneratorOptions.xml | 50 +- .../Baselines100/InsertStatementTests100.sql | 8 +- .../Baselines130/CreateTableTests130.sql | 7 + .../Baselines170/AiGenerateChunksTests170.sql | 6 +- ...teDatabaseCollateBeforeEditionTests120.sql | 12 + .../BaselinesCommon/SelectStatementTests.sql | 4 + ...abaseCollateBeforeEditionTestsFabricDW.sql | 12 + .../ModernGroupByAllTestsFabricDW.sql | 71 + .../OrderByAllTestsFabricDW.sql | 95 ++ Test/SqlDom/Only130SyntaxTests.cs | 2 +- Test/SqlDom/Only180SyntaxTests.cs | 1 + Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 4 + Test/SqlDom/ParserErrorsTests.cs | 88 ++ .../BlockStatementTerminatorTests.cs | 479 +++++++ .../BuiltInFunctionCasingTests.cs | 780 +++++++++++ .../ClauseBodyAlignmentTests.cs | 107 ++ .../ScriptGenerator/CommaPlacementTests.cs | 606 ++++++++ .../FunctionCallFormattingTests.cs | 467 +++++++ .../GroupByElementsListFormattingTests.cs | 225 +++ .../HavingPredicatesListFormattingTests.cs | 180 +++ .../InValuesListFormattingTests.cs | 20 + .../InsertTargetsListFormattingTests.cs | 54 +- .../InsertValuesAlignmentTests.cs | 284 ++++ .../NumNewlinesAfterBatchStatementTests.cs | 154 ++ .../NumNewlinesAfterBatchesTests.cs | 180 +++ .../NumNewlinesAfterStatementTests.cs | 156 +++ .../OrderByElementsListFormattingTests.cs | 239 ++++ .../PartitionByElementsListFormattingTests.cs | 227 +++ .../ScriptGeneratorTestHelper.cs | 103 +- .../ScriptGenerator/ScriptGeneratorTests.cs | 1236 ++++------------- .../WithOptionsListFormattingTests.cs | 647 +++++++++ .../SparseMaskedColumnOrderRegressionTests.cs | 139 ++ ...teDatabaseCollateBeforeEditionTests120.sql | 6 + ...abaseCollateBeforeEditionTestsFabricDW.sql | 6 + .../TestScripts/CreateTableTests130.sql | 9 + .../ModernGroupByAllTestsFabricDW.sql | 71 + .../TestScripts/OrderByAllTestsFabricDW.sql | 95 ++ .../TestScripts/SelectStatementTests.sql | 2 + release-notes/180/180.102.0.md | 36 + 102 files changed, 7004 insertions(+), 1139 deletions(-) create mode 100644 SqlScriptDom/ScriptDom/SqlServer/BuiltInFunctionCasing.cs delete mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionCasing.cs create mode 100644 SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WithOptionsList.cs create mode 100644 Test/SqlDom/Baselines180/CreateDatabaseCollateBeforeEditionTests120.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/ModernGroupByAllTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/OrderByAllTestsFabricDW.sql create mode 100644 Test/SqlDom/ScriptGenerator/BlockStatementTerminatorTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/BuiltInFunctionCasingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/FunctionCallFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/GroupByElementsListFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/HavingPredicatesListFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/InsertValuesAlignmentTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchStatementTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchesTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/NumNewlinesAfterStatementTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/OrderByElementsListFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/PartitionByElementsListFormattingTests.cs create mode 100644 Test/SqlDom/ScriptGenerator/WithOptionsListFormattingTests.cs create mode 100644 Test/SqlDom/SparseMaskedColumnOrderRegressionTests.cs create mode 100644 Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTests120.sql create mode 100644 Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/ModernGroupByAllTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/OrderByAllTestsFabricDW.sql create mode 100644 release-notes/180/180.102.0.md diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index ebf274a3..e9c2d9eb 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -3550,6 +3550,8 @@ + + @@ -4046,6 +4048,7 @@ + diff --git a/SqlScriptDom/Parser/TSql/OptionsHelper.cs b/SqlScriptDom/Parser/TSql/OptionsHelper.cs index a14a9e5b..d44e31c8 100644 --- a/SqlScriptDom/Parser/TSql/OptionsHelper.cs +++ b/SqlScriptDom/Parser/TSql/OptionsHelper.cs @@ -67,6 +67,11 @@ public OptionType Value { get { return _optionValue; } } + + public string Identifier + { + get { return _identifier; } + } } private Dictionary _optionToOptionInfo = new Dictionary(); @@ -208,6 +213,21 @@ internal bool TryGenerateSourceForOption(ScriptWriter writer, OptionType option) return false; } + // Exposes the literal source text of identifier-backed options so callers can apply their own + // casing; returns false for token-backed options, whose text comes from the token table. + internal bool TryGetOptionIdentifier(OptionType option, out string identifier) + { + OptionInfo optionInfo; + if (_optionToOptionInfo.TryGetValue(option, out optionInfo) && optionInfo.Identifier != null) + { + identifier = optionInfo.Identifier; + return true; + } + + identifier = null; + return false; + } + internal void GenerateCommaSeparatedFlagOptions(ScriptWriter writer, OptionType options) { bool first = true; diff --git a/SqlScriptDom/Parser/TSql/TSql100.g b/SqlScriptDom/Parser/TSql/TSql100.g index c17c2f9a..7b485ae6 100644 --- a/SqlScriptDom/Parser/TSql/TSql100.g +++ b/SqlScriptDom/Parser/TSql/TSql100.g @@ -133,13 +133,17 @@ script returns [TSqlScript vResult = this.FragmentFactory.CreateFragment()] +orderByClause [bool allowAll] returns [OrderByClause vResult = this.FragmentFactory.CreateFragment()] { ExpressionWithSortOrder vExpressionWithSortOrder; + SortOrder vAllSortOrder; } : tOrder:Order By { UpdateTokenInfo(vResult,tOrder); } - vExpressionWithSortOrder=expressionWithSortOrder - { - AddAndUpdateTokenInfo(vResult, vResult.OrderByElements, vExpressionWithSortOrder); - } ( - Comma vExpressionWithSortOrder=expressionWithSortOrder + tAll:All + { + // ORDER BY ALL (Fabric DW) is only allowed at the query / subquery level. + // It is not permitted inside OVER(), WINDOW definitions or WITHIN GROUP. + if (!allowAll) + ThrowIncorrectSyntaxErrorException(tAll); + + vResult.All = true; + UpdateTokenInfo(vResult, tAll); + } + (vAllSortOrder = orderByOption[vResult] + { + vResult.AllSortOrder = vAllSortOrder; + } + )? + | + vExpressionWithSortOrder=expressionWithSortOrder { AddAndUpdateTokenInfo(vResult, vResult.OrderByElements, vExpressionWithSortOrder); } - )* + ( + Comma vExpressionWithSortOrder=expressionWithSortOrder + { + AddAndUpdateTokenInfo(vResult, vResult.OrderByElements, vExpressionWithSortOrder); + } + )* + ) ; expressionWithSortOrder returns [ExpressionWithSortOrder vResult = this.FragmentFactory.CreateFragment()] @@ -29103,6 +29149,11 @@ regularColumnBody [IndexAffectingStatement statementType, ColumnDefinition vPare vParent.StorageOptions = vStorageOptions; } )? + // MASKED WITH may follow the storage options (documented SPARSE-before-MASKED order) + ( + {NextTokenMatches(CodeGenerationSupporter.Masked)}? + maskedClause[vParent] + )? )? ( {NextTokenMatches(CodeGenerationSupporter.Hidden)}? @@ -32001,7 +32052,7 @@ windowDefinition returns [WindowDefinition vResult = FragmentFactory.CreateFragm By expressionList[vResult, vResult.Partitions] )? ( - vOrderByClause=orderByClause + vOrderByClause=orderByClause[false] { vResult.OrderByClause = vOrderByClause; } @@ -32026,7 +32077,7 @@ overClause returns [OverClause vResult] } : vResult = overClauseBeginning ( - vOrderByClause=orderByClause + vOrderByClause=orderByClause[false] { vResult.OrderByClause = vOrderByClause; } @@ -32200,7 +32251,7 @@ withinGroupClause returns [WithinGroupClause vResult = FragmentFactory.CreateFra graphPathClause[vResult] ) | - vOrderByClause=orderByClause + vOrderByClause=orderByClause[false] { vResult.OrderByClause = vOrderByClause; UpdateTokenInfo(vResult,tLParen); diff --git a/SqlScriptDom/ScriptDom/SqlServer/BuiltInFunctionCasing.cs b/SqlScriptDom/ScriptDom/SqlServer/BuiltInFunctionCasing.cs new file mode 100644 index 00000000..f59463ef --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/BuiltInFunctionCasing.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.SqlServer.TransactSql.ScriptDom +{ + /// + /// Represents the possible ways of casing built-in / system function names during script + /// generation. Any value other than Preserve takes precedence over KeywordCasing for function + /// names; data type names, keywords, string literals, and variables are never affected. Casing + /// is applied to every unqualified, non-delimited function name, which is safe because T-SQL + /// resolves a one-part scalar function name as a built-in function and never as a user-defined + /// one (a scalar user-defined function must be called with at least a two-part name). + /// Schema-qualified and delimited function names, and method calls on a variable or column, are + /// always preserved. + /// + public enum BuiltInFunctionCasing + { + /// + /// Preserve the built-in function name exactly as it would be produced without this option + /// (backward-compatible: has no effect on the formatted output). + /// + Preserve, + + /// + /// All letters in upper case + /// + Uppercase, + + /// + /// All letters in lower case + /// + Lowercase, + + /// + /// First letter capitalized, remaining letters lower case + /// + PascalCase + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs index d766f43a..49ebfc4b 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/ScriptGeneratorSupporter.cs @@ -96,6 +96,38 @@ public static string GetCasedString(string str, IdentifierCasing casing) return str; } + /// + /// Retrieves a version of the specified built-in function name, in the built-in function + /// casing format specified. + /// + /// The built-in function name to get a specially cased version of + /// The built-in function casing method to use + /// A version of the string in the casing format specified in + [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] + public static string GetCasedString(string str, BuiltInFunctionCasing casing) + { + if (string.IsNullOrEmpty(str)) + { + return str; + } + + switch (casing) + { + case BuiltInFunctionCasing.Preserve: + return str; + case BuiltInFunctionCasing.Lowercase: + return str.ToLowerInvariant(); + case BuiltInFunctionCasing.Uppercase: + return str.ToUpperInvariant(); + case BuiltInFunctionCasing.PascalCase: + return GetPascalCase(str); + default: + Debug.Fail("Invalid BuiltInFunctionCasing value"); + break; + } + return str; + } + /// /// Retrieves a Pascal Cased version of the string /// diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs deleted file mode 100644 index 6d5c8c70..00000000 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorOptions.LeadingComma.cs +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -//------------------------------------------------------------------------------ - -using System; - -namespace Microsoft.SqlServer.TransactSql.ScriptDom -{ - public partial class SqlScriptGeneratorOptions - { - /// - /// The number of whitespace characters written after a leading comma when - /// is . - /// The total width reserved for a leading comma is one column for the comma itself - /// plus this many columns of trailing whitespace (so the default of 1 reserves 2 columns). - /// - /// - /// This is currently an internal knob so the leading-comma spacing is defined in a single - /// place rather than hard-coded at every call site. It can later be promoted to a public - /// script generation option. - /// - internal Int32 LeadingCommaSpaceCount { get; set; } = 1; - } -} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs index 181c775f..e5846571 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs @@ -16,7 +16,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AIAnalyzeSentimentFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AIAnalyzeSentiment); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AIAnalyzeSentiment)) + { + GenerateIdentifier(CodeGenerationSupporter.AIAnalyzeSentiment); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); GenerateSymbol(TSqlTokenType.RightParenthesis); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs index 9baf443b..d6997cba 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs @@ -18,7 +18,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AIClassifyFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AIClassify); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AIClassify)) + { + GenerateIdentifier(CodeGenerationSupporter.AIClassify); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); // input diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs index 0eb0fbb0..7ba23ad1 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs @@ -19,7 +19,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AIExtractFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AIExtract); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AIExtract)) + { + GenerateIdentifier(CodeGenerationSupporter.AIExtract); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); // input diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs index a5de5c1d..3d9f8b34 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs @@ -16,7 +16,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AIFixGrammarFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AIFixGrammar); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AIFixGrammar)) + { + GenerateIdentifier(CodeGenerationSupporter.AIFixGrammar); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); GenerateSymbol(TSqlTokenType.RightParenthesis); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs index 299a1c36..650b7b87 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateEmbeddingsFunction.cs @@ -18,7 +18,10 @@ public override void ExplicitVisit(AIGenerateEmbeddingsFunctionCall node) } // Emit function name without extra space before '(' - GenerateIdentifierWithoutCasing(CodeGenerationSupporter.AIGenerateEmbeddings); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AIGenerateEmbeddings)) + { + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.AIGenerateEmbeddings); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); // Emit input expression diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs index 393a9af3..b9affe86 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs @@ -18,7 +18,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AIGenerateResponseFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AIGenerateResponse); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AIGenerateResponse)) + { + GenerateIdentifier(CodeGenerationSupporter.AIGenerateResponse); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.PromptPart1); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs index fe1adafc..3d73ae5a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs @@ -17,7 +17,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AISummarizeFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AISummarize); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AISummarize)) + { + GenerateIdentifier(CodeGenerationSupporter.AISummarize); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); GenerateSymbol(TSqlTokenType.RightParenthesis); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs index 922751c6..10c56ed2 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs @@ -19,7 +19,10 @@ partial class SqlScriptGeneratorVisitor /// Expression node to generate public override void ExplicitVisit(AITranslateFunctionCall node) { - GenerateIdentifier(CodeGenerationSupporter.AITranslate); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.AITranslate)) + { + GenerateIdentifier(CodeGenerationSupporter.AITranslate); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); GenerateSymbol(TSqlTokenType.Comma); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterIndexStatement.cs index 515faa68..29c09d34 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterIndexStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterIndexStatement.cs @@ -82,7 +82,9 @@ public override void ExplicitVisit(AlterIndexStatement node) if (node.IndexOptions.Count > 0) { GenerateSpaceAndKeyword(TSqlTokenType.With); - GenerateParenthesisedCommaSeparatedList(node.IndexOptions); + // spaceBeforeSingleLineParenthesis: false preserves the pre-PR single-line output, + // which historically emits WITH(...) with no space before the parenthesis here. + GenerateWithOptionsList(node.IndexOptions, spaceBeforeSingleLineParenthesis: false); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableRebuildStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableRebuildStatement.cs index 2e1209cb..38d56478 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableRebuildStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableRebuildStatement.cs @@ -19,8 +19,7 @@ public override void ExplicitVisit(AlterTableRebuildStatement node) if (node.IndexOptions.Count > 0) { GenerateSpaceAndKeyword(TSqlTokenType.With); - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(node.IndexOptions); + GenerateWithOptionsList(node.IndexOptions, spaceBeforeSingleLineParenthesis: true); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BackupStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BackupStatement.cs index 925d4b90..406f3271 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BackupStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BackupStatement.cs @@ -32,8 +32,7 @@ protected void GenerateDeviceAndOption(BackupStatement node) { NewLineAndIndent(); GenerateKeyword(TSqlTokenType.With); - GenerateSpace(); - GenerateCommaSeparatedList(node.Options); + GenerateWithOptionsListNonParenthesized(node.Options); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BooleanBinaryExpression.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BooleanBinaryExpression.cs index 85e94062..f3001f14 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BooleanBinaryExpression.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BooleanBinaryExpression.cs @@ -10,6 +10,8 @@ namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator { partial class SqlScriptGeneratorVisitor { + private Boolean? _multilinePredicates; + public override void ExplicitVisit(BooleanBinaryExpression node) { AlignmentPoint start = new AlignmentPoint(); @@ -35,12 +37,27 @@ private Boolean RightPredicateOnNewline(BooleanBinaryExpression node) // * A Newline was inserted before the WHERE clause, AND // * The Binary Expression is an AND or an OR expression. Boolean insertNewline = - _options.MultilineWherePredicatesList && - _options.NewLineBeforeWhereClause && + (_multilinePredicates ?? + (_options.MultilineWherePredicatesList && _options.NewLineBeforeWhereClause)) && (node.BinaryExpressionType == BooleanBinaryExpressionType.And || node.BinaryExpressionType == BooleanBinaryExpressionType.Or); return insertNewline; } + private void GeneratePredicate(TSqlFragment predicate, Boolean multiline) + { + Boolean? previousMultilinePredicates = _multilinePredicates; + _multilinePredicates = multiline; + + try + { + GenerateFragmentIfNotNull(predicate); + } + finally + { + _multilinePredicates = previousMultilinePredicates; + } + } + } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionCasing.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionCasing.cs new file mode 100644 index 00000000..c5da8eea --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.BuiltInFunctionCasing.cs @@ -0,0 +1,80 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + // Emits the name of a built-in function whose name is represented in the AST by a keyword + // token (for example CONVERT, COALESCE, NULLIF, LEFT, RIGHT). When BuiltInFunctionCasing is + // Preserve this is a no-op and returns false so the caller emits its default representation + // (backward-compatible, so the name keeps following KeywordCasing). Otherwise the name is + // emitted with the configured casing applied, taking precedence over KeywordCasing, and + // true is returned. + protected bool TryGenerateBuiltInFunctionName(TSqlTokenType keywordId) + { + if (_options.BuiltInFunctionCasing == BuiltInFunctionCasing.Preserve) + { + return false; + } + + string baseText = ScriptGeneratorSupporter.GetLowerCase(keywordId); + GenerateToken(TSqlTokenType.Identifier, ScriptGeneratorSupporter.GetCasedString(baseText, _options.BuiltInFunctionCasing)); + return true; + } + + // Emits the name of a built-in function whose name is represented in the AST by a literal + // string (for example CAST, TRY_CAST, IIF). Behaves like the keyword overload above. + protected bool TryGenerateBuiltInFunctionName(string name) + { + if (_options.BuiltInFunctionCasing == BuiltInFunctionCasing.Preserve) + { + return false; + } + + GenerateToken(TSqlTokenType.Identifier, ScriptGeneratorSupporter.GetCasedString(name, _options.BuiltInFunctionCasing)); + return true; + } + + // Emits the name of a generic FunctionCall when BuiltInFunctionCasing is not Preserve. + // Returns false (leaving the caller to emit the name unchanged) for qualified calls, which + // also covers CLR/XML/spatial method invocations, and for delimited names. Every remaining + // name is re-cased without consulting a catalog of built-ins, because T-SQL resolves a + // one-part scalar function name as a built-in function and never as a user-defined one - a + // scalar UDF must be called with at least a two-part name - so a name reaching this point is + // either a built-in, whose name is matched case-insensitively under every collation, or + // already-invalid T-SQL. Table-valued functions, which do resolve one-part names against the + // default schema, are SchemaObjectFunctionTableReference and never reach this path. + private bool TryGenerateBuiltInFunctionName(FunctionCall node) + { + if (_options.BuiltInFunctionCasing == BuiltInFunctionCasing.Preserve) + { + return false; + } + + if (node.CallTarget != null) + { + return false; + } + + Identifier name = node.FunctionName; + if (name == null || name.Value == null || name.QuoteType != QuoteType.NotQuoted) + { + return false; + } + + // The replaced path emitted the name through GenerateFragmentIfNotNull, which is what + // normally runs the comment hooks and advances the last-processed token index. Emitting a + // raw token instead means they have to be driven explicitly, or comments adjacent to the + // function name are relocated into the argument list (or dropped for zero-argument calls). + HandleCommentsBeforeFragment(name); + GenerateToken(TSqlTokenType.Identifier, ScriptGeneratorSupporter.GetCasedString(name.Value, _options.BuiltInFunctionCasing)); + HandleCommentsAfterFragment(name); + return true; + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CastCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CastCall.cs index 5772f2a6..552400f6 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CastCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CastCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(CastCall node) { - GenerateIdentifier(CodeGenerationSupporter.Cast); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.Cast)) + { + GenerateIdentifier(CodeGenerationSupporter.Cast); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Parameter); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CoalesceExpression.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CoalesceExpression.cs index 995e2f9f..38f0a576 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CoalesceExpression.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CoalesceExpression.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(CoalesceExpression node) { - GenerateKeyword(TSqlTokenType.Coalesce); + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.Coalesce)) + { + GenerateKeyword(TSqlTokenType.Coalesce); + } GenerateSpace(); GenerateParenthesisedCommaSeparatedList(node.Expressions); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs index 6fe8d85b..ef0e005a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs @@ -427,6 +427,18 @@ internal void FlushDeferredTrailingSingleLineComments() _deferredTrailingSingleLineComments.Clear(); } + /// + /// Indicates that a trailing -- comment is waiting for the next newline. This allows + /// callers that are about to emit closing punctuation, such as a function's right + /// parenthesis, to start a new line first so the punctuation is not consumed by the comment. + /// + /// + /// For TRANSLATE(city, 'a', 'b' -- replacement characters, the closing parenthesis + /// must be emitted on the following line; otherwise it becomes part of the comment. + /// + protected bool HasDeferredTrailingSingleLineComments => + _deferredTrailingSingleLineComments.Count > 0; + /// /// Updates tracking after generating a fragment. /// diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs index 5004cc2c..16bbaec0 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs @@ -361,17 +361,29 @@ protected Boolean GenerateClauseBodyStart(Boolean newline, AlignmentPoint ap) return false; } + // Marks the river that lines up an INSERT statement's VALUES row constructors under its + // column list (e.g. "INSERT INTO t (a, b)" / "VALUES (1, 2)"). Only skipped for the + // Indented + !AlignClauseBodies combination, where ValuesInsertSource instead puts the row + // list on its own indented line (see ShouldMoveInsertValuesToNewLine); every other option + // combination keeps the existing river behavior so current baselines are unaffected. protected void MarkInsertColumnsAlignmentPointWhenNecessary(AlignmentPoint ap) { #if !PIMODLANGUAGE Debug.Assert(ap != null, "Alignment point should not be null"); #endif - if (ap != null) + if (ap != null && !ShouldMoveInsertValuesToNewLine()) { Mark(ap); } } + // True when an INSERT statement's VALUES row constructors should move to their own + // indented line instead of being padded (or single-spaced) onto the "VALUES" line. + protected Boolean ShouldMoveInsertValuesToNewLine() + { + return _options.ClauseBodyAlignment == ClauseBodyAlignment.Indented && !_options.AlignClauseBodies; + } + protected void GenerateSeparatorForOrderBy() { GenerateNewLineOrSpace(_options.NewLineBeforeOrderByClause); @@ -575,11 +587,34 @@ internal abstract HashSet StatementsThatCannotHaveSemiColon // part of CREATE VIEW statement, and we don't want to generate semicolon for the included statements protected Boolean _generateSemiColon = true; + // Blocks that StatementsThatCannotHaveSemiColon suppresses by default but that + // TerminateBlockStatements opts back in. TryCatchStatement covers END CATCH; END TRY is + // internal to the block and never reaches this check. + private static readonly HashSet _blockStatementsTerminatedByOption = new HashSet + { + typeof(BeginEndBlockStatement), + typeof(TryCatchStatement), + }; + + // Membership is tested on the exact runtime type, so a derived block such as + // BeginEndAtomicBlockStatement is unaffected by either set. + private Boolean CanHaveSemiColon(TSqlStatement statement) + { + Type statementType = statement.GetType(); + + if (StatementsThatCannotHaveSemiColon.Contains(statementType) == false) + { + return true; + } + + return _options.TerminateBlockStatements && _blockStatementsTerminatedByOption.Contains(statementType); + } + protected void GenerateSemiColonWhenNecessary(TSqlStatement node) { if (node != null && _generateSemiColon && - StatementsThatCannotHaveSemiColon.Contains(node.GetType()) == false) + CanHaveSemiColon(node)) { GenerateSymbol(TSqlTokenType.Semicolon); } @@ -635,7 +670,7 @@ protected void GenerateStatementWithSemiColon(TSqlStatement statement) // Only suppress for fragments at the statement boundary (LastTokenIndex). bool previousSuppressState = _suppressTrailingComments; int previousSuppressIndex = _suppressTrailingCommentsAfterIndex; - if (_options.PreserveComments && _generateSemiColon && !StatementsThatCannotHaveSemiColon.Contains(statement.GetType())) + if (_options.PreserveComments && _generateSemiColon && CanHaveSemiColon(statement)) { _suppressTrailingComments = true; _suppressTrailingCommentsAfterIndex = statement.LastTokenIndex; diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ComputeFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ComputeFunction.cs index 2fa7b788..e64e8db1 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ComputeFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ComputeFunction.cs @@ -10,7 +10,14 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(ComputeFunction node) { - ComputeFunctionTypeHelper.Instance.GenerateSourceForOption(_writer, node.ComputeFunctionType); + // The aggregate name here is the same built-in as in a SELECT list, so it follows + // BuiltInFunctionCasing rather than being emitted as a fixed-case literal. + if (!ComputeFunctionTypeHelper.Instance.TryGetOptionIdentifier(node.ComputeFunctionType, out string name) || + !TryGenerateBuiltInFunctionName(name)) + { + ComputeFunctionTypeHelper.Instance.GenerateSourceForOption(_writer, node.ComputeFunctionType); + } + GenerateParenthesisedFragmentIfNotNull(node.Expression); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ConvertCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ConvertCall.cs index eb63a093..a3462ee9 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ConvertCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ConvertCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(ConvertCall node) { - GenerateKeyword(TSqlTokenType.Convert); + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.Convert)) + { + GenerateKeyword(TSqlTokenType.Convert); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.DataType); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateIndexStatement.cs index 6ff2623f..c17597cb 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateIndexStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateIndexStatement.cs @@ -69,8 +69,7 @@ protected virtual void GenerateIndexOptions(IList options) { GenerateSpaceAndKeyword(TSqlTokenType.With); - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(options); + GenerateWithOptionsList(options, spaceBeforeSingleLineParenthesis: true); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSelectiveXmlIndexStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSelectiveXmlIndexStatement.cs index 77b910b1..7b6bbbae 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSelectiveXmlIndexStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CreateSelectiveXmlIndexStatement.cs @@ -66,9 +66,8 @@ public override void ExplicitVisit(CreateSelectiveXmlIndexStatement node) { NewLine(); GenerateKeyword(TSqlTokenType.With); - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(node.IndexOptions); + GenerateWithOptionsList(node.IndexOptions, spaceBeforeSingleLineParenthesis: true); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs index 37fe8287..baea48c4 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FunctionCall.cs @@ -10,28 +10,91 @@ namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator { partial class SqlScriptGeneratorVisitor { + private int _multilineFunctionCallDepth; + public override void ExplicitVisit(LeftFunctionCall node) { - GenerateKeyword(TSqlTokenType.Left); - GenerateParenthesisedCommaSeparatedList(node.Parameters, true); - GenerateSpaceAndCollation(node.Collation); + if (!ShouldFormatFunctionCallParameterList(node.Parameters)) + { + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.Left)) + { + GenerateKeyword(TSqlTokenType.Left); + } + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateCommaSeparatedList(node.Parameters); + GenerateFunctionCallRightParenthesis(); + GenerateSpaceAndCollation(node.Collation); + return; + } + + AlignmentPoint functionCallStart = PushFunctionCallAlignmentPoint(); + try + { + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.Left)) + { + GenerateKeyword(TSqlTokenType.Left); + } + GenerateMultilineFunctionCallParameterList(node.Parameters); + GenerateSpaceAndCollation(node.Collation); + } + finally + { + PopFunctionCallAlignmentPoint(functionCallStart); + } } public override void ExplicitVisit(RightFunctionCall node) { - GenerateKeyword(TSqlTokenType.Right); - GenerateParenthesisedCommaSeparatedList(node.Parameters, true); - GenerateSpaceAndCollation(node.Collation); + if (!ShouldFormatFunctionCallParameterList(node.Parameters)) + { + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.Right)) + { + GenerateKeyword(TSqlTokenType.Right); + } + GenerateSymbol(TSqlTokenType.LeftParenthesis); + GenerateCommaSeparatedList(node.Parameters); + GenerateFunctionCallRightParenthesis(); + GenerateSpaceAndCollation(node.Collation); + return; + } + + AlignmentPoint functionCallStart = PushFunctionCallAlignmentPoint(); + try + { + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.Right)) + { + GenerateKeyword(TSqlTokenType.Right); + } + GenerateMultilineFunctionCallParameterList(node.Parameters); + GenerateSpaceAndCollation(node.Collation); + } + finally + { + PopFunctionCallAlignmentPoint(functionCallStart); + } } public override void ExplicitVisit(FunctionCall node) { + if (ShouldFormatFunctionCall(node)) + { + GenerateMultilineFunctionCall(node); + return; + } + GenerateFragmentIfNotNull(node.CallTarget); + // Recognized, unqualified built-in function names follow the BuiltInFunctionCasing + // option. When that option is Preserve (the default) or the name is a user-defined + // function, fall back to emitting the name with its original casing. + // // Function names are not affected by the IdentifierCasing / IdentifierBracketing options - // (their casing is governed by a separate option), so emit the function name with + // (their casing is governed by BuiltInFunctionCasing), so emit the function name with // identifier formatting suppressed. This has no effect under default options. - GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.FunctionName)); + if (!TryGenerateBuiltInFunctionName(node)) + { + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.FunctionName)); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); @@ -50,11 +113,18 @@ public override void ExplicitVisit(FunctionCall node) GenerateSpace(); } GenerateFragmentIfNotNull(node.Parameters[0]); - GenerateSpace(); + if (HasDeferredTrailingSingleLineComments) + { + NewLine(); + } + else + { + GenerateSpace(); + } GenerateKeyword(TSqlTokenType.From); GenerateSpace(); GenerateFragmentIfNotNull(node.Parameters[1]); - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonObject) { @@ -65,7 +135,7 @@ public override void ExplicitVisit(FunctionCall node) if (node.JsonParameters?.Count > 0 && node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them GenerateSpace(); GenerateReturnType(node?.ReturnType); - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonObjectAgg) { @@ -76,7 +146,7 @@ public override void ExplicitVisit(FunctionCall node) if (node.JsonParameters?.Count > 0 && node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them GenerateSpace(); GenerateReturnType(node?.ReturnType); - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); // Generate OVER clause for windowed json_objectagg GenerateSpaceAndFragmentIfNotNull(node.OverClause); } @@ -89,7 +159,7 @@ public override void ExplicitVisit(FunctionCall node) if (node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them GenerateSpace(); GenerateReturnType(node?.ReturnType); - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonArrayAgg) { @@ -102,7 +172,7 @@ public override void ExplicitVisit(FunctionCall node) if (node.ReturnType?.Count > 0) //If there are values and null on null or absent on null present then generate space in between them GenerateSpace(); GenerateReturnType(node?.ReturnType); - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); // Generate OVER clause for windowed json_arrayagg GenerateSpaceAndFragmentIfNotNull(node.OverClause); } @@ -121,7 +191,7 @@ public override void ExplicitVisit(FunctionCall node) GenerateIdentifier(CodeGenerationSupporter.Wrapper); } - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); } else if (node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture) == CodeGenerationSupporter.JsonValue) { @@ -131,7 +201,7 @@ public override void ExplicitVisit(FunctionCall node) GenerateSpace(); GenerateReturnType(node?.ReturnType); } - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); } else { @@ -140,7 +210,7 @@ public override void ExplicitVisit(FunctionCall node) GenerateSpace(); GenerateCommaSeparatedList(node.Parameters); - GenerateSymbol(TSqlTokenType.RightParenthesis); + GenerateFunctionCallRightParenthesis(); if (node.IgnoreRespectNulls?.Count > 0) { @@ -158,6 +228,188 @@ public override void ExplicitVisit(FunctionCall node) GenerateSpaceAndCollation(node.Collation); } + /// + /// Generates an ordinary function call using multiline parameter formatting while preserving + /// its optional null-handling, grouping, windowing, and collation clauses. + /// + private void GenerateMultilineFunctionCall(FunctionCall node) + { + AlignmentPoint functionCallStart = PushFunctionCallAlignmentPoint(); + try + { + GenerateFragmentIfNotNull(node.CallTarget); + if (!TryGenerateBuiltInFunctionName(node)) + { + GenerateWithoutIdentifierFormatting(() => GenerateFragmentIfNotNull(node.FunctionName)); + } + + GenerateMultilineFunctionCallParameterList(node.Parameters); + + if (node.IgnoreRespectNulls?.Count > 0) + { + GenerateSpace(); + GenerateWithoutIdentifierFormatting(() => GenerateSpaceSeparatedList(node.IgnoreRespectNulls)); + } + + GenerateSpaceAndFragmentIfNotNull(node.WithinGroupClause); + GenerateSpaceAndFragmentIfNotNull(node.OverClause); + GenerateSpaceAndCollation(node.Collation); + } + finally + { + PopFunctionCallAlignmentPoint(functionCallStart); + } + } + + /// + /// Determines whether to render a function's parameters with the generic multiline layout. + /// The option must be enabled, the function must use an ordinary comma-separated parameter + /// list without a DISTINCT or ALL qualifier, and the function must either be inside an + /// already-formatted nested call tree or contain another function in its parameter subtree. + /// + private bool ShouldFormatFunctionCall(FunctionCall node) + { + return node.UniqueRowFilter == UniqueRowFilter.NotSpecified + && !UsesSpecialFunctionCallSyntax(node) + && ShouldFormatFunctionCallParameterList(node.Parameters); + } + + /// + /// Determines whether a function contains nonstandard argument grammar, such as TRIM's FROM + /// syntax or JSON-specific key/value, null-handling, ordering, wrapper, and RETURNING clauses. + /// Such functions must bypass generic comma-separated multiline parameter rendering to + /// preserve valid SQL. + /// + private static bool UsesSpecialFunctionCallSyntax(FunctionCall node) + { + string functionName = node.FunctionName.Value.ToUpper(CultureInfo.InvariantCulture); + return (functionName == CodeGenerationSupporter.Trim && node.Parameters.Count == 2) + || functionName == CodeGenerationSupporter.JsonObject + || functionName == CodeGenerationSupporter.JsonObjectAgg + || functionName == CodeGenerationSupporter.JsonArray + || functionName == CodeGenerationSupporter.JsonArrayAgg + || functionName == CodeGenerationSupporter.JsonQuery + || functionName == CodeGenerationSupporter.JsonValue; + } + + /// + /// Determines whether a parameter list belongs to the nested function tree that should use + /// multiline formatting. The option must be enabled, and the list must either be inside an + /// already-formatted function call or contain another function in its parameter subtree. + /// This overload is also used by LEFT and RIGHT, which have dedicated AST node types. + /// + private bool ShouldFormatFunctionCallParameterList(IList parameters) where T : TSqlFragment + { + return _options.MultilineNestedFunctionCalls + && parameters.Count > 0 + && (_multilineFunctionCallDepth > 0 || ContainsFunctionCall(parameters)); + } + + /// + /// Anchors the outermost multiline function call so new lines return to its starting column. + /// Nested calls reuse that alignment scope. + /// + private AlignmentPoint PushFunctionCallAlignmentPoint() + { + if (_multilineFunctionCallDepth > 0) + { + return null; + } + + var functionCallStart = new AlignmentPoint(); + MarkAndPushAlignmentPointKeepingNameScope(functionCallStart); + return functionCallStart; + } + + /// + /// Removes the alignment scope created for an outermost multiline function call. + /// + private void PopFunctionCallAlignmentPoint(AlignmentPoint functionCallStart) + { + if (functionCallStart != null) + { + PopAlignmentPoint(); + } + } + + /// + /// Generates a multiline parameter list and tracks nested calls. A sole non-function + /// parameter remains beside the opening parenthesis. + /// + private void GenerateMultilineFunctionCallParameterList(IList parameters) where T : TSqlFragment + { + _multilineFunctionCallDepth++; + try + { + ListGenerationOption option = ListGenerationOption.CreateMultilineFunctionCallOption(_options); + if (parameters.Count == 1 && !ContainsFunctionCall(parameters)) + { + option.NewLineAfterOpenParenthesis = false; + option.NewLineBeforeCloseParenthesis = false; + option.NewLineBeforeItems = false; + option.MultipleIndentItems = 0; + } + + GenerateFragmentList(parameters, option); + } + finally + { + _multilineFunctionCallDepth--; + } + } + + /// + /// Determines whether any parameter subtree contains a supported function-call node. + /// + private static bool ContainsFunctionCall(IList parameters) where T : TSqlFragment + { + var visitor = new FunctionCallFindingVisitor(); + foreach (T parameter in parameters) + { + parameter.Accept(visitor); + if (visitor.Found) + { + return true; + } + } + + return false; + } + + private sealed class FunctionCallFindingVisitor : TSqlFragmentVisitor + { + public bool Found { get; private set; } + + public override void Visit(FunctionCall node) + { + Found = true; + } + + public override void ExplicitVisit(LeftFunctionCall node) + { + Found = true; + } + + public override void ExplicitVisit(RightFunctionCall node) + { + Found = true; + } + } + + /// + /// Generates a closing parenthesis on a new line when required to terminate a deferred + /// trailing single-line comment first. + /// + private void GenerateFunctionCallRightParenthesis() + { + if (HasDeferredTrailingSingleLineComments) + { + NewLine(); + } + + GenerateSymbol(TSqlTokenType.RightParenthesis); + } + public override void ExplicitVisit(JsonKeyValue pair) { GenerateFragmentIfNotNull(pair.JsonKeyName); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs index d3d73987..d96a9285 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.GroupByClause.cs @@ -22,11 +22,26 @@ public override void ExplicitVisit(GroupByClause node) } AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); - if (!GenerateClauseBodyStart(_options.NewLineBeforeGroupByClause, clauseBody)) + + // Modern GROUP BY ALL (no explicit column list) has no grouping specifications; + // the grouping columns are inferred from the SELECT list. Only emit the body + // (and its leading space/newline) when a column list is actually present. + if (!node.All || node.GroupingSpecifications.Count > 0) { - GenerateSpace(); + if (!GenerateClauseBodyStart(_options.NewLineBeforeGroupByClause, clauseBody)) + { + GenerateSpace(); + } + + if (_options.MultilineGroupByElementsList) + { + GenerateAlignedMultilineCommaSeparatedList(node.GroupingSpecifications); + } + else + { + GenerateCommaSeparatedList(node.GroupingSpecifications); + } } - GenerateCommaSeparatedList(node.GroupingSpecifications); if (node.GroupByOption != GroupByOption.None) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs index c2b3bfe9..9b754ac6 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.HavingClause.cs @@ -19,11 +19,12 @@ public override void ExplicitVisit(HavingClause node) AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); if (GenerateClauseBodyStart(_options.NewLineBeforeHavingClause, clauseBody)) { - GenerateFragmentIfNotNull(node.SearchCondition); + GeneratePredicate(node.SearchCondition, _options.MultilineHavingPredicatesList); } else { - GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); + GenerateSpace(); + GeneratePredicate(node.SearchCondition, _options.MultilineHavingPredicatesList); } PopAlignmentPoint(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IifCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IifCall.cs index 2f2980c0..726c58dd 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IifCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.IifCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(IIfCall node) { - GenerateIdentifier(CodeGenerationSupporter.IIf); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.IIf)) + { + GenerateIdentifier(CodeGenerationSupporter.IIf); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Predicate); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs index 45957598..fe97db26 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InsertStatement.cs @@ -65,15 +65,30 @@ public override void ExplicitVisit(InsertSpecification node) if (node.Columns.Count > 0) { - MarkInsertColumnsAlignmentPointWhenNecessary(insertColumns); if (_options.MultilineInsertTargetsList) { ListGenerationOption option = ListGenerationOption.CreateOptionFromFormattingConfig(_options); - GenerateFragmentList(node.Columns, option); + if (option.NewLineBeforeOpenParenthesis || ShouldMoveInsertValuesToNewLine()) + { + // No inline "(" to align under (it moves to its own line), or the VALUES + // rows move to their own indented line: keep the pre-existing mark position. + MarkInsertColumnsAlignmentPointWhenNecessary(insertColumns); + GenerateFragmentList(node.Columns, option); + } + else + { + // Inline "(": mark insertColumns at the list's "(" (the same column the + // non-multiline branch marks) so the VALUES row constructors line up under + // the target list's opening parenthesis. + GenerateFragmentList(node.Columns, option, insertColumns); + } } else { + // Mark insertColumns right at "(" (after the separating space), matching where + // ValuesInsertSource marks it for its own row list, so both parentheses line up. GenerateSpace(); + MarkInsertColumnsAlignmentPointWhenNecessary(insertColumns); GenerateParenthesisedCommaSeparatedList(node.Columns); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs index 8b6e8188..4e7fb3c9 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.InvokeExternalApiFunction.cs @@ -31,7 +31,10 @@ public override void ExplicitVisit(InvokeExternalApiFunctionCall node) throw new InvalidOperationException("InvokeExternalApiFunctionCall.FunctionName is required."); } - GenerateIdentifier(CodeGenerationSupporter.InvokeExternalApi); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.InvokeExternalApi)) + { + GenerateIdentifier(CodeGenerationSupporter.InvokeExternalApi); + } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.FunctionSetName); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs index 2fbb9c26..1df5d7d7 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ListGenerationOption.cs @@ -30,6 +30,7 @@ internal enum SeparatorType public Boolean NewLineBeforeFirstItem { get; set; } public Boolean NewLineBeforeItems { get; set; } + public Boolean AlignItemsForNewLines { get; set; } public int MultipleIndentItems { get; set; } public static readonly ListGenerationOption MultipleLineSelectElementOption = new ListGenerationOption() @@ -81,6 +82,25 @@ public static ListGenerationOption CreateOptionFromFormattingConfig(SqlScriptGen return option; } + + public static ListGenerationOption CreateMultilineFunctionCallOption(SqlScriptGeneratorOptions formatting) + { + return new ListGenerationOption + { + Parenthesised = true, + AlwaysGenerateParenthesis = true, + NewLineBeforeOpenParenthesis = formatting.NewLineBeforeOpenParenthesisInMultilineList, + NewLineAfterOpenParenthesis = true, + IndentParentheses = false, + NewLineBeforeCloseParenthesis = formatting.NewLineBeforeCloseParenthesisInMultilineList, + AlignParentheses = false, + NewLineBeforeItems = true, + NewLineBeforeFirstItem = false, + AlignItemsForNewLines = true, + MultipleIndentItems = 1, + Separator = SeparatorType.Comma, + }; + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.NullIfExpression.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.NullIfExpression.cs index 2619ec56..b2ae046d 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.NullIfExpression.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.NullIfExpression.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(NullIfExpression node) { - GenerateKeyword(TSqlTokenType.NullIf); + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.NullIf)) + { + GenerateKeyword(TSqlTokenType.NullIf); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.FirstExpression); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHints.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHints.cs index 201df617..22f05f50 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHints.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHints.cs @@ -17,8 +17,11 @@ protected void GenerateOptimizerHints(IList hints) AlignmentPoint start = new AlignmentPoint(); MarkAndPushAlignmentPoint(start); - GenerateKeywordAndSpace(TSqlTokenType.Option); - GenerateParenthesisedCommaSeparatedList(hints); + // GenerateKeyword (not GenerateKeywordAndSpace): the separating space before the + // open parenthesis is emitted by GenerateWithOptionsList so the single-line output + // (OPTION (...)) is unchanged while multiline output is handled uniformly. + GenerateKeyword(TSqlTokenType.Option); + GenerateWithOptionsList(hints, spaceBeforeSingleLineParenthesis: true); PopAlignmentPoint(); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs index c74949e7..a9375204 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OrderByClause.cs @@ -18,11 +18,39 @@ public override void ExplicitVisit(OrderByClause node) GenerateSpaceAndKeyword(TSqlTokenType.By); AlignmentPoint clauseBody = GetAlignmentPointForFragment(node, ClauseBody); - if (!GenerateClauseBodyStart(_options.NewLineBeforeOrderByClause, clauseBody)) + + if (node.All) { + // ORDER BY ALL shorthand: orders by every column in the select list. + // ALL is a keyword modifier of the clause (like GROUP BY ALL), so keep it on + // the same line as ORDER BY. The NewLineBeforeOrderByClause option only applies + // to an explicit column list, not to the ALL shorthand. GenerateSpace(); + GenerateKeyword(TSqlTokenType.All); + + TokenGenerator sortOrderGenerator = GetValueForEnumKey(_sortOrderGenerators, node.AllSortOrder); + if (sortOrderGenerator != null && node.AllSortOrder != SortOrder.NotSpecified) + { + GenerateSpace(); + GenerateToken(sortOrderGenerator); + } + } + else + { + if (!GenerateClauseBodyStart(_options.NewLineBeforeOrderByClause, clauseBody)) + { + GenerateSpace(); + } + + if (_options.MultilineOrderByElementsList) + { + GenerateAlignedMultilineCommaSeparatedList(node.OrderByElements); + } + else + { + GenerateCommaSeparatedList(node.OrderByElements); + } } - GenerateCommaSeparatedList(node.OrderByElements); PopAlignmentPoint(); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs index 36c072b7..a9d8a42a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs @@ -40,7 +40,14 @@ public override void ExplicitVisit(OverClause node) GenerateSpaceAndKeyword(TSqlTokenType.By); GenerateSpace(); - GenerateCommaSeparatedList(node.Partitions); + if (_options.MultilinePartitionByElementsList) + { + GenerateAlignedMultilineCommaSeparatedList(node.Partitions); + } + else + { + GenerateCommaSeparatedList(node.Partitions); + } } if (node.OrderByClause != null) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ParseCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ParseCall.cs index c81f67cc..b769a93a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ParseCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ParseCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(ParseCall node) { - GenerateIdentifier(CodeGenerationSupporter.Parse); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.Parse)) + { + GenerateIdentifier(CodeGenerationSupporter.Parse); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.StringValue); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.RestoreStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.RestoreStatement.cs index ee632b72..669929a9 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.RestoreStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.RestoreStatement.cs @@ -65,12 +65,11 @@ public override void ExplicitVisit(RestoreStatement node) NewLineAndIndent(); GenerateKeyword(TSqlTokenType.With); - GenerateSpace(); // could be // MoveRestoreOption // SimpleRestoreOption // StopRestoreOption - GenerateCommaSeparatedList(node.Options); + GenerateWithOptionsListNonParenthesized(node.Options); } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSEqualCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSEqualCall.cs index 9e93cf2d..2f8ec041 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSEqualCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSEqualCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(TSEqualCall node) { - GenerateKeyword(TSqlTokenType.TSEqual); + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.TSEqual)) + { + GenerateKeyword(TSqlTokenType.TSEqual); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.FirstExpression); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs index a5ed633c..3151471e 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlBatch.cs @@ -23,8 +23,10 @@ public override void ExplicitVisit(TSqlBatch node) if (statement is TSqlStatementSnippet == false) { - NewLine(); - NewLine(); + for (int i = 0; i < _options.NumNewlinesAfterBatchStatement; i++) + { + NewLine(); + } } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs index 5f568500..ced6634a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TSqlScript.cs @@ -27,16 +27,38 @@ public override void ExplicitVisit(TSqlScript node) } else { + // GO always starts a new line, whatever the batch statements left behind. NewLine(); GenerateKeyword(TSqlTokenType.Go); - NewLine(); + GenerateNewLinesAfterBatch(); } GenerateFragmentIfNotNull(item); } + // Preserve the trailing GO separators when the parsed script ended with them and the option is enabled. + if (_options.PersistTrailingGo && node.TrailingGoCount > 0) + { + // Emit comments that precede the trailing GO(s) so they stay above the batch separator. + EmitCommentsUntilNextNonTriviaToken(); + for (int i = 0; i < node.TrailingGoCount; i++) + { + NewLine(); + GenerateKeyword(TSqlTokenType.Go); + GenerateNewLinesAfterBatch(); + } + } + // Emit any remaining comments at end of script (after the last statement) EmitRemainingComments(); } + + private void GenerateNewLinesAfterBatch() + { + for (int i = 0; i < _options.NumNewlinesAfterBatches; i++) + { + NewLine(); + } + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TableHints.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TableHints.cs index 60f15d2d..5ecb4d92 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TableHints.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TableHints.cs @@ -15,8 +15,7 @@ protected void GenerateWithTableHints(IList tableHints) if (tableHints.Count > 0) { GenerateSpaceAndKeyword(TSqlTokenType.With); - GenerateSpace(); - GenerateParenthesisedCommaSeparatedList(tableHints); + GenerateWithOptionsList(tableHints, spaceBeforeSingleLineParenthesis: true); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryCastCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryCastCall.cs index e7f2b8ba..4aa51776 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryCastCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryCastCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(TryCastCall node) { - GenerateIdentifier(CodeGenerationSupporter.TryCast); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.TryCast)) + { + GenerateIdentifier(CodeGenerationSupporter.TryCast); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Parameter); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryConvertCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryConvertCall.cs index 268ef1d1..85675cb7 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryConvertCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryConvertCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(TryConvertCall node) { - GenerateKeyword(TSqlTokenType.TryConvert); + if (!TryGenerateBuiltInFunctionName(TSqlTokenType.TryConvert)) + { + GenerateKeyword(TSqlTokenType.TryConvert); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.DataType); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryParseCall.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryParseCall.cs index 47338c31..04b83415 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryParseCall.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.TryParseCall.cs @@ -11,7 +11,10 @@ partial class SqlScriptGeneratorVisitor { public override void ExplicitVisit(TryParseCall node) { - GenerateIdentifier(CodeGenerationSupporter.TryParse); + if (!TryGenerateBuiltInFunctionName(CodeGenerationSupporter.TryParse)) + { + GenerateIdentifier(CodeGenerationSupporter.TryParse); + } GenerateSpaceAndSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.StringValue); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs index df7b2f49..cdefa265 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs @@ -224,7 +224,7 @@ protected void GenerateCommaSeparatedList(IList list, Boolean insertNewLin else { GenerateSymbol(TSqlTokenType.Comma); - if (insertNewLine) + if (insertNewLine || HasDeferredTrailingSingleLineComments) { NewLine(); } @@ -236,6 +236,41 @@ protected void GenerateCommaSeparatedList(IList list, Boolean insertNewLin }); } + // generate a multiline comma-separated list whose elements remain aligned when commas lead + protected void GenerateAlignedMultilineCommaSeparatedList(IList list) where T : TSqlFragment + { + if (list == null) + { + return; + } + + Boolean first = true; + Boolean leadingComma = _options.CommaPlacement == CommaPlacement.Leading; + AlignmentPoint elements = new AlignmentPoint(); + + foreach (T fragment in list) + { + if (!first) + { + if (leadingComma) + { + NewLine(); + GenerateRightAlignedCommaSeparator(); + } + else + { + GenerateSymbol(TSqlTokenType.Comma); + NewLine(); + } + } + + MarkAndPushAlignmentPoint(elements); + GenerateFragmentIfNotNull(fragment); + PopAlignmentPoint(); + first = false; + } + } + // generate a comma-separated list protected void GenerateCommaSeparatedList(IList list, bool insertNewLine, bool indent, bool generateSpaces = true) where T : TSqlFragment { @@ -334,9 +369,12 @@ protected void GenerateParenthesisedCommaSeparatedList(IList list, Boolean } } - protected void GenerateFragmentList(IList list, ListGenerationOption option) where T : TSqlFragment + protected void GenerateFragmentList(IList list, ListGenerationOption option, AlignmentPoint openParenthesisAlignmentPoint = null) where T : TSqlFragment { - AlignmentPoint parentheses = new AlignmentPoint(); + // When the caller supplies its own open-parenthesis alignment point, mark it at the "(" + // so downstream content (e.g. an INSERT statement's VALUES row constructors) can line up + // under the list's opening parenthesis. Defaults to a private point for all other callers. + AlignmentPoint parentheses = openParenthesisAlignmentPoint ?? new AlignmentPoint(); AlignmentPoint items = new AlignmentPoint(); Boolean generateParentheses = (option.AlwaysGenerateParenthesis || (list.Count > 0 && option.Parenthesised)); @@ -449,7 +487,7 @@ protected void GenerateFragmentList(IList list, ListGenerationOption optio // Only push alignment point for NewLine() restoration when comment preservation is enabled. // This ensures NewLine() calls within items (e.g., from EmitCommentToken) can restore // to the correct indented position, without affecting general formatting. - if (_options.PreserveComments) + if (_options.PreserveComments || option.AlignItemsForNewLines) { AlignmentPoint itemScope = new AlignmentPoint(); // Keep the current named-alignment-point scope so field alignment points @@ -483,7 +521,7 @@ protected void GenerateFragmentList(IList list, ListGenerationOption optio // generate close parenthesis if (generateParentheses) { - if (option.NewLineBeforeCloseParenthesis) + if (option.NewLineBeforeCloseParenthesis || HasDeferredTrailingSingleLineComments) { NewLine(); if (option.AlignParentheses) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ValuesInsertSource.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ValuesInsertSource.cs index cff3ddcd..726644a5 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ValuesInsertSource.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.ValuesInsertSource.cs @@ -25,15 +25,72 @@ public override void ExplicitVisit(ValuesInsertSource node) } else { - GenerateKeywordAndSpace(TSqlTokenType.Values); - - MarkClauseBodyAlignmentWhenNecessary(true, clauseBody); + GenerateKeyword(TSqlTokenType.Values); AlignmentPoint insertColumns = GetAlignmentPointForFragment(node, InsertColumns); + bool moveToNewLine = ShouldMoveInsertValuesToNewLine(); + + if (moveToNewLine) + { + NewLineAndIndent(); + } + else + { + GenerateSpace(); + MarkClauseBodyAlignmentWhenNecessary(true, clauseBody); + MarkInsertColumnsAlignmentPointWhenNecessary(insertColumns); + } + + // insertColumns is null for a ValuesInsertSource scripted on its own (no enclosing + // INSERT/MERGE registered the column-list point); skip all re-anchoring in that case. + bool alignLeadingCommaRows = !moveToNewLine + && _options.CommaPlacement == CommaPlacement.Leading + && insertColumns != null; + + if (alignLeadingCommaRows) + { + // A plain leading comma after NewLine() would land 2 columns past the aligned "(". + // Restore each continuation row to a neutral anchor, then re-mark insertColumns + // after a right-aligned comma so every row's "(" lines up with the first row's. + AlignmentPoint rowAnchor = new AlignmentPoint(); + PushAlignmentPoint(rowAnchor); + + bool firstRow = true; + foreach (RowValue rowValue in node.RowValues) + { + if (!firstRow) + { + NewLine(); + GenerateRightAlignedCommaSeparator(); + // insertColumns is non-null here (guaranteed by alignLeadingCommaRows). + Mark(insertColumns); + } + + GenerateFragmentIfNotNull(rowValue); + firstRow = false; + } + + PopAlignmentPoint(); + } + else + { + // Align continuation rows under the first row when an enclosing INSERT/MERGE + // registered insertColumns. For a bare source (null) we intentionally skip the + // push: rows fall back to the statement's start anchor, which is null-safe and + // avoids an unreachable branch (the non-moved bare-source path can't run in debug + // builds because the null clauseBody/insertColumns marks above assert first). + if (insertColumns != null) + { + PushAlignmentPoint(insertColumns); + } - MarkInsertColumnsAlignmentPointWhenNecessary(insertColumns); + GenerateCommaSeparatedList(node.RowValues, true, moveToNewLine); - GenerateCommaSeparatedList(node.RowValues, true); + if (insertColumns != null) + { + PopAlignmentPoint(); + } + } } PopAlignmentPoint(); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs index 2e222117..ac94831d 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WhereClause.cs @@ -22,13 +22,16 @@ public override void ExplicitVisit(WhereClause node) if (node.SearchCondition != null) { + bool multilinePredicates = _options.MultilineWherePredicatesList && _options.NewLineBeforeWhereClause; + if (indented) { - GenerateFragmentIfNotNull(node.SearchCondition); + GeneratePredicate(node.SearchCondition, multilinePredicates); } else { - GenerateSpaceAndFragmentIfNotNull(node.SearchCondition); + GenerateSpace(); + GeneratePredicate(node.SearchCondition, multilinePredicates); } } else diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs index dc40eb84..6d77ae23 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WindowDefinition.cs @@ -31,7 +31,14 @@ public override void ExplicitVisit(WindowDefinition node) GenerateSpaceAndKeyword(TSqlTokenType.By); GenerateSpace(); - GenerateCommaSeparatedList(node.Partitions); + if (_options.MultilinePartitionByElementsList) + { + GenerateAlignedMultilineCommaSeparatedList(node.Partitions); + } + else + { + GenerateCommaSeparatedList(node.Partitions); + } } if (node.OrderByClause != null) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WithOptionsList.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WithOptionsList.cs new file mode 100644 index 00000000..47e92e44 --- /dev/null +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.WithOptionsList.cs @@ -0,0 +1,92 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ +using System.Collections.Generic; +using Microsoft.SqlServer.TransactSql.ScriptDom; + +namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator +{ + partial class SqlScriptGeneratorVisitor + { + // Scope of MultilineWithOptionsList (what these helpers do and do NOT cover): + // + // Covered (routed through these helpers): + // * Index options for every statement that funnels through the shared virtual + // GenerateIndexOptions (CREATE/ALTER INDEX, CREATE COLUMNSTORE/JSON/VECTOR INDEX, + // inline index definitions and UNIQUE/PRIMARY KEY constraints in CREATE TABLE, and + // ALTER TABLE ... ALTER INDEX / REBUILD). + // * CREATE SELECTIVE XML INDEX options, table hints (WITH), query hints (OPTION), and + // the non-parenthesized BACKUP / RESTORE WITH options. + // + // Intentionally NOT covered: + // * The Sql80ScriptGeneratorVisitor.GenerateIndexOptions override, which emits the legacy + // SQL Server 2000 "WITH opt, opt" (non-parenthesized) index-option syntax. It does not + // call these helpers, so the option is a no-op for that generator. + // * ALTER INDEX ... SET (...): SET is a distinct clause from WITH and is left single-line. + // * The non-selective CREATE XML INDEX and CREATE SPATIAL INDEX option lists, which emit + // their WITH (...) options through their own generators rather than the shared + // GenerateIndexOptions (only CREATE SELECTIVE XML INDEX is routed through these helpers). + // * Other WITH / option lists outside the list above, e.g. CREATE TABLE table options + // (MEMORY_OPTIMIZED, DATA_COMPRESSION, DISTRIBUTION), CREATE/ALTER PROCEDURE|FUNCTION| + // TRIGGER WITH options (ENCRYPTION, SCHEMABINDING, EXECUTE AS), CREATE STATISTICS WITH, + // FULLTEXT INDEX WITH, and DBCC ... WITH. CREATE EXTERNAL TABLE already has its own + // multiline handling and is not affected here. The WITH keyword of a common table + // expression and XMLNAMESPACES are unrelated constructs and are never touched. + + // Generates a parenthesized WITH / OPTION clause option list (index options, table hints, + // query hints). When MultilineWithOptionsList is enabled the options are written one per + // line inside the parentheses (honoring CommaPlacement and the parenthesis-placement + // options); otherwise the original single-line parenthesized list is produced. Callers that + // have not already written the separating space before the open parenthesis (for example + // ALTER INDEX ... REBUILD, which historically emits WITH(...) with no space) pass + // spaceBeforeSingleLineParenthesis = true so their single-line output is unchanged. + protected void GenerateWithOptionsList(IList options, bool spaceBeforeSingleLineParenthesis) where T : TSqlFragment + { + if (options == null || options.Count == 0) + { + return; + } + + if (_options.MultilineWithOptionsList) + { + GenerateFragmentList(options, ListGenerationOption.CreateOptionFromFormattingConfig(_options)); + } + else + { + if (spaceBeforeSingleLineParenthesis) + { + GenerateSpace(); + } + + GenerateParenthesisedCommaSeparatedList(options); + } + } + + // Generates a non-parenthesized WITH clause option list (BACKUP / RESTORE options). The + // caller has already written the WITH keyword. When MultilineWithOptionsList is enabled each + // option is written on its own line indented one level from the statement keyword (aligned + // beneath the WITH keyword), honoring CommaPlacement; otherwise the options remain on a + // single line following the WITH keyword. + protected void GenerateWithOptionsListNonParenthesized(IList options) where T : TSqlFragment + { + if (options == null || options.Count == 0) + { + return; + } + + if (_options.MultilineWithOptionsList) + { + // Same layout as procedure parameters: non-parenthesized, one option per line, + // indented one level, with the leading new line produced by the option itself. + GenerateFragmentList(options, ListGenerationOption.MultipleLineProcedureParameterOption); + } + else + { + GenerateSpace(); + GenerateCommaSeparatedList(options); + } + } + } +} diff --git a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml index e8b6bd1c..a7c86591 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml +++ b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml @@ -27,6 +27,13 @@ Gets or sets how square brackets are applied to object identifiers during script generation. IncludeBrackets wraps all identifiers in square brackets; ExcludeBrackets removes brackets from identifiers that do not require them (identifiers conflicting with reserved words for the configured SqlVersion or containing special characters retain their brackets). + + + + + + Gets or sets the casing applied to built-in / system function names (such as GETDATE, ISNULL, COALESCE, CAST, COUNT) during script generation. The default (Preserve) has no effect on the formatted output. When set to any other value it takes precedence over KeywordCasing for function names; under Preserve, keyword-backed built-ins such as CAST and CONVERT continue to follow KeywordCasing. Data type names, keywords, string literals, and variables are never affected. Casing is applied to every unqualified, non-delimited function name, which is safe because T-SQL resolves a one-part scalar function name as a built-in function and never as a user-defined one (a scalar user-defined function must be called with at least a two-part name). Schema-qualified (for example dbo.MyFunc) and delimited (for example [MyFunc]) function names, and method calls on a variable or column (for example @g.STArea()), are always preserved. Keyword-form niladic functions (such as CURRENT_TIMESTAMP, SYSTEM_USER) and built-in table-valued functions (such as STRING_SPLIT, OPENJSON) are not affected. + Gets or sets the Sql version to generate script for @@ -44,6 +51,9 @@ IncludeSemiColons_Description Gets or sets a boolean indicating if a semi colon should be included after each statement + + Gets or sets a boolean indicating if a semicolon terminator is written after a BEGIN...END block and after the END CATCH of a BEGIN TRY...END TRY BEGIN CATCH...END CATCH block. When false (the default), these blocks are written without a terminator, preserving the previous script-generation behavior. When true, a semicolon is appended, so a terminator supplied in the source script survives a parse and generate round-trip. END TRY is never terminated because it is internal to the TRY...CATCH block. + Gets or sets a boolean indicating if index definitions should have UNIQUE, INCLUDE and WHERE on their own line @@ -57,7 +67,16 @@ Gets or sets a boolean indicating if a space should be included between parameters in a data type - Gets or sets the number of newlines to include after each statement + Gets or sets the number of newlines to include after each statement of a nested statement list, such as the body of a BEGIN...END block, stored procedure, trigger, function, IF or WHILE. The newlines are written between consecutive statements only, not after the last one, so the default of 1 puts each nested statement on its own line with no blank line between them. Statements owned directly by a batch are not affected by this setting; use NumNewlinesAfterBatchStatement for those. + + + Gets or sets the number of newlines to include after each statement owned directly by a batch, that is, each top level statement of a script between GO separators. The newlines are written after every such statement, including the last one in the batch, except when the statement is a TSqlStatementSnippet (snippets are emitted as-is and do not receive additional trailing newlines from this option). The default of 2 leaves one blank line between consecutive top level statements and, together with the newline that always precedes GO, two blank lines before the GO that closes the batch. Statements nested inside another statement are not affected by this setting; use NumNewlinesAfterStatement for those. + + + Gets or sets the number of newlines to include after the GO separator that is written between two batches. GO is always preceded by a newline of its own so that it starts a new line, and the blank lines before it are controlled by NumNewlinesAfterBatchStatement; this setting only controls what follows GO, so the default of 1 starts the next batch on the following line with no blank line in between. + + + Gets or sets a boolean indicating whether the trailing GO batch separators are generated when the parsed script ended with them (see TSqlScript.TrailingGoCount). Defaults to false, so a trailing GO is not emitted and generation behavior is unchanged. Gets or sets a boolean indicating if comments from the original script should be preserved in the generated output @@ -65,6 +84,9 @@ Gets or sets a value indicating whether commas in a multi-line comma-separated list are placed at the end of the line (trailing) or at the start of the next line (leading). When set to Leading, the IndentationMode setting is ignored and indentation always uses spaces. + + Gets or sets the number of spaces written after a leading comma when CommaPlacement is Leading. Valid values are 0 and 1. The default is 1. + @@ -110,10 +132,10 @@ - Gets or sets how a clause body (the part after FROM, WHERE, GROUP BY, etc.) is laid out. Aligned keeps the body on the keyword's line, lining all clause bodies up under a shared column past the widest keyword. Indented puts the body on its own new line, one indent level (IndentationSize) past the keyword, so nesting grows one step per level instead of drifting right. When Indented, AlignClauseBodies is ignored. + Gets or sets how a clause body (the part after FROM, WHERE, GROUP BY, etc.) is laid out. Aligned keeps the body on the keyword's line, lining all clause bodies up under a shared column past the widest keyword. Indented puts the body on its own new line, one indent level (IndentationSize) past the keyword, so nesting grows one step per level instead of drifting right. When Indented, AlignClauseBodies is ignored for clause bodies. - Gets or sets whether clause bodies are padded to line up under a shared column. Only applies when ClauseBodyAlignment is Aligned: true pads to the aligned column, false uses a single space after the keyword. Ignored when ClauseBodyAlignment is Indented. + Gets or sets whether clause bodies are padded to line up under a shared column. Only applies when ClauseBodyAlignment is Aligned: true pads to the aligned column, false uses a single space after the keyword. When ClauseBodyAlignment is Indented, this setting is generally ignored for clause bodies; however, it also affects an INSERT statement's VALUES row constructors: when ClauseBodyAlignment is Indented and this is false, the row constructors move to their own indented line instead of being padded to line up under the column list. @@ -123,6 +145,18 @@ Gets or sets a boolean indicating if WHERE predicates (expressions separated by AND, and OR) should be written on multiple lines + + Gets or sets a boolean indicating if GROUP BY elements should be listed as a multi-line list + + + Gets or sets a boolean indicating if HAVING predicates (expressions separated by AND or OR) should be written on multiple lines + + + Gets or sets a boolean indicating if ORDER BY elements should be listed as a multi-line list + + + Gets or sets a boolean indicating if PARTITION BY elements in window specifications should be listed as a multi-line list + Gets or sets a boolean indicating if the values in an IN (values) predicate should be listed as a multi-line list. When false, the IN list is written on a single line. @@ -176,6 +210,11 @@ Gets or sets a boolean indicating if a newline should be placed before an close parenthesis when writing a multi-line list in parenthesis + + + Gets or sets a boolean indicating if parameters in a nested function call tree should be written on separate lines and indented one level per call. Isolated function calls remain on one line. When false (the default), all function calls retain the existing compact layout. + + Gets or sets a boolean indicating if file paths can be used for external library content @@ -186,4 +225,9 @@ Gets or sets a boolean indicating if file paths can be used for external language content + + + Gets or sets a boolean indicating if the options in a WITH (or OPTION) clause should be listed on separate lines. This applies to CREATE/ALTER INDEX and other index options, table hints (WITH), query hints (OPTION), and BACKUP/RESTORE options (WITH). It does not apply to the WITH keyword of common table expressions or XMLNAMESPACES, nor to the option lists of CREATE XML INDEX (non-selective) or CREATE SPATIAL INDEX, which have their own generators. When false (default), the options are written on a single line. CommaPlacement applies within the options list. For parenthesized clauses, NewLineBeforeOpenParenthesisInMultilineList and NewLineBeforeCloseParenthesisInMultilineList control parenthesis placement. When the WITH keyword begins the option list, the options are indented one level from the statement. + + diff --git a/Test/SqlDom/Baselines100/InsertStatementTests100.sql b/Test/SqlDom/Baselines100/InsertStatementTests100.sql index 9160ad48..d6047940 100644 --- a/Test/SqlDom/Baselines100/InsertStatementTests100.sql +++ b/Test/SqlDom/Baselines100/InsertStatementTests100.sql @@ -3,11 +3,11 @@ AS BEGIN INSERT INTO t1 VALUES (1, 2), - (DEFAULT, 0), - (NULL, NULL); + (DEFAULT, 0), + (NULL, NULL); INSERT INTO t2 VALUES ('aaa', 'bbb', 1), - ('ccc', 'ddd', 20); + ('ccc', 'ddd', 20); END @@ -32,5 +32,5 @@ CREATE PROCEDURE p1 AS BEGIN INSERT INTO t1 ($ACTION, $CUID, $ROWGUID) - VALUES (1, 2, 3); + VALUES (1, 2, 3); END \ No newline at end of file diff --git a/Test/SqlDom/Baselines130/CreateTableTests130.sql b/Test/SqlDom/Baselines130/CreateTableTests130.sql index 2e6f8d1d..7590e1f7 100644 --- a/Test/SqlDom/Baselines130/CreateTableTests130.sql +++ b/Test/SqlDom/Baselines130/CreateTableTests130.sql @@ -330,6 +330,13 @@ CREATE TABLE t ( ); +GO +CREATE TABLE t ( + COL0 VARCHAR (100) COLLATE SQL_Latin1_General_CP1_CI_AS SPARSE MASKED WITH (FUNCTION = 'default()') NULL, + COL1 VARCHAR (100) SPARSE MASKED WITH (FUNCTION = 'default()') NULL +); + + GO CREATE TABLE t ( COL0 INT NOT NULL, diff --git a/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql b/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql index a11724cd..ef7cb3c0 100644 --- a/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql +++ b/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql @@ -44,9 +44,9 @@ CREATE TABLE t2 ( GO INSERT INTO t2 (Text) -VALUES (N'This is the first text.'), -(N'Second sample text.'), -(N'Third example text.'); +VALUES (N'This is the first text.'), + (N'Second sample text.'), + (N'Third example text.'); GO CREATE VIEW v_GeneratedChunksFromTable diff --git a/Test/SqlDom/Baselines180/CreateDatabaseCollateBeforeEditionTests120.sql b/Test/SqlDom/Baselines180/CreateDatabaseCollateBeforeEditionTests120.sql new file mode 100644 index 00000000..761e9284 --- /dev/null +++ b/Test/SqlDom/Baselines180/CreateDatabaseCollateBeforeEditionTests120.sql @@ -0,0 +1,12 @@ +CREATE DATABASE [db1] COLLATE SQL_Latin1_General_CP1_CI_AS + (EDITION = 'Standard'); + + +GO +CREATE DATABASE hito COLLATE Japanese_Bushu_Kakusu_100_CS_AS_KS_WS + (MAXSIZE = 500 MB, EDITION = 'GeneralPurpose', SERVICE_OBJECTIVE = 'GP_Gen5_8'); + + +GO +CREATE DATABASE d1 COLLATE SQL_Latin1_General_CP1_CI_AS + (EDITION = 'business', SERVICE_OBJECTIVE = 'shared'); diff --git a/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql b/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql index a0af4ad7..ee84ff09 100644 --- a/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql +++ b/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql @@ -93,6 +93,10 @@ SELECT * FROM t1 GROUP BY ALL c1; +SELECT * +FROM t1 +GROUP BY ALL c1, c2, c3; + SELECT * FROM t1 GROUP BY c1, c2, c3; diff --git a/Test/SqlDom/BaselinesFabricDW/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql new file mode 100644 index 00000000..761e9284 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql @@ -0,0 +1,12 @@ +CREATE DATABASE [db1] COLLATE SQL_Latin1_General_CP1_CI_AS + (EDITION = 'Standard'); + + +GO +CREATE DATABASE hito COLLATE Japanese_Bushu_Kakusu_100_CS_AS_KS_WS + (MAXSIZE = 500 MB, EDITION = 'GeneralPurpose', SERVICE_OBJECTIVE = 'GP_Gen5_8'); + + +GO +CREATE DATABASE d1 COLLATE SQL_Latin1_General_CP1_CI_AS + (EDITION = 'business', SERVICE_OBJECTIVE = 'shared'); diff --git a/Test/SqlDom/BaselinesFabricDW/ModernGroupByAllTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/ModernGroupByAllTestsFabricDW.sql new file mode 100644 index 00000000..5acd429b --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/ModernGroupByAllTestsFabricDW.sql @@ -0,0 +1,71 @@ +SELECT City, + Region, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL; +GO + +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +WHERE HireDate >= '19930101' +GROUP BY ALL +HAVING COUNT(*) > 5 +ORDER BY City; +GO + +SELECT Region, + YEAR(OrderDate) AS OrderYear, + Category, + COUNT(*) AS NumOrders, + SUM(Amount) AS Total +FROM Sales +WHERE Amount > 0 +GROUP BY ALL; +GO + +SELECT c.CustomerName, + COUNT(*) AS Orders +FROM Orders AS o + INNER JOIN + Customers AS c + ON o.CustomerId = c.CustomerId +GROUP BY ALL; +GO + +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL +ORDER BY City DESC; +GO + +SELECT * +FROM (SELECT City, + COUNT(*) AS Cnt + FROM dbo.Employees + GROUP BY ALL) AS t; +GO + +SELECT Region, + SUM(Amount) / COUNT(DISTINCT CustomerId) AS AvgSpend +FROM Sales +GROUP BY ALL; +GO + +CREATE VIEW v_GroupByAllView +AS +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL; +GO + +CREATE PROCEDURE usp_GroupByAll +AS +BEGIN + SELECT City, + COUNT(*) AS NumEmps + FROM dbo.Employees + GROUP BY ALL; +END diff --git a/Test/SqlDom/BaselinesFabricDW/OrderByAllTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/OrderByAllTestsFabricDW.sql new file mode 100644 index 00000000..89b452ff --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/OrderByAllTestsFabricDW.sql @@ -0,0 +1,95 @@ +SELECT c1, + c2 +FROM t1 +ORDER BY ALL; +GO + +SELECT c1, + c2 +FROM t1 +ORDER BY ALL ASC; +GO + +SELECT c1, + c2 +FROM t1 +ORDER BY ALL DESC; +GO + +SELECT * +FROM t1 +ORDER BY ALL; +GO + +SELECT c1, + c2 +FROM t1 +ORDER BY ALL +OFFSET 2 ROWS FETCH NEXT 5 ROWS ONLY; +GO + +SELECT c1 +FROM t1 +UNION ALL +SELECT c1 +FROM t2 +ORDER BY ALL; +GO + +SELECT * +FROM (SELECT TOP 5 c1, + c2 + FROM t1 + ORDER BY ALL) AS sub; +GO + +SELECT c1, + COUNT(*) AS Cnt +FROM t1 +GROUP BY c1 +ORDER BY ALL; +GO + +SELECT c1, + COUNT(*) AS Cnt +FROM t1 +GROUP BY c1 +HAVING COUNT(*) > 1 +ORDER BY ALL DESC; +GO + +SELECT a.c1, + b.c2 +FROM t1 AS a + INNER JOIN + t2 AS b + ON a.c1 = b.c1 +WHERE b.c2 > 0 +ORDER BY ALL; +GO + +SELECT c1, + COUNT(*) AS Cnt, + SUM(COUNT(*)) OVER (ORDER BY c1 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningCnt +FROM t1 +GROUP BY c1 +ORDER BY ALL; +GO + +CREATE VIEW v_OrderByAllView +AS +SELECT c1, + c2 +FROM t1 +ORDER BY ALL +OFFSET 0 ROWS; +GO + +CREATE PROCEDURE usp_OrderByAll +AS +BEGIN + SELECT c1, + c2 + FROM t1 + ORDER BY ALL; +END \ No newline at end of file diff --git a/Test/SqlDom/Only130SyntaxTests.cs b/Test/SqlDom/Only130SyntaxTests.cs index 0665459f..3b71eb28 100644 --- a/Test/SqlDom/Only130SyntaxTests.cs +++ b/Test/SqlDom/Only130SyntaxTests.cs @@ -26,7 +26,7 @@ public partial class SqlDomTests new ParserTest130("AlterTableDropTableElementStatementTests130.sql", 1, 1, 1, 1, 1), new ParserTest130("ColumnStoreInlineIndex130.sql", 10, 10, 10, 10, 10), new ParserTest130("CreateIndexStatementTests130.sql", 6, 6, 6, 6, 6), - new ParserTest130("CreateTableTests130.sql", 62, 62, 62, 62, 62), + new ParserTest130("CreateTableTests130.sql", 63, 63, 63, 63, 63), new ParserTest130("CreateAlterSecurityPolicyStatementTests130.sql", 2, 33, 33, 33, 33), new ParserTest130("JsonForClauseTests130.sql", 14, 14, 14, 14, 14), new ParserTest130("DropStatementsTests130.sql", 10, 10, 9, 9, 9), diff --git a/Test/SqlDom/Only180SyntaxTests.cs b/Test/SqlDom/Only180SyntaxTests.cs index 9be98076..e26be85e 100644 --- a/Test/SqlDom/Only180SyntaxTests.cs +++ b/Test/SqlDom/Only180SyntaxTests.cs @@ -16,6 +16,7 @@ public partial class SqlDomTests new ParserTest180("TrimFromReturnTests160.sql"), new ParserTest180("PersistSamplePercentStatisticsTests130.sql"), new ParserTest180("CreateSemanticIndexTests180.sql"), + new ParserTest180("CreateDatabaseCollateBeforeEditionTests120.sql", nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0) }; private static readonly ParserTest[] SqlAzure180_TestInfos = diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index 483e08ef..e3a53fef 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -27,6 +27,10 @@ public partial class SqlDomTests new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("InvokeExternalApiTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("ExternalFunctionTestsFabricDW.sql", nErrors80: 12, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11, nErrors170: 11, nErrors180: 0), + new ParserTestFabricDW("CreateDatabaseCollateBeforeEditionTestsFabricDW.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("ModernGroupByAllTestsFabricDW.sql", nErrors80: 9, nErrors90: 9, nErrors100: 9, nErrors110: 9, nErrors120: 9, nErrors130: 9, nErrors140: 9, nErrors150: 9, nErrors160: 9, nErrors170: 9, nErrors180: 9), + new ParserTestFabricDW("OrderByAllTestsFabricDW.sql", nErrors80: 13, nErrors90: 13, nErrors100: 13, nErrors110: 13, nErrors120: 13, nErrors130: 13, nErrors140: 13, nErrors150: 13, nErrors160: 13, nErrors170: 13, nErrors180: 13), + }; [TestMethod] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index faeb5a68..26e48488 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -2918,6 +2918,20 @@ public void SQL46062Test() } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CreateDatabaseCollateWithAzureOptionsDownlevelErrorTest() + { + // TSql110 wires azureOptions and collationOpt as mutually-exclusive alternatives, so COLLATE + // and parenthesized Azure edition options cannot coexist in either order (see TSql110.g createDatabase). + ParserTestUtils.ErrorTest110("CREATE DATABASE [db1] COLLATE SQL_Latin1_General_CP1_CI_AS (EDITION = 'Standard')", + new ParserErrorInfo(60, "SQL46010", "EDITION")); + ParserTestUtils.ErrorTest110("CREATE DATABASE d1 (EDITION = 'business') COLLATE SQL_Latin1_General_CP1_CI_AS", + new ParserErrorInfo(42, "SQL46010", "COLLATE")); + } + + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] @@ -7270,6 +7284,80 @@ Description NVARCHAR(200) ParserTestUtils.ErrorTestFabricDW(identityColumnSyntax2, new ParserErrorInfo(errorOffSet, "SQL46010", "(")); } + /// + /// Negative tests for the modern GROUP BY ALL (no explicit column list) syntax on Fabric DW. + /// The grammar accepts GROUP BY ALL with no columns, but WITH CUBE / WITH ROLLUP are rejected + /// at parse time (SQL46084), matching the source engine behavior. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void ModernGroupByAllNegativeTestsFabricDW() + { + // GROUP BY ALL (no columns) cannot be combined with WITH CUBE. + string withCube = "SELECT City, COUNT(*) AS NumEmps FROM dbo.Employees GROUP BY ALL WITH CUBE"; + ParserTestUtils.ErrorTestFabricDW(withCube, new ParserErrorInfo(withCube.IndexOf("CUBE"), "SQL46084")); + + // GROUP BY ALL (no columns) cannot be combined with WITH ROLLUP. + string withRollup = "SELECT City, COUNT(*) AS NumEmps FROM dbo.Employees GROUP BY ALL WITH ROLLUP"; + ParserTestUtils.ErrorTestFabricDW(withRollup, new ParserErrorInfo(withRollup.IndexOf("ROLLUP"), "SQL46084")); + + // GROUP BY ALL cannot be combined with a GROUPING SETS specification. + string groupingSets = "SELECT City, COUNT(*) AS NumEmps FROM dbo.Employees GROUP BY ALL GROUPING SETS ((City), ())"; + ParserTestUtils.ErrorTestFabricDW(groupingSets, new ParserErrorInfo(groupingSets.IndexOf("GROUPING"), "SQL46084")); + } + + /// + /// Negative tests for the ORDER BY ALL syntax on Fabric DW. ORDER BY ALL must stand alone + /// at the query / subquery level; mixing it with explicit items, or using it inside an + /// OVER() window clause or a WITHIN GROUP ordered-set aggregate, is rejected at parse time. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void OrderByAllNegativeTestsFabricDW() + { + // ALL followed by an explicit column is a syntax error. + string allThenColumn = "SELECT c1, c2 FROM t1 ORDER BY ALL, c1"; + ParserTestUtils.ErrorTestFabricDW(allThenColumn, new ParserErrorInfo(allThenColumn.IndexOf(",", allThenColumn.IndexOf("ALL")), "SQL46010", ",")); + + // An explicit column followed by ALL is a syntax error. + string columnThenAll = "SELECT c1, c2 FROM t1 ORDER BY c1, ALL"; + ParserTestUtils.ErrorTestFabricDW(columnThenAll, new ParserErrorInfo(columnThenAll.LastIndexOf("ALL"), "SQL46010", "ALL")); + + // ORDER BY ALL is not allowed inside an OVER() window clause. + string inOver = "SELECT ROW_NUMBER() OVER (ORDER BY ALL) FROM t1"; + ParserTestUtils.ErrorTestFabricDW(inOver, new ParserErrorInfo(inOver.IndexOf("ALL"), "SQL46010", "ALL")); + + // ORDER BY ALL is not allowed inside a WITHIN GROUP ordered-set aggregate. + string inWithinGroup = "SELECT STRING_AGG(c2, ',') WITHIN GROUP (ORDER BY ALL) FROM t1"; + ParserTestUtils.ErrorTestFabricDW(inWithinGroup, new ParserErrorInfo(inWithinGroup.LastIndexOf("ALL"), "SQL46010", "ALL")); + + // ORDER BY ALL is not allowed inside an OVER() window clause with PARTITION BY. + string inOverPartition = "SELECT ROW_NUMBER() OVER (PARTITION BY c2 ORDER BY ALL) FROM t1"; + ParserTestUtils.ErrorTestFabricDW(inOverPartition, new ParserErrorInfo(inOverPartition.LastIndexOf("ALL"), "SQL46010", "ALL")); + + // ORDER BY ALL inside a derived table without TOP / OFFSET / FOR is invalid (SQL46047), + // exactly like any other ORDER BY in that position. + string subqueryNoTop = "SELECT * FROM (SELECT c1, c2 FROM t1 ORDER BY ALL) AS sub"; + ParserTestUtils.ErrorTestFabricDW(subqueryNoTop, new ParserErrorInfo(subqueryNoTop.IndexOf("SELECT", 1), "SQL46047")); + + // ORDER BY ALL is not allowed inside an OVER() window clause with a window frame (ROWS BETWEEN). + string inOverFrame = "SELECT SUM(c1) OVER (ORDER BY ALL ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM t1"; + ParserTestUtils.ErrorTestFabricDW(inOverFrame, new ParserErrorInfo(inOverFrame.IndexOf("ALL"), "SQL46010", "ALL")); + + // ORDER BY ALL is not allowed inside a named WINDOW definition. + string inNamedWindow = "SELECT ROW_NUMBER() OVER w FROM t1 WINDOW w AS (ORDER BY ALL)"; + ParserTestUtils.ErrorTestFabricDW(inNamedWindow, new ParserErrorInfo(inNamedWindow.LastIndexOf("ALL"), "SQL46010", "ALL")); + + // ORDER BY ALL is not allowed inside a named WINDOW definition with PARTITION BY. + string inNamedWindowPartition = "SELECT ROW_NUMBER() OVER w FROM t1 WINDOW w AS (PARTITION BY c2 ORDER BY ALL)"; + ParserTestUtils.ErrorTestFabricDW(inNamedWindowPartition, new ParserErrorInfo(inNamedWindowPartition.LastIndexOf("ALL"), "SQL46010", "ALL")); + + string inJsonArrayAgg = "SELECT JSON_ARRAYAGG(c1 ORDER BY ALL) FROM t1"; + ParserTestUtils.ErrorTestFabricDW(inJsonArrayAgg, new ParserErrorInfo(inJsonArrayAgg.IndexOf("ORDER"), "SQL46010", "ORDER")); + } + /// /// Negative tests for AI_GENERATE_CHUNKS syntax /// diff --git a/Test/SqlDom/ScriptGenerator/BlockStatementTerminatorTests.cs b/Test/SqlDom/ScriptGenerator/BlockStatementTerminatorTests.cs new file mode 100644 index 00000000..208fe119 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/BlockStatementTerminatorTests.cs @@ -0,0 +1,479 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System.Collections.Generic; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the TerminateBlockStatements script-generation option, which controls whether a + // semicolon terminator is written after a BEGIN...END block and after the END CATCH of a + // TRY...CATCH block. When false (the default) these blocks are written without a terminator, + // preserving the previous behavior; when true a semicolon is appended so a terminator supplied + // in the source survives a parse and generate round-trip. + // + // Reported at https://developercommunity.visualstudio.com/t/SSMS-SQL-Formatter-removes-semicolons-af/11126731 + [TestClass] + public class BlockStatementTerminatorTests + { + // Options that opt in to block terminators, leaving everything else at default. + private static SqlScriptGeneratorOptions Terminated() + { + return new SqlScriptGeneratorOptions { TerminateBlockStatements = true }; + } + + // ----------------------------------------------------------------------------------------- + // Default: the option is off, so the existing unterminated form is preserved. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTerminateBlockStatementsDefaultIsFalse() + { + Assert.AreEqual(false, new SqlScriptGeneratorOptions().TerminateBlockStatements); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBlockDefaultDropsSuppliedTerminator() + { + // The reported behavior, retained as the default: a supplied semicolon is not preserved. + const string input = "BEGIN SELECT 1; END;"; + const string expected = +@" +BEGIN + SELECT 1; +END"; + AssertGenerated(input, new SqlScriptGeneratorOptions(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTryCatchDefaultDropsSuppliedTerminator() + { + const string input = "BEGIN TRY SELECT 1; END TRY BEGIN CATCH SELECT ERROR_NUMBER(); END CATCH;"; + const string expected = +@" +BEGIN TRY + SELECT 1; +END TRY +BEGIN CATCH + SELECT ERROR_NUMBER(); +END CATCH"; + AssertGenerated(input, new SqlScriptGeneratorOptions(), expected); + } + + // ----------------------------------------------------------------------------------------- + // Opt in: blocks are terminated. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBlockIsTerminatedWhenOptionIsSet() + { + const string input = "BEGIN SELECT 1; END;"; + const string expected = +@" +BEGIN + SELECT 1; +END;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBlockIsTerminatedEvenWhenSourceOmitsTheTerminator() + { + // The option normalizes to the terminated form; it does not merely preserve what was supplied. + const string input = "BEGIN SELECT 1; END"; + const string expected = +@" +BEGIN + SELECT 1; +END;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestEndCatchIsTerminatedButEndTryIsNot() + { + // END TRY is internal to the TRY...CATCH block, so only END CATCH receives a terminator. + const string input = "BEGIN TRY SELECT 1; END TRY BEGIN CATCH SELECT ERROR_NUMBER(); END CATCH;"; + const string expected = +@" +BEGIN TRY + SELECT 1; +END TRY +BEGIN CATCH + SELECT ERROR_NUMBER(); +END CATCH;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedBlocksInsideProcedureAreTerminated() + { + // The exact scenario from the customer report. + const string input = +@"CREATE PROCEDURE dbo.SemicolonTerminatedBlocks +AS +BEGIN + BEGIN TRY + SELECT 1; + END TRY + BEGIN CATCH + SELECT ERROR_NUMBER(); + END CATCH; +END;"; + const string expected = +@" +CREATE PROCEDURE dbo.SemicolonTerminatedBlocks +AS +BEGIN + BEGIN TRY + SELECT 1; + END TRY + BEGIN CATCH + SELECT ERROR_NUMBER(); + END CATCH; +END;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTerminatedBlockRoundTripsUnchanged() + { + // Generating the already-terminated output again must be a fixed point. + const string expected = +@" +BEGIN + SELECT 1; +END;"; + string once = Generate("BEGIN SELECT 1; END;", Terminated()); + Assert.AreEqual(Normalize(expected).Trim(), Normalize(once).Trim()); + AssertGenerated(once, Terminated(), expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction with the separating semicolon injected before CTEs and THROW. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCteAfterTerminatedBlockDoesNotGetASecondSemicolon() + { + // The block now supplies its own terminator, so the separating semicolon must not be added. + const string input = "BEGIN SELECT 1; END WITH cte AS (SELECT 1 AS c) SELECT c FROM cte;"; + const string expected = +@" +BEGIN + SELECT 1; +END; + +WITH cte +AS (SELECT 1 AS c) +SELECT c +FROM cte;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestThrowAfterTerminatedBlockDoesNotGetASecondSemicolon() + { + const string input = "BEGIN SELECT 1; END THROW 50000, 'x', 1;"; + const string expected = +@" +BEGIN + SELECT 1; +END; + +THROW 50000, 'x', 1;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIfStatementIsStillNotTerminated() + { + // The option opts in only BEGIN...END and TRY...CATCH; IF, WHILE and labels keep their + // existing unterminated form, so the separating semicolon before a CTE is still required. + const string input = "IF 1 = 1 SELECT 1 WITH cte AS (SELECT 1 AS c) SELECT c FROM cte;"; + const string expected = +@" +IF 1 = 1 + SELECT 1; + +WITH cte +AS (SELECT 1 AS c) +SELECT c +FROM cte;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestWhileStatementIsStillNotTerminated() + { + const string input = "WHILE 1 = 1 SELECT 1 WITH cte AS (SELECT 1 AS c) SELECT c FROM cte;"; + const string expected = +@" +WHILE 1 = 1 + SELECT 1; + +WITH cte +AS (SELECT 1 AS c) +SELECT c +FROM cte;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLabelStatementIsStillNotTerminated() + { + const string input = "lbl: SELECT 1;"; + const string expected = +@" +lbl: + +SELECT 1;"; + AssertGenerated(input, Terminated(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestStatementSnippetIsStillNotTerminated() + { + // Snippets are emitted verbatim, so a terminator here would corrupt the preserved text. + // They are not produced by parsing, so the AST is built directly. + var batch = new TSqlBatch(); + batch.Statements.Add(new TSqlStatementSnippet { Script = "EXEC dbo.SomeProc" }); + var script = new TSqlScript(); + script.Batches.Add(batch); + + var generator = new Sql170ScriptGenerator(Terminated()); + generator.GenerateScript(script, out string generated); + Assert.AreEqual("EXEC dbo.SomeProc", Normalize(generated).Trim()); + } + + // ----------------------------------------------------------------------------------------- + // BeginEndAtomicBlockStatement derives from BeginEndBlockStatement, so these pin the + // exact-runtime-type membership test: an atomic block must not follow the option. + // ----------------------------------------------------------------------------------------- + + private const string AtomicProcedure = +@"CREATE PROCEDURE dbo.NativeProc +WITH NATIVE_COMPILATION, SCHEMABINDING +AS +BEGIN ATOMIC WITH (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english') + SELECT 1; +END"; + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAtomicBlockIsTerminatedByDefault() + { + // Atomic blocks are not in StatementsThatCannotHaveSemiColon, so they already carry a + // terminator before this option existed. + const string expected = +@" +CREATE PROCEDURE dbo.NativeProc +WITH NATIVE_COMPILATION, SCHEMABINDING +AS +BEGIN ATOMIC +WITH (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english') + SELECT 1; +END;"; + AssertGenerated(AtomicProcedure, new SqlScriptGeneratorOptions(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAtomicBlockOutputIsUnaffectedByTheOption() + { + const string expected = +@" +CREATE PROCEDURE dbo.NativeProc +WITH NATIVE_COMPILATION, SCHEMABINDING +AS +BEGIN ATOMIC +WITH (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english') + SELECT 1; +END;"; + AssertGenerated(AtomicProcedure, Terminated(), expected); + } + + // ----------------------------------------------------------------------------------------- + // Comment placement: the terminator must land before a trailing comment, not inside it. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTerminatorIsPlacedBeforeTrailingSingleLineComment() + { + const string input = "BEGIN SELECT 1; END -- trailing"; + var options = new SqlScriptGeneratorOptions { TerminateBlockStatements = true, PreserveComments = true }; + const string expected = +@" +BEGIN + SELECT 1; +END; -- trailing"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingCommentPlacementIsUnchangedByDefault() + { + const string input = "BEGIN SELECT 1; END -- trailing"; + var options = new SqlScriptGeneratorOptions { PreserveComments = true }; + const string expected = +@" +BEGIN + SELECT 1; +END -- trailing"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTerminatorIsPlacedBeforeTrailingBlockComment() + { + const string input = "BEGIN SELECT 1; END /* trailing */"; + var options = new SqlScriptGeneratorOptions { TerminateBlockStatements = true, PreserveComments = true }; + const string expected = +@" +BEGIN + SELECT 1; +END; /* trailing */"; + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // The option is honored by every generator version, including Fabric DW and Serverless. + // Each version supplies its own StatementsThatCannotHaveSemiColon, which the gate consults. + // ----------------------------------------------------------------------------------------- + + private static IEnumerable AllGenerators(SqlScriptGeneratorOptions options) + { + yield return new Sql80ScriptGenerator(options); + yield return new Sql90ScriptGenerator(options); + yield return new Sql100ScriptGenerator(options); + yield return new Sql110ScriptGenerator(options); + yield return new Sql120ScriptGenerator(options); + yield return new Sql130ScriptGenerator(options); + yield return new Sql140ScriptGenerator(options); + yield return new Sql150ScriptGenerator(options); + yield return new Sql160ScriptGenerator(options); + yield return new Sql170ScriptGenerator(options); + yield return new Sql180ScriptGenerator(options); + yield return new SqlFabricDWScriptGenerator(options); + yield return new SqlServerlessScriptGenerator(options); + } + + private static TSqlFragment ParseBlock() + { + var parser = new TSql80Parser(true); + TSqlFragment fragment = parser.Parse(new StringReader("BEGIN SELECT 1; END"), out IList errors); + Assert.AreEqual(0, errors.Count, "Input must parse without errors."); + return fragment; + } + + private static void AssertGeneratedBy(SqlScriptGenerator generator, TSqlFragment fragment, string expected) + { + generator.GenerateScript(fragment, out string generated); + Assert.AreEqual(Normalize(expected).Trim(), Normalize(generated).Trim(), generator.GetType().Name); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestEveryGeneratorVersionTerminatesWhenOptionIsSet() + { + // Every version supplies its own StatementsThatCannotHaveSemiColon, so assert the exact + // output for each rather than trusting that the shared gate is reached. + const string expected = +@" +BEGIN + SELECT 1; +END;"; + TSqlFragment fragment = ParseBlock(); + foreach (SqlScriptGenerator generator in AllGenerators(Terminated())) + { + AssertGeneratedBy(generator, fragment, expected); + } + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestEveryGeneratorVersionLeavesBlockUnterminatedByDefault() + { + const string expected = +@" +BEGIN + SELECT 1; +END"; + TSqlFragment fragment = ParseBlock(); + foreach (SqlScriptGenerator generator in AllGenerators(new SqlScriptGeneratorOptions())) + { + AssertGeneratedBy(generator, fragment, expected); + } + } + + // ----------------------------------------------------------------------------------------- + // The oldest parser must accept the terminated form the generator now produces. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSql80GeneratorOutputReparsesWithSql80Parser() + { + const string expected = +@" +BEGIN + SELECT 1; +END;"; + TSqlFragment fragment = ParseBlock(); + + var generator = new Sql80ScriptGenerator(Terminated()); + generator.GenerateScript(fragment, out string generated); + Assert.AreEqual(Normalize(expected).Trim(), Normalize(generated).Trim()); + + var reparser = new TSql80Parser(true); + reparser.Parse(new StringReader(generated), out IList reErrors); + Assert.AreEqual(0, reErrors.Count, "Generated script must reparse without errors. Actual:\n" + generated); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/BuiltInFunctionCasingTests.cs b/Test/SqlDom/ScriptGenerator/BuiltInFunctionCasingTests.cs new file mode 100644 index 00000000..a3216497 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/BuiltInFunctionCasingTests.cs @@ -0,0 +1,780 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the BuiltInFunctionCasing script-generation option. + // + // Expected values follow the IdentifierFormattingTests pattern: verbatim @"..." literals compared + // via the shared AssertGenerated helper (which normalizes line endings and trims). MakeOptions + // sets the casing under test and disables unrelated multi-line/alignment formatting. + // + // Work item: Formatter option: Built-in function name casing + [TestClass] + public class BuiltInFunctionCasingTests + { + // Builds options that set the BuiltInFunctionCasing (and KeywordCasing) under test while + // disabling unrelated multi-line/alignment formatting, so the expected literals stay focused + // on the function-name transformation itself. + private static SqlScriptGeneratorOptions MakeOptions( + BuiltInFunctionCasing casing, + KeywordCasing keywordCasing = KeywordCasing.Uppercase, + bool preserveComments = false) + { + return new SqlScriptGeneratorOptions + { + BuiltInFunctionCasing = casing, + KeywordCasing = keywordCasing, + PreserveComments = preserveComments, + AlignColumnDefinitionFields = false, + AlignClauseBodies = false, + NewLineBeforeFromClause = false, + NewLineBeforeJoinClause = false, + MultilineSelectElementsList = false, + }; + } + + // ----------------------------------------------------------------------------------------- + // Default / backward compatibility + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBuiltInFunctionCasingDefaultIsPreserve() + { + Assert.AreEqual(BuiltInFunctionCasing.Preserve, new SqlScriptGeneratorOptions().BuiltInFunctionCasing); + } + + // Preserve must reproduce the pre-feature output exactly: generic function names keep their + // original casing, while keyword-backed built-ins (CAST, CONVERT, COALESCE) continue to + // follow KeywordCasing as they always have. This is the backward-compatibility sentinel. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPreserveHasZeroImpact() + { + const string input = "SELECT cast(x AS INT), Convert(INT, y), Coalesce(a, b), getdate(), IsNull(a, b);"; + var options = MakeOptions(BuiltInFunctionCasing.Preserve); + const string expected = @"SELECT CAST (x AS INT), CONVERT (INT, y), COALESCE (a, b), getdate(), IsNull(a, b);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Generic FunctionCall names (GETDATE, ISNULL, COUNT, OBJECT_ID, ...) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGenericFunctionUppercase() + { + const string input = "SELECT getdate(), isnull(a, b), object_id('t');"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT GETDATE(), ISNULL(a, b), OBJECT_ID('t');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGenericFunctionLowercase() + { + const string input = "SELECT GETDATE(), ISNULL(A, B), OBJECT_ID('t');"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT getdate(), isnull(A, B), object_id('t');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGenericFunctionPascalCase() + { + // PascalCase capitalizes the first letter and lowercases the rest (matching the shared + // PascalCase helper used by KeywordCasing/IdentifierCasing); underscores are preserved. + const string input = "SELECT GETDATE(), object_id('t');"; + var options = MakeOptions(BuiltInFunctionCasing.PascalCase); + const string expected = @"SELECT Getdate(), Object_id('t');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMixedCaseInputIsNormalized() + { + const string input = "SELECT GetDate(), IsNull(a, b);"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT GETDATE(), ISNULL(a, b);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Aggregate functions + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAggregateFunctions() + { + const string input = "SELECT count(*), sum(a), max(b), min(c), avg(d) FROM t;"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT COUNT(*), SUM(a), MAX(b), MIN(c), AVG(d) FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestWindowedAggregate() + { + const string input = "SELECT count(*) OVER (PARTITION BY a) FROM t;"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT count(*) OVER (PARTITION BY a) FROM t;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Dedicated built-in nodes (CAST, CONVERT, COALESCE, NULLIF, IIF, LEFT, RIGHT, TRY_*) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCastLowercase() + { + const string input = "SELECT CAST(x AS INT);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT cast (x AS INT);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestConvertLowercase() + { + const string input = "SELECT CONVERT(INT, y, 1);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT convert (INT, y, 1);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCoalesceAndNullIfLowercase() + { + const string input = "SELECT COALESCE(a, b), NULLIF(a, b);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT coalesce (a, b), nullif (a, b);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIIfLowercase() + { + const string input = "SELECT IIF(a > b, 1, 0);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT iif (a > b, 1, 0);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeftAndRightLowercase() + { + const string input = "SELECT LEFT(s, 1), RIGHT(s, 1);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT left(s, 1), right(s, 1);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTryCastAndTryConvertLowercase() + { + const string input = "SELECT TRY_CAST(x AS INT), TRY_CONVERT(INT, y);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT try_cast (x AS INT), try_convert (INT, y);"; + + AssertGenerated(input, options, expected); + } + + // PascalCase on the dedicated (keyword/literal-backed) built-in nodes: the shared PascalCase + // helper lowercases the whole name then capitalizes the first letter, so CAST -> Cast and + // TRY_CONVERT -> Try_convert. LEFT/RIGHT emit without a space before '(' while the other + // dedicated nodes keep the pre-existing space. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDedicatedNodesPascalCase() + { + const string input = "SELECT CAST(x AS INT), CONVERT(INT, y), COALESCE(a, b), NULLIF(a, b), IIF(a > b, 1, 0), LEFT(s, 1), RIGHT(s, 1), TRY_CAST(x AS INT), TRY_CONVERT(INT, y);"; + var options = MakeOptions(BuiltInFunctionCasing.PascalCase); + const string expected = @"SELECT Cast (x AS INT), Convert (INT, y), Coalesce (a, b), Nullif (a, b), Iif (a > b, 1, 0), Left(s, 1), Right(s, 1), Try_cast (x AS INT), Try_convert (INT, y);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction rule: takes precedence over KeywordCasing for function names, so the two can be + // set to different casings. + // ----------------------------------------------------------------------------------------- + + // KeywordCasing lowercases keywords, but built-in function names follow their own option. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndependentOfKeywordCasing_KeywordsLowerFunctionsUpper() + { + const string input = "select getdate(), coalesce(a, b) from t;"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase, KeywordCasing.Lowercase); + const string expected = @"select GETDATE(), COALESCE (a, b) from t;"; + + AssertGenerated(input, options, expected); + } + + // KeywordCasing uppercases keywords, but built-in function names follow their own option. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndependentOfKeywordCasing_KeywordsUpperFunctionsLower() + { + const string input = "select GETDATE(), COALESCE(a, b) from t;"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, KeywordCasing.Uppercase); + const string expected = @"SELECT getdate(), coalesce (a, b) FROM t;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction rule: AS inside CAST follows KeywordCasing, not BuiltInFunctionCasing + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCastAsKeywordFollowsKeywordCasing() + { + // Function name CAST -> uppercase (BuiltInFunctionCasing); AS -> lowercase (KeywordCasing). + const string input = "SELECT CAST(x AS INT);"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase, KeywordCasing.Lowercase); + const string expected = @"select CAST (x as int);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction rule: data type names are not affected + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDataTypeNamesNotAffected() + { + // BuiltInFunctionCasing is Lowercase, but the INT / VARCHAR data type names follow + // KeywordCasing (Uppercase here), not the function-casing option. + const string input = "SELECT CAST(x AS INT), CONVERT(VARCHAR(10), y);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, KeywordCasing.Uppercase); + const string expected = @"SELECT cast (x AS INT), convert (VARCHAR (10), y);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction rule: only qualified / delimited names are preserved + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSchemaQualifiedFunctionNotAffected() + { + // Schema-qualified => user-defined, even if the name matches a built-in. + const string input = "SELECT dbo.GetDate(), dbo.Count(a);"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT dbo.GetDate(), dbo.Count(a);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestUnqualifiedUnknownFunctionIsRecased() + { + // Unrecognized one-part names are re-cased too. That is safe rather than merely + // unavoidable: SQL Server rejects a one-part scalar function call ("'MyCustomFunc' is not + // a recognized built-in function name"), so no executable script reaches this path with a + // UDF name. TestSchemaQualifiedFunctionNotAffected covers the callable two-part form. + const string input = "SELECT MyCustomFunc(a), fn_MyHelper(b);"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT MYCUSTOMFUNC(a), FN_MYHELPER(b);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDelimitedFunctionNameNotAffected() + { + // A delimited (bracketed) name is treated as an identifier / UDF and left untouched. + const string input = "SELECT [GETDATE]();"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT [GETDATE]();"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMethodCallOnVariableOrColumnNotAffected() + { + // CLR/spatial/XML method invocations parse as FunctionCall with a non-null CallTarget, + // so they take the same qualified-call exit as dbo.MyFunc() and keep their casing. + const string input = "SELECT @g.STArea(), x.value('(/a)[1]', 'int');"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT @g.STArea(), x.value('(/a)[1]', 'int');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTableValuedFunctionNameNotAffected() + { + // A TVF in a FROM clause is a SchemaObjectFunctionTableReference, not a FunctionCall, so + // it never reaches the re-casing path - including the one-part form, which (unlike a + // scalar UDF) T-SQL does resolve against the default schema. + const string input = "SELECT * FROM MyTvf(1) AS t CROSS APPLY dbo.OtherTvf(t.a) AS u;"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT * FROM MyTvf(1) AS t CROSS APPLY dbo.OtherTvf(t.a) AS u;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Nested and mixed usage + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedBuiltInFunctions() + { + const string input = "SELECT isnull(convert(varchar(20), getdate()), 'n/a');"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT ISNULL(CONVERT (VARCHAR (20), GETDATE()), 'n/a');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBuiltInMixedWithUdf() + { + // Built-ins re-cased, the qualified UDF left alone, in a single expression. + const string input = "SELECT getdate(), dbo.MyFunc(datediff(day, a, b));"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT GETDATE(), dbo.MyFunc(DATEDIFF(day, a, b));"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // System / error functions + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSystemFunctions() + { + const string input = "SELECT error_number(), error_message(), newid();"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT ERROR_NUMBER(), ERROR_MESSAGE(), NEWID();"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Dedicated conversion nodes: PARSE / TRY_PARSE (mirror the CAST / CONVERT family) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestParseAndTryParseLowercase() + { + // PARSE / TRY_PARSE are keyword-backed conversion built-ins like CAST/CONVERT: the name + // follows BuiltInFunctionCasing (lower) while AS and the data type follow KeywordCasing. + const string input = "SELECT PARSE('42' AS INT), TRY_PARSE('42' AS INT);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT parse ('42' AS INT), try_parse ('42' AS INT);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Built-in AI_* scalar functions (SQL Server 2025 / 170) follow BuiltInFunctionCasing + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAiFunctionNameUppercase() + { + // The AI_* function name is a built-in and is re-cased; USE / MODEL and the model name + // keep their own rules (KeywordCasing / IdentifierCasing). + const string input = "SELECT ai_generate_embeddings('t' USE MODEL MyModel);"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = @"SELECT AI_GENERATE_EMBEDDINGS('t' USE MODEL MyModel);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAiFunctionNameLowercase() + { + const string input = "SELECT AI_GENERATE_EMBEDDINGS('t' USE MODEL MyModel);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT ai_generate_embeddings('t' USE MODEL MyModel);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestInvokeExternalApiFunctionNameLowercase() + { + const string input = "SELECT INVOKE_EXTERNAL_API('MySet', 'MyFunc', 1);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT invoke_external_api('MySet', 'MyFunc', 1);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Out-of-scope constructs: niladic system functions and built-in table-valued functions + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestParameterlessSystemFunctionsNotAffected() + { + // Keyword-form niladic functions are emitted as keywords and are NOT re-cased by + // BuiltInFunctionCasing; they continue to follow KeywordCasing (Uppercase here). + const string input = "SELECT current_timestamp, system_user, current_user;"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, KeywordCasing.Uppercase); + const string expected = @"SELECT CURRENT_TIMESTAMP, SYSTEM_USER, CURRENT_USER;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBuiltInTableValuedFunctionNotAffected() + { + // Built-in table-valued functions flow through table-reference nodes, not FunctionCall, + // so their names are governed by IdentifierCasing and are NOT re-cased. + const string input = "SELECT * FROM STRING_SPLIT('a,b,c', ',');"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT * FROM STRING_SPLIT ('a,b,c', ',');"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Out-of-scope constructs: keyword-operator forms. Each is its own AST node rather than a + // FunctionCall, so none of them reaches the re-casing helper. These pin that boundary. + // ----------------------------------------------------------------------------------------- + + // Asserts the option leaves a construct untouched by comparing output with it off and on, + // so the assertion does not depend on unrelated layout options. Names in sql must be + // uppercase or mixed case, otherwise lowercasing would be invisible. + private static void AssertNotAffectedByCasing(string sql) + { + Assert.AreEqual( + Generate(sql, MakeOptions(BuiltInFunctionCasing.Preserve)), + Generate(sql, MakeOptions(BuiltInFunctionCasing.Lowercase))); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentityFunctionNotAffected() + { + AssertNotAffectedByCasing("SELECT IDENTITY(INT, 1, 1) AS id INTO t2 FROM t;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAtTimeZoneNotAffected() + { + AssertNotAffectedByCasing("SELECT d AT TIME ZONE 'UTC' FROM t;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNextValueForNotAffected() + { + AssertNotAffectedByCasing("SELECT NEXT VALUE FOR dbo.MySeq;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPartitionFunctionNotAffected() + { + AssertNotAffectedByCasing("SELECT $PARTITION.MyRangeFn(1);"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOdbcFunctionCallNotAffected() + { + AssertNotAffectedByCasing("SELECT {fn NOW()};"); + } + + // ----------------------------------------------------------------------------------------- + // Remaining guard branches on the generic FunctionCall path + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDoubleQuotedFunctionNameNotAffected() + { + // The guard is QuoteType != NotQuoted, so double-quoted names are preserved just like + // bracketed ones. + const string input = "SELECT \"GETDATE\"();"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = "SELECT \"GETDATE\"();"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Generic FunctionCall nodes that branch on the function name to emit a custom body. + // Re-casing the emitted name must not disturb that body generation, because the branches + // dispatch on the unmodified AST value (node.FunctionName.Value). + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestJsonConstructorFunctionsAreRecased() + { + const string input = "SELECT JSON_OBJECT('a':'1'), JSON_ARRAY(1, 2);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT json_object('a':'1'), json_array(1, 2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrimWithOptionsIsRecased() + { + // The two-argument TRIM form keeps its LEADING/TRAILING/BOTH keyword and FROM body. + const string input = "SELECT TRIM(LEADING ' ' FROM s);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT trim( LEADING ' ' FROM s);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction with PreserveComments. Re-casing emits the function name as a raw token rather + // than as a fragment, so the comment hooks have to be driven explicitly; without them a + // comment trailing the name is absorbed into the argument list or dropped entirely. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommentAfterFunctionNameStaysWithName() + { + const string input = "SELECT LEN /*c*/ (x);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, preserveComments: true); + const string expected = @"SELECT len /*c*/(x);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommentAfterParameterlessFunctionNameIsPreserved() + { + // A zero-argument call has no following fragment inside the parentheses, so the comment + // has nowhere to migrate to and would be lost outright without the trailing-comment hook. + const string input = "SELECT GETDATE /*c*/ ();"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, preserveComments: true); + const string expected = @"SELECT getdate /*c*/();"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommentBeforeFunctionNameIsPreserved() + { + // Exercises the leading hook; the trailing-comment tests above only cover the other side. + const string input = "SELECT /*c*/ LEN(x);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, preserveComments: true); + const string expected = @"SELECT /*c*/ +len(x);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Fabric DW dialect. The helper lives on the shared SqlScriptGeneratorVisitor base, so every + // derived generator inherits it; these also cover the seven AI_* functions that the SQL-170 + // grammar does not accept. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFabricDwGenericFunctionLowercase() + { + const string input = "SELECT GETDATE(), ISNULL(a, b);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = @"SELECT getdate(), isnull(a, b);"; + + AssertGeneratedFabric(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFabricDwAiFunctionNamesLowercase() + { + const string input = + "SELECT AI_ANALYZE_SENTIMENT('text'), AI_CLASSIFY('text', 'spam', 'ham'), " + + "AI_EXTRACT('text', 'spam', 'ham'), AI_FIX_GRAMMAR('text');"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase); + const string expected = + @"SELECT ai_analyze_sentiment('text'), ai_classify('text', 'spam', 'ham'), ai_extract('text', 'spam', 'ham'), ai_fix_grammar('text');"; + + AssertGeneratedFabric(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFabricDwAiFunctionNamesUppercase() + { + const string input = + "SELECT ai_generate_response('Hello'), ai_summarize('text'), ai_translate('text', 'es');"; + var options = MakeOptions(BuiltInFunctionCasing.Uppercase); + const string expected = + @"SELECT AI_GENERATE_RESPONSE('Hello'), AI_SUMMARIZE('text'), AI_TRANSLATE('text', 'es');"; + + AssertGeneratedFabric(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Dedicated built-in forms outside the scalar-expression path: the TSEQUAL predicate and the + // aggregate name in a COMPUTE clause. Both name a built-in function, so both follow the + // option rather than KeywordCasing or a fixed-case literal. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTSEqualLowercase() + { + const string input = "SELECT * FROM t WHERE TSEQUAL(c1, c2);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, KeywordCasing.Uppercase); + const string expected = @"SELECT * FROM t +WHERE tsequal (c1, c2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTSEqualPreserveIsUnchanged() + { + const string input = "SELECT * FROM t WHERE tsequal(c1, c2);"; + var options = MakeOptions(BuiltInFunctionCasing.Preserve, KeywordCasing.Uppercase); + const string expected = @"SELECT * FROM t +WHERE TSEQUAL (c1, c2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestComputeClauseAggregateLowercase() + { + const string input = "SELECT a FROM t COMPUTE SUM(a);"; + var options = MakeOptions(BuiltInFunctionCasing.Lowercase, KeywordCasing.Uppercase); + const string expected = @"SELECT a FROM t +COMPUTE sum(a);"; + + AssertGenerated100(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestComputeClauseAggregatePreserveIsUnchanged() + { + // Preserve must keep the historical fixed-case literal, not the input's casing. + const string input = "SELECT a FROM t COMPUTE sum(a);"; + var options = MakeOptions(BuiltInFunctionCasing.Preserve, KeywordCasing.Uppercase); + const string expected = @"SELECT a FROM t +COMPUTE SUM(a);"; + + AssertGenerated100(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs b/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs index 7de4b8dd..f42cb4c3 100644 --- a/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs +++ b/Test/SqlDom/ScriptGenerator/ClauseBodyAlignmentTests.cs @@ -201,6 +201,113 @@ ORDER BY AssertGenerated(input, options, expected); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedLegacyGroupByAllColumnsStillIndent() + { + // Legacy GROUP BY ALL (accepted by the box parsers too): ALL stays on the + // GROUP BY line as a keyword modifier, but the explicit column list still drops to its + // own indented lines under Indented layout. + const string input = "SELECT a, COUNT(*) FROM t GROUP BY ALL a, b;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + a, + COUNT(*) +FROM + t +GROUP BY ALL + a, b;"; + + AssertGenerated(input, options, expected); + } + + // --- GROUP BY ALL / ORDER BY ALL shorthands (Fabric DW first syntax) ---------------------- + // GROUP BY ALL (no column list) and ORDER BY ALL are Fabric DW first, so these go through the + // Fabric DW pipeline (AssertGeneratedFabric). They confirm the ALL keyword is a clause-keyword + // modifier that stays on the GROUP BY / ORDER BY line under both Aligned and Indented layouts. + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedGroupByAll() + { + // Aligned: clause bodies line up under the widest keyword that has a body (here SELECT / + // FROM). The ALL shorthand has no body, so GROUP BY does not widen the alignment column; + // ALL simply stays on the GROUP BY line. + const string input = "SELECT City, COUNT(*) AS NumEmps FROM dbo.Employees GROUP BY ALL;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL;"; + + AssertGeneratedFabric(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedGroupByAllKeepsAllInline() + { + // Indented: every clause body drops to its own indented line, but the ALL shorthand is a + // keyword modifier, so it stays on the GROUP BY line (no empty indented body line). + const string input = "SELECT City, COUNT(*) AS NumEmps FROM dbo.Employees GROUP BY ALL;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + City, + COUNT(*) AS NumEmps +FROM + dbo.Employees +GROUP BY ALL;"; + + AssertGeneratedFabric(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignedOrderByAll() + { + const string input = "SELECT c1, c2 FROM t1 ORDER BY ALL;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Aligned }; + const string expected = +@" +SELECT c1, + c2 +FROM t1 +ORDER BY ALL;"; + + AssertGeneratedFabric(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedOrderByAllKeepsAllInline() + { + // Indented: the ALL shorthand (with its optional sort order) stays on the ORDER BY line + // rather than being pushed onto its own indented line. + const string input = "SELECT c1, c2 FROM t1 ORDER BY ALL DESC;"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +SELECT + c1, + c2 +FROM + t1 +ORDER BY ALL DESC;"; + + AssertGeneratedFabric(input, options, expected); + } + // --- Nested derived table (the motivating case: linear growth vs. rightward drift) ------- [TestMethod] diff --git a/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs b/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs new file mode 100644 index 00000000..c48dc771 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs @@ -0,0 +1,606 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + [TestClass] + public class CommaPlacementTests + { + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementDefaultIsTrailing() + { + Assert.AreEqual(CommaPlacement.Trailing, new SqlScriptGeneratorOptions().CommaPlacement); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSelectList() + { + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading }; + const string expected = @" +SELECT a + , b + , c +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingSelectList() + { + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Trailing }; + const string expected = @" +SELECT a, + b, + c +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingParenthesizedList() + { + const string input = "CREATE TABLE t (a INT, b INT, c INT);"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading }; + const string expected = @" +CREATE TABLE t ( + a INT + , b INT + , c INT +);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingParenthesizedList() + { + const string input = "CREATE TABLE t (a INT, b INT, c INT);"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Trailing }; + const string expected = @" +CREATE TABLE t ( + a INT, + b INT, + c INT +);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertTargets() + { + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertTargetsList = true, + }; + const string expected = @" +INSERT INTO t ( + a + , b + , c +) +VALUES (1, 2, 3);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingInsertTargets() + { + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineInsertTargetsList = true, + }; + const string expected = @" +INSERT INTO t ( + a, + b, + c +) +VALUES (1, 2, 3);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertSources() + { + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertSourcesList = true, + MultilineInsertTargetsList = true, + }; + const string expected = @" +INSERT INTO t ( + a + , b + , c +) +VALUES (1, 2, 3) + , (4, 5, 6) + , (7, 8, 9);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingInsertSources() + { + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineInsertSourcesList = true, + }; + const string expected = @" +INSERT INTO t (a, b, c) +VALUES (1, 2, 3), + (4, 5, 6), + (7, 8, 9);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingViewColumns() + { + const string input = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineViewColumnsList = true, + }; + const string expected = @" +CREATE VIEW v ( + a + , b + , c +) +AS +SELECT 1 + , 2 + , 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingViewColumns() + { + const string input = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineViewColumnsList = true, + }; + const string expected = @" +CREATE VIEW v ( + a, + b, + c +) +AS +SELECT 1, + 2, + 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSetClauseItems() + { + const string input = "UPDATE t SET a = 1, b = 2, c = 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSetClauseItems = true, + }; + const string expected = @" +UPDATE t +SET a = 1 + , b = 2 + , c = 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingSetClauseItems() + { + const string input = "UPDATE t SET a = 1, b = 2, c = 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineSetClauseItems = true, + }; + const string expected = @" +UPDATE t +SET a = 1, + b = 2, + c = 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSingleColumnHasNoComma() + { + const string input = "SELECT a FROM t;"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading }; + const string expected = @" +SELECT a +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingWithPreserveCommentsDoesNotAbsorbComma() + { + // A line comment after an element must not absorb the following leading comma. + const string input = @"SELECT col1, -- first column + col2, -- second column + col3 +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + PreserveComments = true, + }; + const string expected = @" +SELECT col1 -- first column + , col2 -- second column + , col3 +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingWithPreserveCommentsKeepsCommentsAfterComma() + { + const string input = @"SELECT col1, -- first column + col2, -- second column + col3 +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + PreserveComments = true, + }; + const string expected = @" +SELECT col1, -- first column + col2, -- second column + col3 +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingWithCommentBeforeCommaForcesNewLine() + { + const string input = @"SELECT col1 -- first column +, col2 +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + PreserveComments = true, + }; + const string expected = @" +SELECT col1, -- first column + col2 +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSelectListMultilineFalse() + { + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSelectElementsList = false, + }; + const string expected = @" +SELECT a, b, c +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingViewColumnsMultilineFalse() + { + const string input = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineViewColumnsList = false, + MultilineSelectElementsList = false, + }; + const string expected = @" +CREATE VIEW v (a, b, c) +AS +SELECT 1, 2, 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSetClauseItemsMultilineFalse() + { + const string input = "UPDATE t SET a = 1, b = 2, c = 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSetClauseItems = false, + }; + const string expected = @" +UPDATE t +SET a = 1, b = 2, c = 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertTargetsMultilineFalse() + { + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertTargetsList = false, + }; + const string expected = @" +INSERT INTO t (a, b, c) +VALUES (1, 2, 3);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingInsertSourcesMultilineFalse() + { + // VALUES rows remain multiline even when MultilineInsertSourcesList is false. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineInsertSourcesList = false, + }; + const string expected = @" +INSERT INTO t (a, b, c) +VALUES (1, 2, 3) + , (4, 5, 6) + , (7, 8, 9);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingParenthesizedListAlwaysMultiline() + { + // CREATE TABLE columns have no single-line toggle. + const string input = "CREATE TABLE t (a INT, b INT, c INT);"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading }; + const string expected = @" +CREATE TABLE t ( + a INT + , b INT + , c INT +);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingIndentedOptionList() + { + // Exercises the indented comma-list path used by WITH parameters. + const string input = "CREATE COLUMN MASTER KEY CMK1 WITH (KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE', KEY_PATH = 'some/path');"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading }; + const string expected = @" +CREATE COLUMN MASTER KEY CMK1 +WITH ( + KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE' + , KEY_PATH = 'some/path' +);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSetClauseItemsIndented() + { + const string input = "UPDATE t SET a = 1, b = 2, c = 3;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineSetClauseItems = true, + IndentSetClause = true, + }; + const string expected = @" +UPDATE t + SET a = 1 + , b = 2 + , c = 3;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingCreateTableWithComments() + { + // Exercises preserved line comments in the indented leading-comma path. + const string input = @"CREATE TABLE t (a INT, -- first +b INT, -- second +c INT);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + PreserveComments = true, + }; + const string expected = @" +CREATE TABLE t ( + a INT -- first + , b INT -- second + , c INT +);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingWithBlockCommentTrailingElement() + { + // Block comments use the inline path rather than the deferred line-comment path. + const string input = "SELECT a /* note */, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + PreserveComments = true, + }; + const string expected = @" +SELECT a /* note */ + , b + , c +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSpaceCountDefaultIsOne() + { + Assert.AreEqual(1, new SqlScriptGeneratorOptions().LeadingCommaSpaceCount); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSpaceCountAboveOneClampsToOne() + { + Assert.AreEqual(1, new SqlScriptGeneratorOptions { LeadingCommaSpaceCount = 2 }.LeadingCommaSpaceCount); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommaSpaceCountZeroInSelectList() + { + const string input = "SELECT a, b, c FROM t;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + LeadingCommaSpaceCount = 0, + }; + const string expected = @" +SELECT a + ,b + ,c +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommaSpaceCountZeroInCreateTableColumns() + { + const string input = "CREATE TABLE t (a INT, b INT, c INT);"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + LeadingCommaSpaceCount = 0, + }; + const string expected = @" +CREATE TABLE t ( + a INT + ,b INT + ,c INT +);"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingSpaceCountOne() + { + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + LeadingCommaSpaceCount = 1, + }; + const string selectInput = "SELECT a, b, c FROM t;"; + const string selectExpected = @" +SELECT a + , b + , c +FROM t;"; + AssertGenerated(selectInput, options, selectExpected); + + const string tableInput = "CREATE TABLE t (a INT, b INT, c INT);"; + const string tableExpected = @" +CREATE TABLE t ( + a INT + , b INT + , c INT +);"; + AssertGenerated(tableInput, options, tableExpected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/FunctionCallFormattingTests.cs b/Test/SqlDom/ScriptGenerator/FunctionCallFormattingTests.cs new file mode 100644 index 00000000..27c9d909 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/FunctionCallFormattingTests.cs @@ -0,0 +1,467 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + [TestClass] + public class FunctionCallFormattingTests + { + private static SqlScriptGeneratorOptions MakeOptions() + { + return new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + MultilineSelectElementsList = false, + PreserveComments = true, + }; + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionCallFormattingDefaultsPreserveExistingOutput() + { + var defaults = new SqlScriptGeneratorOptions(); + Assert.IsFalse(defaults.MultilineNestedFunctionCalls); + + const string input = "SELECT REPLACE(value, 'x', 'y');"; + const string expected = "SELECT REPLACE(value, 'x', 'y');"; + + AssertGenerated(input, MakeOptions(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedFunctionCallsRemainCompactByDefault() + { + const string input = "SELECT REPLACE(LOWER(value), 'x', 'y');"; + const string expected = "SELECT REPLACE(LOWER(value), 'x', 'y');"; + + AssertGenerated(input, MakeOptions(), expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNestedFunctionCallsPreservesParameterComments() + { + const string input = +@" +SELECT TRIM( +REPLACE( +TRANSLATE( +city, +'0123456789', -- source characters +'~~~~~~~~~~' -- replacement characters +), +'~', '' +) +);"; + var options = MakeOptions(); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.MultilineNestedFunctionCalls = true; + + const string expected = +@" +SELECT + TRIM ( + REPLACE ( + TRANSLATE ( + city, + '0123456789', -- source characters + '~~~~~~~~~~' -- replacement characters + ), + '~', + '' + ) + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNestedFunctionCallsAlignsLeadingParameterComment() + { + const string input = +@" +SELECT REPLACE( +-- normalize value +LOWER(value), +'x', +'y' +);"; + var options = MakeOptions(); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.MultilineNestedFunctionCalls = true; + + const string expected = +@" +SELECT + REPLACE ( + -- normalize value + LOWER (value), + 'x', + 'y' + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNestedFunctionCallsWithAlignedClauseBodies() + { + const string input = "SELECT TRIM(REPLACE(city, 'x', 'y')) AS result FROM addresses WHERE city IS NOT NULL;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Aligned, + MultilineNestedFunctionCalls = true, + }; + + const string expected = +@" +SELECT TRIM ( + REPLACE ( + city, + 'x', + 'y' + ) + ) AS result +FROM addresses +WHERE city IS NOT NULL;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNestedFunctionCallsWithIndentedClauseBodies() + { + const string input = "SELECT TRIM(REPLACE(city, 'x', 'y')) AS result FROM addresses WHERE city IS NOT NULL;"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + MultilineNestedFunctionCalls = true, + }; + + const string expected = +@" +SELECT + TRIM ( + REPLACE ( + city, + 'x', + 'y' + ) + ) AS result +FROM + addresses +WHERE + city IS NOT NULL;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNestedFunctionCallsNewLineBeforeOpenParenthesis() + { + const string input = "SELECT REPLACE(LOWER(value), 'x', 'y');"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + options.NewLineBeforeOpenParenthesisInMultilineList = true; + + const string expected = +@" +SELECT REPLACE + ( + LOWER + (value), + 'x', + 'y' + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineNestedFunctionCallsNoNewLineBeforeCloseParenthesis() + { + const string input = "SELECT REPLACE(LOWER(value), 'x', 'y');"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + options.NewLineBeforeCloseParenthesisInMultilineList = false; + + const string expected = +@" +SELECT REPLACE ( + LOWER (value), + 'x', + 'y');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIsolatedFunctionCallRemainsCompact() + { + const string input = "SELECT REPLACE(value, 'x', 'y');"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + const string expected = "SELECT REPLACE(value, 'x', 'y');"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestFunctionCallNestedInsideParenthesesUsesMultilineLayout() + { + const string input = "SELECT REPLACE((LOWER(value)), 'x', 'y');"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + + const string expected = +@" +SELECT REPLACE ( + (LOWER (value)), + 'x', + 'y' + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedParameterlessFunctionCallRemainsCompact() + { + const string input = "SELECT REPLACE(GETDATE(), 'x', 'y');"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + + const string expected = +@" +SELECT REPLACE ( + GETDATE(), + 'x', + 'y' + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingParameterCommentForcesNewLineWithCompactFunctionCalls() + { + const string input = +@" +SELECT TRANSLATE(city, +'a', -- source characters +'b' -- replacement characters +);"; + var options = MakeOptions(); + + const string expected = +@" +SELECT TRANSLATE(city, 'a', -- source characters +'b' -- replacement characters +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeftFunctionCallCommentBeforeCommaForcesNewLine() + { + const string input = +@" +SELECT LEFT(value -- input value +, 2);"; + var options = MakeOptions(); + + const string expected = +@" +SELECT LEFT(value, -- input value +2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestRightFunctionCallCommentBeforeClosingParenthesisForcesNewLine() + { + const string input = +@" +SELECT RIGHT(value, 2 -- character count +);"; + var options = MakeOptions(); + + const string expected = +@" +SELECT RIGHT(value, 2 -- character count +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestSyntaxSpecialFunctionsRemainValidWhenNestedFormattingIsEnabled() + { + const string input = "SELECT TRIM(BOTH 'x' FROM value), JSON_OBJECT('a':1);"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + + const string expected = "SELECT TRIM( BOTH 'x' FROM value), JSON_OBJECT('a':1);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrimPreservesCommentBeforeFromClause() + { + const string input = +@" +SELECT TRIM(BOTH 'x' -- trim character +FROM LOWER(value));"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + + const string expected = +@" +SELECT TRIM( BOTH 'x' -- trim character +FROM LOWER(value));"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeftAndRightFunctionCallsUseNestedFormattingOnlyWhenNeeded() + { + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + + AssertGenerated( + "SELECT LEFT(value, 2), RIGHT(value, 2);", + options, + "SELECT LEFT(value, 2), RIGHT(value, 2);"); + + const string leftInput = "SELECT REPLACE(LEFT(LOWER(value), 2), 'x', 'y');"; + const string leftExpected = +@" +SELECT REPLACE ( + LEFT ( + LOWER (value), + 2 + ), + 'x', + 'y' + );"; + AssertGenerated(leftInput, options, leftExpected); + + const string rightInput = "SELECT REPLACE(RIGHT(UPPER(value), 2), 'x', 'y');"; + const string rightExpected = +@" +SELECT REPLACE ( + RIGHT ( + UPPER (value), + 2 + ), + 'x', + 'y' + );"; + AssertGenerated(rightInput, options, rightExpected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestJsonSpecialSyntaxRemainsValidWithNestedFunctionArguments() + { + const string input = +@" +SELECT + JSON_OBJECTAGG('name':LOWER(value)), + JSON_ARRAY(LOWER(value), 2), + JSON_ARRAYAGG(LOWER(value) ORDER BY value), + JSON_QUERY(LOWER(value), '$' WITH ARRAY WRAPPER), + JSON_VALUE(LOWER(value), '$' RETURNING INT);"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + options.MultilineSelectElementsList = true; + + const string expected = +@" +SELECT JSON_OBJECTAGG('name':LOWER(value)), + JSON_ARRAY(LOWER(value), 2), + JSON_ARRAYAGG(LOWER(value) ORDER BY value), + JSON_QUERY(LOWER(value), '$' WITH ARRAY WRAPPER), + JSON_VALUE(LOWER(value), '$' RETURNING INT);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDistinctAndAllFunctionCallsRemainCompact() + { + const string input = "SELECT COUNT(DISTINCT LOWER(value)), SUM(ALL ABS(value));"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + const string expected = "SELECT COUNT(DISTINCT LOWER(value)), SUM(ALL ABS(value));"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineFunctionCallPreservesNullHandlingAndOverClause() + { + const string input = "SELECT FIRST_VALUE(LOWER(Measure)) IGNORE NULLS OVER ();"; + var options = MakeOptions(); + options.MultilineNestedFunctionCalls = true; + + const string expected = +@" +SELECT FIRST_VALUE ( + LOWER (Measure) + ) IGNORE NULLS OVER ();"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/GroupByElementsListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/GroupByElementsListFormattingTests.cs new file mode 100644 index 00000000..38ef05fc --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/GroupByElementsListFormattingTests.cs @@ -0,0 +1,225 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + [TestClass] + public class GroupByElementsListFormattingTests + { + private static SqlScriptGeneratorOptions MakeOptions(bool multiline) + { + return new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + MultilineGroupByElementsList = multiline, + MultilineSelectElementsList = false, + }; + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsGroupByElementsOnOneLine() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + var options = new SqlScriptGeneratorOptions { MultilineSelectElementsList = false }; + const string expected = @" +SELECT a, b, COUNT(*) +FROM t +GROUP BY a, b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGroupByElementsStayOnOneLineWhenDisabled() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(false); + const string expected = @" +SELECT a, b, COUNT(*) +FROM t +GROUP BY a, b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGroupByElementsAreMultilineWhenEnabled() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b, COUNT(*) +FROM t +GROUP BY a, + b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineGroupByElementsWithIndentedClauseBodies() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + const string expected = @" +SELECT + a, b, COUNT(*) +FROM + t +GROUP BY + a, + b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineLegacyGroupByAllElements() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY ALL a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b, COUNT(*) +FROM t +GROUP BY ALL a, + b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineGroupByElementsBeforeWithCube() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b WITH CUBE;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b, COUNT(*) +FROM t +GROUP BY a, + b WITH CUBE;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineGroupByElementsHonorLeadingCommaPlacement() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT a, b, COUNT(*) +FROM t +GROUP BY a + , b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedMultilineGroupByElementsHonorLeadingCommaPlacement() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT + a, b, COUNT(*) +FROM + t +GROUP BY + a + , b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommasWithMultilineSelectAndIndentedGroupByElements() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.MultilineSelectElementsList = true; + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT + a + , b + , COUNT(*) +FROM + t +GROUP BY + a + , b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingCommasWithMultilineSelectAndAlignedGroupByElements() + { + const string input = "SELECT a, b, COUNT(*) FROM t GROUP BY a, b;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.MultilineSelectElementsList = true; + options.ClauseBodyAlignment = ClauseBodyAlignment.Aligned; + options.AlignClauseBodies = true; + options.CommaPlacement = CommaPlacement.Trailing; + const string expected = @" +SELECT a, + b, + COUNT(*) +FROM t +GROUP BY a, + b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineGroupByOnlySplitsTopLevelElements() + { + const string input = "SELECT a, b, c, COUNT(*) FROM t GROUP BY ROLLUP(a, b), c;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b, c, COUNT(*) +FROM t +GROUP BY ROLLUP(a, b), + c;"; + + AssertGenerated(input, options, expected); + } + } +} \ No newline at end of file diff --git a/Test/SqlDom/ScriptGenerator/HavingPredicatesListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/HavingPredicatesListFormattingTests.cs new file mode 100644 index 00000000..b11c4ef0 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/HavingPredicatesListFormattingTests.cs @@ -0,0 +1,180 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + [TestClass] + public class HavingPredicatesListFormattingTests + { + private static SqlScriptGeneratorOptions MakeOptions(bool multiline) + { + return new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + MultilineHavingPredicatesList = multiline, + MultilineSelectElementsList = false, + MultilineWherePredicatesList = false, + }; + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultWritesHavingPredicatesOnMultipleLines() + { + const string input = "SELECT a FROM t GROUP BY a HAVING COUNT(*) > 1 AND SUM(a) > 2;"; + var options = new SqlScriptGeneratorOptions { MultilineSelectElementsList = false }; + const string expected = @" +SELECT a +FROM t +GROUP BY a +HAVING COUNT(*) > 1 + AND SUM(a) > 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestHavingPredicatesStayOnOneLineWhenDisabled() + { + const string input = "SELECT a FROM t GROUP BY a HAVING COUNT(*) > 1 AND SUM(a) > 2;"; + SqlScriptGeneratorOptions options = MakeOptions(false); + const string expected = @" +SELECT a +FROM t +GROUP BY a +HAVING COUNT(*) > 1 AND SUM(a) > 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestHavingPredicatesAreMultilineWhenEnabled() + { + const string input = "SELECT a FROM t WHERE a > 0 AND a < 10 GROUP BY a HAVING COUNT(*) > 1 AND SUM(a) > 2;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a +FROM t +WHERE a > 0 AND a < 10 +GROUP BY a +HAVING COUNT(*) > 1 + AND SUM(a) > 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineHavingPredicatesWithIndentedClauseBodies() + { + const string input = "SELECT a FROM t GROUP BY a HAVING COUNT(*) > 1 AND SUM(a) > 2;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + const string expected = @" +SELECT + a +FROM + t +GROUP BY + a +HAVING + COUNT(*) > 1 + AND SUM(a) > 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineHavingOrPredicates() + { + const string input = "SELECT a FROM t GROUP BY a HAVING COUNT(*) > 1 OR SUM(a) > 2;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a +FROM t +GROUP BY a +HAVING COUNT(*) > 1 + OR SUM(a) > 2;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineHavingPreservesParenthesizedMixedPredicates() + { + const string input = "SELECT a FROM t GROUP BY a HAVING (COUNT(*) > 1 OR SUM(a) > 2) AND MAX(a) < 10;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a +FROM t +GROUP BY a +HAVING (COUNT(*) > 1 + OR SUM(a) > 2) + AND MAX(a) < 10;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedWhereUsesItsOwnPredicateSetting() + { + const string input = "SELECT a FROM t GROUP BY a HAVING EXISTS (SELECT 1 FROM u WHERE u.a = t.a AND u.b > 0) AND COUNT(*) > 1;"; + SqlScriptGeneratorOptions options = MakeOptions(false); + options.MultilineWherePredicatesList = true; + const string expected = @" +SELECT a +FROM t +GROUP BY a +HAVING EXISTS (SELECT 1 + FROM u + WHERE u.a = t.a + AND u.b > 0) AND COUNT(*) > 1;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWhereAndHavingUseIndependentPredicateSettings() + { + const string input = "SELECT a FROM t WHERE a > 0 AND a < 10 GROUP BY a HAVING COUNT(*) > 1 AND SUM(a) > 2;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + const string expected = @" +SELECT + a +FROM + t +WHERE + a > 0 AND a < 10 +GROUP BY + a +HAVING + COUNT(*) > 1 + AND SUM(a) > 2;"; + + AssertGenerated(input, options, expected); + } + } +} \ No newline at end of file diff --git a/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs index 0a76defc..bde1944b 100644 --- a/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs +++ b/Test/SqlDom/ScriptGenerator/InValuesListFormattingTests.cs @@ -143,6 +143,26 @@ public void TestMultilineNoNewLineBeforeCloseParenthesis() AssertGenerated(input, options, expected); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCommentBeforeCloseParenthesisForcesNewLine() + { + const string input = +@"SELECT * FROM t WHERE x IN (1, 2 -- last value +);"; + var options = MakeOptions(true); + options.NewLineBeforeCloseParenthesisInMultilineList = false; + options.PreserveComments = true; + const string expected = @" +SELECT * FROM t WHERE x IN ( + 1, + 2 -- last value + );"; + + AssertGenerated(input, options, expected); + } + // ----------------------------------------------------------------------------------------- // Variants and edge cases // ----------------------------------------------------------------------------------------- diff --git a/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs index 0b8250f3..549a26e5 100644 --- a/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs +++ b/Test/SqlDom/ScriptGenerator/InsertTargetsListFormattingTests.cs @@ -48,7 +48,7 @@ public void TestSingleLineTargetsIsDefault() const string expected = @" INSERT INTO t (a, b, c) -VALUES (1, 2, 3);"; +VALUES (1, 2, 3);"; AssertGenerated(input, options, expected); } @@ -69,7 +69,7 @@ INSERT INTO t ( b, c ) -VALUES (1, 2, 3);"; +VALUES (1, 2, 3);"; AssertGenerated(input, options, expected); } @@ -85,7 +85,7 @@ public void TestSingleLineTargetsWhenDisabled() const string expected = @" INSERT INTO t (a, b, c) -VALUES (1, 2, 3);"; +VALUES (1, 2, 3);"; AssertGenerated(input, options, expected); } @@ -103,7 +103,7 @@ public void TestSingleTargetMultiline() INSERT INTO t ( a ) -VALUES (1);"; +VALUES (1);"; AssertGenerated(input, options, expected); } @@ -199,7 +199,7 @@ INSERT INTO t ( , b , c ) -VALUES (1, 2, 3);"; +VALUES (1, 2, 3);"; AssertGenerated(input, options, expected); } @@ -219,7 +219,36 @@ INSERT INTO t ( b, c ) -VALUES (1, 2, 3);"; +VALUES (1, 2, 3);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTargetsWithValuesMovedToNewLine() + { + // Multi-line target list combined with the Indented + AlignClauseBodies = false mode that + // moves the VALUES row constructors to their own indented line: the target list is still + // multi-line and the rows are not aligned under the target parenthesis. + const string input = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6);"; + var options = new SqlScriptGeneratorOptions + { + MultilineInsertTargetsList = true, + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + AlignClauseBodies = false, + }; + const string expected = +@" +INSERT INTO t ( + a, + b, + c +) +VALUES + (1, 2, 3), + (4, 5, 6);"; AssertGenerated(input, options, expected); } @@ -273,7 +302,7 @@ INSERT INTO t ( a, b, c) -VALUES (1, 2, 3);"; +VALUES (1, 2, 3);"; AssertGenerated(input, options, expected); } @@ -297,7 +326,7 @@ INSERT INTO t ( b ) OUTPUT inserted.a, inserted.b -VALUES (1, 2);"; +VALUES (1, 2);"; AssertGenerated(input, options, expected); } @@ -317,7 +346,7 @@ INSERT INTO t ( b ) OUTPUT inserted.a INTO @log -VALUES (1, 2);"; +VALUES (1, 2);"; AssertGenerated(input, options, expected); } @@ -391,7 +420,8 @@ INSERT INTO t ( [SqlStudioTestCategory(Category.UnitTest)] public void TestMultilineTargetsWithMultiRowValues() { - // Only the target list is affected; a multi-row VALUES source is left as-is. + // Only the target list is affected; a multi-row VALUES source keeps aligning its + // continuation rows under the first row. const string input = "INSERT INTO t (a, b) VALUES (1, 2), (3, 4);"; var options = new SqlScriptGeneratorOptions { MultilineInsertTargetsList = true }; const string expected = @@ -400,8 +430,8 @@ INSERT INTO t ( a, b ) -VALUES (1, 2), -(3, 4);"; +VALUES (1, 2), + (3, 4);"; AssertGenerated(input, options, expected); } diff --git a/Test/SqlDom/ScriptGenerator/InsertValuesAlignmentTests.cs b/Test/SqlDom/ScriptGenerator/InsertValuesAlignmentTests.cs new file mode 100644 index 00000000..2115dc83 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/InsertValuesAlignmentTests.cs @@ -0,0 +1,284 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the "river" that lines up an INSERT statement's VALUES row constructors under its + // column list (e.g. "INSERT INTO t (a, b)" / "VALUES (1, 2)"). The opening parenthesis of + // the VALUES row constructor lines up exactly with the opening parenthesis of the target's + // column list, regardless of how long the target name or column list is. + // Continuation rows (the 2nd, 3rd, ... row constructors) always align under the first row's + // column - either under the river's column (default Aligned behavior), or at the fixed indent + // used when the row constructors are moved to their own line (Indented + AlignClauseBodies = + // false). + [TestClass] + public class InsertValuesAlignmentTests + { + // ----------------------------------------------------------------------------------------- + // Default behavior: continuation rows align under the first row's column + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultAlignsValuesRowUnderColumnList() + { + // Default options: the VALUES row's opening parenthesis lines up exactly under the + // target column list's opening parenthesis, even for a long target/column list. + // Continuation rows align under the first row's column. + const string input = + "INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) " + + "VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), " + + "(2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) +VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), + (2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultAlignsShortColumnListToo() + { + const string input = "INSERT INTO t1 (c1, c2) VALUES (1, 2), (3, 4);"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +INSERT INTO t1 (c1, c2) +VALUES (1, 2), + (3, 4);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultAlignsSingleColumnList() + { + // Edge case: a single-column target list still lines up its VALUES row constructors + // exactly under the target list's opening parenthesis. + const string input = "INSERT INTO t (a) VALUES (1), (2);"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +INSERT INTO t (a) +VALUES (1), + (2);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // AlignClauseBodies = false alone: does not move the first VALUES row (only Indented + + // AlignClauseBodies = false does that - see below), but continuation rows still align under + // the first row's column, same as the default. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAlignClauseBodiesDisabledAloneAlignsValuesRowUnderColumnList() + { + const string input = + "INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) " + + "VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), " + + "(2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + var options = new SqlScriptGeneratorOptions { AlignClauseBodies = false }; + const string expected = +@" +INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) +VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), + (2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // ClauseBodyAlignment = Indented alone: also does not move the first VALUES row, since + // AlignClauseBodies is still true (the default). Continuation rows still align under the + // first row's column, same as the default. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedAloneAlignsValuesRowUnderColumnList() + { + const string input = + "INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) " + + "VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), " + + "(2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + var options = new SqlScriptGeneratorOptions { ClauseBodyAlignment = ClauseBodyAlignment.Indented }; + const string expected = +@" +INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) +VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), + (2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // ClauseBodyAlignment = Indented and AlignClauseBodies = false together: the VALUES row + // constructors move to their own indented line instead of being padded onto the VALUES line, + // and every row constructor (not just the first) is indented consistently. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWithAlignClauseBodiesDisabledMovesValuesRowToNewLine() + { + const string input = + "INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) " + + "VALUES (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), " + + "(2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + AlignClauseBodies = false, + }; + const string expected = +@" +INSERT INTO dbo.Nurses ([NurseID], [FNme], [LNme], [Spclty], [Crt], [CrtDt], [DtCrtd], [DtLst]) +VALUES + (1, 'Susie', 'Derkins', 'Cardiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE()), + (2, 'Jo', 'Harding', 'Radiology', 1, GETDATE() - 23139, GETDATE() - 2319, GETDATE());"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedWithAlignClauseBodiesDisabledMovesShortValuesRowToNewLine() + { + const string input = "INSERT INTO t1 (c1, c2) VALUES (1, 2), (3, 4);"; + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + AlignClauseBodies = false, + }; + const string expected = +@" +INSERT INTO t1 (c1, c2) +VALUES + (1, 2), + (3, 4);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // CommaPlacement = Leading: continuation rows carry a right-aligned leading comma so that + // every row constructor's opening parenthesis still lines up under the first row's column. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommaAlignsValuesRowUnderColumnList() + { + const string input = "INSERT INTO t1 (c1, c2) VALUES (1, 2), (3, 4);"; + var options = new SqlScriptGeneratorOptions { CommaPlacement = CommaPlacement.Leading }; + const string expected = +@" +INSERT INTO t1 (c1, c2) +VALUES (1, 2) + , (3, 4);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // MERGE ... WHEN NOT MATCHED THEN INSERT (...) VALUES (...) routes through the same + // ValuesInsertSource path. MERGE permits only a single VALUES row, so it exercises the + // path where the column-list alignment point is registered but never re-marked. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMergeInsertActionValuesGenerates() + { + const string input = + "MERGE INTO t AS tgt USING s AS src ON tgt.c1 = src.c1 " + + "WHEN NOT MATCHED THEN INSERT (c1, c2) VALUES (src.c1, src.c2);"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +MERGE INTO t + AS tgt +USING s AS src ON tgt.c1 = src.c1 +WHEN NOT MATCHED THEN INSERT (c1, c2) VALUES (src.c1, src.c2);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // A ValuesInsertSource scripted on its own has no column-list alignment point (that point is + // registered by the enclosing INSERT/MERGE). Generation must still succeed and emit every + // row instead of dereferencing the missing point. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBareValuesInsertSourceGeneratesWithoutColumnAlignmentPoint() + { + var source = new ValuesInsertSource(); + source.RowValues.Add(new RowValue { ColumnValues = { new IntegerLiteral { Value = "1" } } }); + source.RowValues.Add(new RowValue { ColumnValues = { new IntegerLiteral { Value = "2" } } }); + + var options = new SqlScriptGeneratorOptions + { + ClauseBodyAlignment = ClauseBodyAlignment.Indented, + AlignClauseBodies = false, + CommaPlacement = CommaPlacement.Leading, + }; + var generator = new Sql170ScriptGenerator(options); + generator.GenerateScript(source, out string generated); + + const string expected = +@" +VALUES + (1) + , (2)"; + + Assert.AreEqual(Normalize(expected).Trim(), Normalize(generated).Trim()); + } + + // ----------------------------------------------------------------------------------------- + // INSERT ... DEFAULT VALUES takes the IsDefaultValues branch of the VALUES source (no row + // constructors, so no river alignment). + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultValuesSource() + { + const string input = "INSERT INTO t DEFAULT VALUES;"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +INSERT INTO t +DEFAULT VALUES;"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchStatementTests.cs b/Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchStatementTests.cs new file mode 100644 index 00000000..ef44255e --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchStatementTests.cs @@ -0,0 +1,154 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the NumNewlinesAfterBatchStatement script-generation option, which controls how many + // newlines follow each statement owned directly by a TSqlBatch. Statements nested inside another + // statement are governed by NumNewlinesAfterStatement instead. + [TestClass] + public class NumNewlinesAfterBatchStatementTests + { + private const string TwoSelectsInBatch = @" +SELECT * FROM sys.databases; +SELECT * FROM sys.databases;"; + + private const string TwoSelectsInBeginEnd = @" +BEGIN +SELECT * FROM sys.databases; +SELECT * FROM sys.databases; +END"; + + private const string OneSelectInBatch = @"SELECT * FROM sys.databases;"; + + private static SqlScriptGeneratorOptions MakeOptions(int numNewlinesAfterBatchStatement) + { + return new SqlScriptGeneratorOptions { NumNewlinesAfterBatchStatement = numNewlinesAfterBatchStatement }; + } + + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNumNewlinesAfterBatchStatementDefaultIsTwo() + { + Assert.AreEqual(2, new SqlScriptGeneratorOptions().NumNewlinesAfterBatchStatement); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNegativeNumNewlinesAfterBatchStatementClampsToZero() + { + Assert.AreEqual(0, MakeOptions(-1).NumNewlinesAfterBatchStatement); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBatchStatementsWithDefaultOptions() + { + AssertGenerated(TwoSelectsInBatch, new SqlScriptGeneratorOptions(), @" +SELECT * +FROM sys.databases; + +SELECT * +FROM sys.databases;"); + } + + // ----------------------------------------------------------------------------------------- + // Batch-level statements (option applies) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBatchStatementsWithOneNewline() + { + AssertGenerated(TwoSelectsInBatch, MakeOptions(1), @" +SELECT * +FROM sys.databases; +SELECT * +FROM sys.databases;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBatchStatementsWithFourNewlines() + { + AssertGenerated(TwoSelectsInBatch, MakeOptions(4), @" +SELECT * +FROM sys.databases; + + + +SELECT * +FROM sys.databases;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBatchStatementsWithZeroNewlines() + { + // With no separating newline the second statement starts on the first one's last line, + // so its remaining clauses are aligned under that column. + AssertGenerated(TwoSelectsInBatch, MakeOptions(0), @" +SELECT * +FROM sys.databases;SELECT * + FROM sys.databases;"); + } + + // Exact (non-trimmed) assertions that pin the trailing newlines emitted after the final + // batch's last statement, which AssertGenerated's Trim() would otherwise discard. + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingNewlinesAfterLastStatementDefault() + { + AssertGeneratedExact(OneSelectInBatch, new SqlScriptGeneratorOptions(), + "SELECT *\nFROM sys.databases;\n\n"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingNewlinesAfterLastStatementZero() + { + AssertGeneratedExact(OneSelectInBatch, MakeOptions(0), + "SELECT *\nFROM sys.databases;"); + } + + // ----------------------------------------------------------------------------------------- + // Nested statement lists (option does not apply) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedStatementListWithFourNewlines() + { + // Statements nested in a BEGIN...END block follow NumNewlinesAfterStatement instead, so + // this matches the default. + AssertGenerated(TwoSelectsInBeginEnd, MakeOptions(4), @" +BEGIN + SELECT * + FROM sys.databases; + SELECT * + FROM sys.databases; +END"); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchesTests.cs b/Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchesTests.cs new file mode 100644 index 00000000..ba7dc877 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/NumNewlinesAfterBatchesTests.cs @@ -0,0 +1,180 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the NumNewlinesAfterBatches script-generation option, which controls how many + // newlines follow the GO separator between two batches. GO is always preceded by a newline of + // its own, and the blank lines before it come from NumNewlinesAfterBatchStatement. + [TestClass] + public class NumNewlinesAfterBatchesTests + { + private const string TwoBatches = @" +SELECT * FROM sys.databases; +GO +SELECT * FROM sys.databases;"; + + private const string BatchWithNestedBlockThenBatch = @" +SELECT * FROM sys.databases; +BEGIN +SELECT * FROM sys.databases; +SELECT * FROM sys.databases; +END +GO +SELECT * FROM sys.databases;"; + + private static SqlScriptGeneratorOptions MakeOptions(int numNewlinesAfterBatches) + { + return new SqlScriptGeneratorOptions { NumNewlinesAfterBatches = numNewlinesAfterBatches }; + } + + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNumNewlinesAfterBatchesDefaultIsOne() + { + Assert.AreEqual(1, new SqlScriptGeneratorOptions().NumNewlinesAfterBatches); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTwoBatchesWithDefaultOptions() + { + // The two blank lines before GO come from NumNewlinesAfterBatchStatement, which is + // applied after the last statement of the batch as well. + AssertGenerated(TwoBatches, new SqlScriptGeneratorOptions(), @" +SELECT * +FROM sys.databases; + + +GO +SELECT * +FROM sys.databases;"); + } + + // ----------------------------------------------------------------------------------------- + // Newlines after GO + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTwoBatchesWithThreeNewlines() + { + AssertGenerated(TwoBatches, MakeOptions(3), @" +SELECT * +FROM sys.databases; + + +GO + + +SELECT * +FROM sys.databases;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTwoBatchesWithZeroNewlinesClampsToOne() + { + // The next batch must start on its own line, so the setting is clamped to its minimum of 1. + Assert.AreEqual(1, MakeOptions(0).NumNewlinesAfterBatches); + } + + // ----------------------------------------------------------------------------------------- + // Interaction with NumNewlinesAfterBatchStatement + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestGoWithNoBlankLineOnEitherSide() + { + SqlScriptGeneratorOptions options = new SqlScriptGeneratorOptions + { + NumNewlinesAfterBatchStatement = 0, + NumNewlinesAfterBatches = 1 + }; + + AssertGenerated(TwoBatches, options, @" +SELECT * +FROM sys.databases; +GO +SELECT * +FROM sys.databases;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOneBlankLineOnEachSideOfGo() + { + SqlScriptGeneratorOptions options = new SqlScriptGeneratorOptions + { + NumNewlinesAfterBatchStatement = 1, + NumNewlinesAfterBatches = 2 + }; + + AssertGenerated(TwoBatches, options, @" +SELECT * +FROM sys.databases; + +GO + +SELECT * +FROM sys.databases;"); + } + + // ----------------------------------------------------------------------------------------- + // All three newline options together + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestAllThreeNewlineOptionsTogether() + { + SqlScriptGeneratorOptions options = new SqlScriptGeneratorOptions + { + NumNewlinesAfterStatement = 2, + NumNewlinesAfterBatchStatement = 2, + NumNewlinesAfterBatches = 2 + }; + + // One blank line between statements, nested and top level alike. The batch closes with + // two blank lines because the newline that carries GO stacks on top of the two written + // after END. + AssertGenerated(BatchWithNestedBlockThenBatch, options, @" +SELECT * +FROM sys.databases; + +BEGIN + SELECT * + FROM sys.databases; + + SELECT * + FROM sys.databases; +END + + +GO + +SELECT * +FROM sys.databases;"); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/NumNewlinesAfterStatementTests.cs b/Test/SqlDom/ScriptGenerator/NumNewlinesAfterStatementTests.cs new file mode 100644 index 00000000..2c07b998 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/NumNewlinesAfterStatementTests.cs @@ -0,0 +1,156 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the NumNewlinesAfterStatement script-generation option, which controls how many + // newlines separate consecutive statements of a StatementList. It does not apply to statements + // held directly by a TSqlBatch, which are governed by NumNewlinesAfterBatchStatement. + [TestClass] + public class NumNewlinesAfterStatementTests + { + private const string TwoSelectsInBatch = @" +SELECT * FROM sys.databases; +SELECT * FROM sys.databases;"; + + private const string TwoSelectsInBeginEnd = @" +BEGIN +SELECT * FROM sys.databases; +SELECT * FROM sys.databases; +END"; + + private static SqlScriptGeneratorOptions MakeOptions(int numNewlinesAfterStatement) + { + return new SqlScriptGeneratorOptions { NumNewlinesAfterStatement = numNewlinesAfterStatement }; + } + + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNumNewlinesAfterStatementDefaultIsOne() + { + Assert.AreEqual(1, new SqlScriptGeneratorOptions().NumNewlinesAfterStatement); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNegativeNumNewlinesAfterStatementClampsToZero() + { + Assert.AreEqual(0, MakeOptions(-1).NumNewlinesAfterStatement); + } + + // ----------------------------------------------------------------------------------------- + // Batch-level statements (option does not apply) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBatchStatementsWithDefaultOptions() + { + AssertGenerated(TwoSelectsInBatch, new SqlScriptGeneratorOptions(), @" +SELECT * +FROM sys.databases; + +SELECT * +FROM sys.databases;"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestBatchStatementsWithFourNewlines() + { + // Statements owned by a TSqlBatch follow NumNewlinesAfterBatchStatement instead, so + // this matches the default. + AssertGenerated(TwoSelectsInBatch, MakeOptions(4), @" +SELECT * +FROM sys.databases; + +SELECT * +FROM sys.databases;"); + } + + // ----------------------------------------------------------------------------------------- + // Nested statement lists (option applies) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedStatementListWithDefaultOptions() + { + AssertGenerated(TwoSelectsInBeginEnd, new SqlScriptGeneratorOptions(), @" +BEGIN + SELECT * + FROM sys.databases; + SELECT * + FROM sys.databases; +END"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedStatementListWithTwoNewlines() + { + // Every newline is followed by the current indentation, so the separating blank line + // below is not empty: it carries the four-space indent. + AssertGenerated(TwoSelectsInBeginEnd, MakeOptions(2), @" +BEGIN + SELECT * + FROM sys.databases; + + SELECT * + FROM sys.databases; +END"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedStatementListWithFourNewlines() + { + // Every newline is followed by the current indentation, so the separating blank lines + // below are not empty: each one carries the four-space indent. + AssertGenerated(TwoSelectsInBeginEnd, MakeOptions(4), @" +BEGIN + SELECT * + FROM sys.databases; + + + + SELECT * + FROM sys.databases; +END"); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNestedStatementListWithZeroNewlines() + { + // With no separating newline the second statement starts on the first one's last line, + // so its remaining clauses are aligned under that column. + AssertGenerated(TwoSelectsInBeginEnd, MakeOptions(0), @" +BEGIN + SELECT * + FROM sys.databases;SELECT * + FROM sys.databases; +END"); + } + } +} diff --git a/Test/SqlDom/ScriptGenerator/OrderByElementsListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/OrderByElementsListFormattingTests.cs new file mode 100644 index 00000000..9c7fe050 --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/OrderByElementsListFormattingTests.cs @@ -0,0 +1,239 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + [TestClass] + public class OrderByElementsListFormattingTests + { + private static SqlScriptGeneratorOptions MakeOptions(bool multiline) + { + return new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + MultilineOrderByElementsList = multiline, + MultilineSelectElementsList = false, + }; + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsOrderByElementsOnOneLine() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + var options = new SqlScriptGeneratorOptions { MultilineSelectElementsList = false }; + const string expected = @" +SELECT a, b +FROM t +ORDER BY a, b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOrderByElementsStayOnOneLineWhenDisabled() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(false); + const string expected = @" +SELECT a, b +FROM t +ORDER BY a, b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOrderByElementsAreMultilineWhenEnabled() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b +FROM t +ORDER BY a, + b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineOrderByElementsWithIndentedClauseBodies() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + const string expected = @" +SELECT + a, b +FROM + t +ORDER BY + a, + b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineOrderByElementsHonorLeadingCommaPlacement() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT a, b +FROM t +ORDER BY a + , b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedMultilineOrderByElementsHonorLeadingCommaPlacement() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT + a, b +FROM + t +ORDER BY + a + , b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommasWithMultilineSelectAndIndentedOrderByElements() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.MultilineSelectElementsList = true; + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT + a + , b +FROM + t +ORDER BY + a + , b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingCommasWithMultilineSelectAndAlignedOrderByElements() + { + const string input = "SELECT a, b FROM t ORDER BY a, b DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.MultilineSelectElementsList = true; + options.ClauseBodyAlignment = ClauseBodyAlignment.Aligned; + options.AlignClauseBodies = true; + options.CommaPlacement = CommaPlacement.Trailing; + const string expected = @" +SELECT a, + b +FROM t +ORDER BY a, + b DESC;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestThreeMultilineOrderByElementsHonorZeroLeadingCommaSpacing() + { + const string input = "SELECT a, b, c FROM t ORDER BY a, b DESC, c;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + options.LeadingCommaSpaceCount = 0; + const string expected = @" +SELECT a, b, c +FROM t +ORDER BY a + ,b DESC + ,c;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineOrderByElementsInOverClause() + { + const string input = "SELECT ROW_NUMBER() OVER (ORDER BY a, b DESC) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT ROW_NUMBER() OVER (ORDER BY a, + b DESC) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOrderByAllIgnoresMultilineElementsSetting() + { + const string input = "SELECT a, b FROM t ORDER BY ALL DESC;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b +FROM t +ORDER BY ALL DESC;"; + + AssertGeneratedFabric(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOrderByAllWithoutSortOrderIgnoresMultilineElementsSetting() + { + const string input = "SELECT a, b FROM t ORDER BY ALL;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT a, b +FROM t +ORDER BY ALL;"; + + AssertGeneratedFabric(input, options, expected); + } + } +} \ No newline at end of file diff --git a/Test/SqlDom/ScriptGenerator/PartitionByElementsListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/PartitionByElementsListFormattingTests.cs new file mode 100644 index 00000000..1fe9894a --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/PartitionByElementsListFormattingTests.cs @@ -0,0 +1,227 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + [TestClass] + public class PartitionByElementsListFormattingTests + { + private static SqlScriptGeneratorOptions MakeOptions(bool multiline) + { + return new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + MultilinePartitionByElementsList = multiline, + MultilineSelectElementsList = false, + }; + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsPartitionByElementsOnOneLine() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b) FROM t;"; + var options = new SqlScriptGeneratorOptions { MultilineSelectElementsList = false }; + const string expected = @" +SELECT SUM(c) OVER (PARTITION BY a, b) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPartitionByElementsStayOnOneLineWhenDisabled() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(false); + const string expected = @" +SELECT SUM(c) OVER (PARTITION BY a, b) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPartitionByElementsAreMultilineInOverClause() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT SUM(c) OVER (PARTITION BY a, + b) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestPartitionByElementsAreMultilineInNamedWindow() + { + const string input = "SELECT SUM(c) OVER win FROM t WINDOW win AS (PARTITION BY a, b);"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT SUM(c) OVER win +FROM t +WINDOW win AS (PARTITION BY a, + b);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilinePartitionByElementsWithIndentedClauseBodies() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + const string expected = @" +SELECT + SUM(c) OVER (PARTITION BY a, + b) +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilinePartitionByElementsBeforeOrderByAndFrame() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b ORDER BY c ROWS UNBOUNDED PRECEDING) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT SUM(c) OVER (PARTITION BY a, + b ORDER BY c ROWS UNBOUNDED PRECEDING) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilinePartitionByElementsBeforeOrderByInNamedWindow() + { + const string input = "SELECT SUM(c) OVER win FROM t WINDOW win AS (PARTITION BY a, b ORDER BY c);"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT SUM(c) OVER win +FROM t +WINDOW win AS (PARTITION BY a, + b ORDER BY c);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilinePartitionByElementsHonorLeadingCommaPlacement() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT SUM(c) OVER (PARTITION BY a + , b) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIndentedMultilinePartitionByElementsHonorLeadingCommaPlacement() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT + SUM(c) OVER (PARTITION BY a + , b) +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestLeadingCommasWithMultilineSelectAndIndentedPartitionByElements() + { + const string input = "SELECT a, SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.MultilineSelectElementsList = true; + options.ClauseBodyAlignment = ClauseBodyAlignment.Indented; + options.CommaPlacement = CommaPlacement.Leading; + const string expected = @" +SELECT + a + , SUM(c) OVER (PARTITION BY a + , b) +FROM + t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingCommasWithMultilineSelectAndAlignedPartitionByElements() + { + const string input = "SELECT a, SUM(c) OVER (PARTITION BY a, b) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + options.MultilineSelectElementsList = true; + options.ClauseBodyAlignment = ClauseBodyAlignment.Aligned; + options.AlignClauseBodies = true; + options.CommaPlacement = CommaPlacement.Trailing; + const string expected = @" +SELECT a, + SUM(c) OVER (PARTITION BY a, + b) +FROM t;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilinePartitionByOnlySplitsTopLevelElements() + { + const string input = "SELECT SUM(c) OVER (PARTITION BY COALESCE(a, b), c, d) FROM t;"; + SqlScriptGeneratorOptions options = MakeOptions(true); + const string expected = @" +SELECT SUM(c) OVER (PARTITION BY COALESCE (a, b), + c, + d) +FROM t;"; + + AssertGenerated(input, options, expected); + } + } +} \ No newline at end of file diff --git a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs index a1c10ecc..3569cabb 100644 --- a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs +++ b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTestHelper.cs @@ -4,6 +4,7 @@ // //------------------------------------------------------------------------------ +using System; using System.Collections.Generic; using System.IO; using Microsoft.SqlServer.TransactSql.ScriptDom; @@ -11,32 +12,97 @@ namespace SqlStudio.Tests.UTSqlScriptDom { - // Shared helpers for script-generation option tests: generate a script from SQL with the given - // options and verify both the input and the generated output parse without errors. - internal static class ScriptGeneratorTestHelper + // Template-method pipeline for script-generation option tests. The Generate/Verify/reparse + // steps are identical across dialects; only the parser and generator types differ. They are + // supplied as type parameters, and factory delegates create the concrete instances (whose + // constructors take arguments, so a new() constraint is not usable). + internal sealed class ScriptGenerationPipeline + where TParser : TSqlParser + where TGenerator : SqlScriptGenerator { - // Parses the input, generates a script with the given options (using the SQL-170 generator), - // asserts the input parses and the generated script reparses, and returns the generated script. - public static string Generate(string sql, SqlScriptGeneratorOptions options) + private readonly Func _createParser; + private readonly Func _createGenerator; + + public ScriptGenerationPipeline( + Func createParser, + Func createGenerator) + { + _createParser = createParser; + _createGenerator = createGenerator; + } + + // Template method: parse the input, generate a script with the given options, assert the + // input parses and the generated script reparses, and return the generated script. + public string Generate(string sql, SqlScriptGeneratorOptions options) { - var parser = new TSql170Parser(true); - TSqlFragment fragment = parser.Parse(new StringReader(sql), out IList errors); + TSqlFragment fragment = _createParser().Parse(new StringReader(sql), out IList errors); Assert.AreEqual(0, errors.Count, "Input must parse without errors."); - var generator = new Sql170ScriptGenerator(options); - generator.GenerateScript(fragment, out string generated); + _createGenerator(options).GenerateScript(fragment, out string generated); AssertReparses(generated); return generated; } - public static void AssertReparses(string sql) + public void AssertReparses(string sql) { - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(sql), out IList errors); + _createParser().Parse(new StringReader(sql), out IList errors); Assert.AreEqual(0, errors.Count, "Generated script must reparse without errors. Actual:\n" + sql); } + // Generates a script from the given SQL with the given options and asserts it equals the + // expected value. The expected literals typically start with a newline right after @" so the + // first SQL line lines up with the rest in source; Trim() removes that leading newline (and + // any trailing whitespace from the generated output) before comparing. + public void AssertGenerated(string sql, SqlScriptGeneratorOptions options, string expected) + { + Assert.AreEqual( + ScriptGeneratorTestHelper.Normalize(expected).Trim(), + ScriptGeneratorTestHelper.Normalize(Generate(sql, options)).Trim()); + } + + // Exact comparison without Trim(), so leading and trailing newline counts are part of the + // assertion. Use this to lock down the newlines emitted after the final batch's last statement. + public void AssertGeneratedExact(string sql, SqlScriptGeneratorOptions options, string expected) + { + Assert.AreEqual( + ScriptGeneratorTestHelper.Normalize(expected), + ScriptGeneratorTestHelper.Normalize(Generate(sql, options))); + } + } + + // Shared helpers for script-generation option tests. The default (SQL-170) and Fabric DW + // pipelines share all logic via ScriptGenerationPipeline; these static + // methods are thin entry points so existing tests keep their call style. + internal static class ScriptGeneratorTestHelper + { + private static readonly ScriptGenerationPipeline Sql170 = + new ScriptGenerationPipeline( + () => new TSql170Parser(true), options => new Sql170ScriptGenerator(options)); + + private static readonly ScriptGenerationPipeline FabricDW = + new ScriptGenerationPipeline( + () => new TSqlFabricDWParser(true), options => new SqlFabricDWScriptGenerator(options)); + + // SQL-100 pipeline, for syntax that later versions removed (for example the COMPUTE clause). + private static readonly ScriptGenerationPipeline Sql100 = + new ScriptGenerationPipeline( + () => new TSql100Parser(true), options => new Sql100ScriptGenerator(options)); + + // SQL-170 pipeline. + public static string Generate(string sql, SqlScriptGeneratorOptions options) => Sql170.Generate(sql, options); + public static void AssertReparses(string sql) => Sql170.AssertReparses(sql); + public static void AssertGenerated(string sql, SqlScriptGeneratorOptions options, string expected) => Sql170.AssertGenerated(sql, options, expected); + + // Fabric DW pipeline. + public static string GenerateFabric(string sql, SqlScriptGeneratorOptions options) => FabricDW.Generate(sql, options); + public static void AssertReparsesFabric(string sql) => FabricDW.AssertReparses(sql); + public static void AssertGeneratedFabric(string sql, SqlScriptGeneratorOptions options, string expected) => FabricDW.AssertGenerated(sql, options, expected); + + // SQL-100 pipeline. + public static string Generate100(string sql, SqlScriptGeneratorOptions options) => Sql100.Generate(sql, options); + public static void AssertGenerated100(string sql, SqlScriptGeneratorOptions options, string expected) => Sql100.AssertGenerated(sql, options, expected); + // Normalizes line endings so verbatim expected constants compare equal regardless of the // source file's line-ending style. public static string Normalize(string value) @@ -44,13 +110,8 @@ public static string Normalize(string value) return value.Replace("\r\n", "\n").Replace("\r", "\n"); } - // Generates a script from the given SQL with the given options and asserts it equals the - // expected value. The expected literals typically start with a newline right after @" so the - // first SQL line lines up with the rest in source; Trim() removes that leading newline (and - // any trailing whitespace from the generated output) before comparing. - public static void AssertGenerated(string sql, SqlScriptGeneratorOptions options, string expected) - { - Assert.AreEqual(Normalize(expected).Trim(), Normalize(Generate(sql, options)).Trim()); - } + // Exact comparison without Trim(), so leading and trailing newline counts are part of the + // assertion. Use this to lock down the newlines emitted after the final batch's last statement. + public static void AssertGeneratedExact(string sql, SqlScriptGeneratorOptions options, string expected) => Sql170.AssertGeneratedExact(sql, options, expected); } } diff --git a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs index a153791d..72f0b680 100644 --- a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs @@ -1,4 +1,4 @@ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -429,6 +429,270 @@ public void TestAlterTableAddIndexOnly_EmitsNoLeadingSeparator() "Generated SQL must reparse. Actual:\n" + generated); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_IsPreservedOnRoundTrip() + { + // With PersistTrailingGo enabled, a trailing GO present on input is regenerated. + var sql = @"DECLARE @v1 AS VARCHAR (100) = ''; +SELECT id, name FROM sys.databases; +GO +"; + var expected = @"DECLARE @v1 AS VARCHAR (100) = ''; + +SELECT id, + name +FROM sys.databases; + + +GO +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_NotEmittedByDefault() + { + // PersistTrailingGo defaults to false, so the trailing GO is not regenerated. + var sql = @"DECLARE @v1 AS VARCHAR (100) = ''; +SELECT id, name FROM sys.databases; +GO +"; + var expected = @"DECLARE @v1 AS VARCHAR (100) = ''; + +SELECT id, + name +FROM sys.databases; + +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions(), + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestNoTrailingGo_IsNotAdded() + { + // The trailing GO is optional on input; when absent it must not be generated even when enabled. + var sql = @"DECLARE @v1 AS VARCHAR (100) = ''; +SELECT id, name FROM sys.databases; +"; + var expected = @"DECLARE @v1 AS VARCHAR (100) = ''; + +SELECT id, + name +FROM sys.databases; + +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_ExtraNewLinesAroundGoAreNormalized() + { + // Several blank lines before and after the GO must not affect the generated output. + var sql = @"DECLARE @v1 AS VARCHAR (100) = ''; +SELECT id, name FROM sys.databases; + + + +GO + + + +"; + var expected = @"DECLARE @v1 AS VARCHAR (100) = ''; + +SELECT id, + name +FROM sys.databases; + + +GO +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_CommentBeforeGoStaysAboveSeparator() + { + // With PreserveComments + PersistTrailingGo, a comment between the last statement + // and the trailing GO must stay above the GO, not cross the batch separator. + var sql = @"SELECT 1; +-- trailing note +GO +"; + var expected = @"SELECT 1; + + -- trailing note +GO +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true, PreserveComments = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_BlockCommentBeforeAndCommentAfterGo() + { + // With PreserveComments + PersistTrailingGo, a block comment before the trailing GO + // must stay above it and a comment after the GO must stay below it — neither crosses + // the batch separator. + var sql = @"SELECT 1; +/* before */ +GO +-- after +"; + var expected = @"SELECT 1; + + +/* before */ +GO + +-- after"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true, PreserveComments = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_MultiBatchWithoutTrailingGoAddsNone() + { + // A GO between batches with no trailing GO must reset TrailingGoCount to 0, so even with + // PersistTrailingGo enabled the between-batch GO is preserved but no extra GO is appended. + var sql = @"SELECT 1; +GO +SELECT 2; +"; + var expected = @"SELECT 1; + + +GO +SELECT 2; + +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_MultiBatchWithTrailingGoPreserved() + { + // A multi-batch script that also ends with a trailing GO keeps both the between-batch + // GO and the trailing GO when PersistTrailingGo is enabled. + var sql = @"SELECT 1; +GO +SELECT 2; +GO +"; + var expected = @"SELECT 1; + + +GO +SELECT 2; + + +GO +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_ConsecutiveTrailingGosArePreserved() + { + // Consecutive trailing GO separators must be counted and re-emitted one-for-one so a + // parse -> generate -> reparse round-trip preserves the exact number of trailing GOs. + var sql = @"SELECT 1; +GO +GO +"; + var expected = @"SELECT 1; + + +GO + +GO +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestTrailingGo_MultiBatchVaryingGoCountsBetweenBatches() + { + // Between-batch GO runs (any count) collapse to a single batch separator, while only the + // consecutive trailing GO run is counted and re-emitted one-for-one. + var sql = @"SELECT 1; +GO +GO +SELECT 2; +GO +SELECT 3; +GO +GO +GO +"; + var expected = @"SELECT 1; + + +GO +SELECT 2; + + +GO +SELECT 3; + + +GO + +GO + +GO +"; + ScriptGeneratorTestHelper.AssertGeneratedExact( + sql, + new SqlScriptGeneratorOptions { PersistTrailingGo = true }, + expected); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] @@ -688,7 +952,12 @@ c VARCHAR (20) NOT NULL -- a string // AssertGenerated also verifies the generated script (comments included) reparses cleanly. ScriptGeneratorTestHelper.AssertGenerated( sql, - new SqlScriptGeneratorOptions { AlignColumnDefinitionFields = true, PreserveComments = true }, + new SqlScriptGeneratorOptions + { + AlignColumnDefinitionFields = true, + NewLineBeforeCloseParenthesisInMultilineList = false, + PreserveComments = true, + }, expected); } @@ -2247,968 +2516,5 @@ public void TestPreserveComments_RealWorldXmlModifyBatchFromDocs() #endregion - #region CommaPlacement - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementDefaultIsTrailing() - { - Assert.AreEqual(CommaPlacement.Trailing, new SqlScriptGeneratorOptions().CommaPlacement); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSelectList() - { - var sql = "SELECT a, b, c FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading - }); - generator.GenerateScript(fragment, out var generated); - - // Leading comma style for a keyword-aligned list: the columns stay aligned with the - // first element and each comma is placed two columns before them. - string expected = - "SELECT a" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingSelectList() - { - var sql = "SELECT a, b, c FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing - }); - generator.GenerateScript(fragment, out var generated); - - // Trailing comma style (default): the comma is placed at the end of each line. - string expected = - "SELECT a," + Environment.NewLine + - " b," + Environment.NewLine + - " c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingParenthesizedList() - { - var sql = "CREATE TABLE t (a INT, b INT, c INT);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading - }); - generator.GenerateScript(fragment, out var generated); - - // Leading comma style in a parenthesized (CREATE TABLE) column list. - // Elements stay at the list indentation level (4); the comma is indented two - // characters fewer (column 2), per the CommaPlacement=Leading rule. - string expected = - "CREATE TABLE t (" + Environment.NewLine + - " a INT" + Environment.NewLine + - " , b INT" + Environment.NewLine + - " , c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingParenthesizedList() - { - var sql = "CREATE TABLE t (a INT, b INT, c INT);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing - }); - generator.GenerateScript(fragment, out var generated); - - // Trailing comma style (default) in a parenthesized (CREATE TABLE) column list: - // each comma follows the element on the same line and the elements stay at the - // list indentation level (4). - string expected = - "CREATE TABLE t (" + Environment.NewLine + - " a INT," + Environment.NewLine + - " b INT," + Environment.NewLine + - " c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingInsertTargets() - { - // With MultilineInsertTargetsList = true the INSERT column target list is emitted as a - // multi-line parenthesized list (like CREATE TABLE / VIEW columns): each column on its - // own line indented one level. CommaPlacement = Leading places each column's comma at - // the start of its line (indented two characters fewer than the column). - var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineInsertTargetsList = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "INSERT INTO t (" + Environment.NewLine + - " a" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - ")" + Environment.NewLine + - "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingInsertTargets() - { - // With MultilineInsertTargetsList = true and CommaPlacement = Trailing (default) the - // INSERT column target list is emitted multi-line with each column on its own line and - // its comma trailing the column. - var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing, - MultilineInsertTargetsList = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "INSERT INTO t (" + Environment.NewLine + - " a," + Environment.NewLine + - " b," + Environment.NewLine + - " c" + Environment.NewLine + - ")" + Environment.NewLine + - "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingInsertSources() - { - // The INSERT source (VALUES) row list is a multi-line comma-separated list, so - // CommaPlacement = Leading places each continuation row's comma at the start of its - // line. (The rows are not aligned under the first row: this list is emitted via the - // newline comma-list path, so continuation rows begin at column 0.) The target column - // list is emitted multi-line because MultilineInsertTargetsList is explicitly enabled - // (it is no longer the default). - var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineInsertSourcesList = true, - MultilineInsertTargetsList = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "INSERT INTO t (" + Environment.NewLine + - " a" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - ")" + Environment.NewLine + - "VALUES (1, 2, 3)" + Environment.NewLine + - ", (4, 5, 6)" + Environment.NewLine + - ", (7, 8, 9);" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingInsertSources() - { - // The INSERT source (VALUES) row list with CommaPlacement = Trailing (default): - // each row's comma follows it at the end of the line. The target column list stays - // on a single line because MultilineInsertTargetsList is left at its default (false), - // exercising the common case of enabling only the source list. - var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing, - MultilineInsertSourcesList = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "INSERT INTO t (a, b, c)" + Environment.NewLine + - "VALUES (1, 2, 3)," + Environment.NewLine + - "(4, 5, 6)," + Environment.NewLine + - "(7, 8, 9);" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingViewColumns() - { - // The CREATE VIEW column list is a parenthesized, indented list (like CREATE TABLE): - // with CommaPlacement = Leading the columns stay at the list indentation level (4) - // and each comma is indented two characters fewer (column 2). The SELECT list in the - // view body is keyword-aligned, so its leading commas sit two columns before the - // aligned expression column. - var sql = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineViewColumnsList = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "CREATE VIEW v (" + Environment.NewLine + - " a" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - ")" + Environment.NewLine + - "AS" + Environment.NewLine + - "SELECT 1" + Environment.NewLine + - " , 2" + Environment.NewLine + - " , 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingViewColumns() - { - // Trailing comma style (default): the CREATE VIEW column list keeps each comma on the - // element's line at the list indentation level (4), and the SELECT list in the view - // body places each comma at the end of its line. - var sql = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing, - MultilineViewColumnsList = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "CREATE VIEW v (" + Environment.NewLine + - " a," + Environment.NewLine + - " b," + Environment.NewLine + - " c" + Environment.NewLine + - ")" + Environment.NewLine + - "AS" + Environment.NewLine + - "SELECT 1," + Environment.NewLine + - " 2," + Environment.NewLine + - " 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSetClauseItems() - { - // The UPDATE SET item list is keyword-aligned: with CommaPlacement = Leading the items - // stay aligned with the first item and each comma is placed two columns before them - // (the '=' signs remain aligned via a separate alignment point), matching the SELECT - // list behavior. - var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineSetClauseItems = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "UPDATE t" + Environment.NewLine + - "SET a = 1" + Environment.NewLine + - " , b = 2" + Environment.NewLine + - " , c = 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingSetClauseItems() - { - // Trailing comma style (default): the UPDATE SET items stay aligned with the first - // item and each comma follows the item at the end of its line. - var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing, - MultilineSetClauseItems = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "UPDATE t" + Environment.NewLine + - "SET a = 1," + Environment.NewLine + - " b = 2," + Environment.NewLine + - " c = 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSingleColumnHasNoComma() - { - // A list with a single element must never emit a comma regardless of placement. - var sql = "SELECT a FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading - }); - generator.GenerateScript(fragment, out var generated); - - // A list with a single element must never emit a comma regardless of placement. - string expected = - "SELECT a" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingWithPreserveCommentsDoesNotAbsorbComma() - { - // Interaction rule (FeedbackTicket 3016816 "SQL Formatter reformats leading - // commas to invalid SQL"): with - // CommaPlacement = Leading and PreserveComments = true, a line comment trailing - // an element must not cause the following comma to land on the comment line - // (which would comment out the comma). The comma belongs on the next element's line. - var sql = - "SELECT col1, -- first column" + Environment.NewLine + - " col2, -- second column" + Environment.NewLine + - " col3" + Environment.NewLine + - "FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - PreserveComments = true - }); - generator.GenerateScript(fragment, out var generated); - - // The full generated script: each line comment stays on its element's line, and the - // leading comma is placed at the start of the next element's line (before a column, - // never before a comment), so the comment is never commented out and the script - // reparses cleanly. - string expected = - "SELECT col1 -- first column" + Environment.NewLine + - " , col2 -- second column" + Environment.NewLine + - " , col3" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - // The generated script must reparse cleanly. - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementTrailingWithPreserveCommentsKeepsCommentsAfterComma() - { - // Counterpart to TestCommaPlacementLeadingWithPreserveCommentsDoesNotAbsorbComma - // (FeedbackTicket 3016816 "SQL Formatter reformats leading commas to invalid SQL"). With - // CommaPlacement = Trailing (default) and PreserveComments = true, each trailing comma - // stays on the element's line and its line comment follows the comma, so the generated - // script still reparses cleanly. - var sql = - "SELECT col1, -- first column" + Environment.NewLine + - " col2, -- second column" + Environment.NewLine + - " col3" + Environment.NewLine + - "FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Trailing, - PreserveComments = true - }); - generator.GenerateScript(fragment, out var generated); - - // The full generated script: the trailing comma stays on the element's line and its - // line comment follows the comma on that same line, so the script reparses cleanly. - string expected = - "SELECT col1, -- first column" + Environment.NewLine + - " col2, -- second column" + Environment.NewLine + - " col3" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - // The generated script must reparse cleanly. - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - // ---- Interaction rule: CommaPlacement = Leading has no visual effect when the - // ---- corresponding Multiline* option is false (the list stays on a single line). - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSelectListMultilineFalse() - { - // With MultilineSelectElementsList = false the SELECT list is emitted on a single - // line, so CommaPlacement = Leading has no visual effect (commas remain inline). - var sql = "SELECT a, b, c FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineSelectElementsList = false - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "SELECT a, b, c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingViewColumnsMultilineFalse() - { - // With MultilineViewColumnsList = false the VIEW column list is emitted as a single - // parenthesized line, so CommaPlacement = Leading has no visual effect there. (The - // SELECT body still honors leading placement via MultilineSelectElementsList, which - // defaults to true.) - var sql = "CREATE VIEW v (a, b, c) AS SELECT 1, 2, 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineViewColumnsList = false, - MultilineSelectElementsList = false - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "CREATE VIEW v (a, b, c)" + Environment.NewLine + - "AS" + Environment.NewLine + - "SELECT 1, 2, 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSetClauseItemsMultilineFalse() - { - // With MultilineSetClauseItems = false the UPDATE SET item list is emitted on a - // single line, so CommaPlacement = Leading has no visual effect (commas remain - // inline). - var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineSetClauseItems = false - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "UPDATE t" + Environment.NewLine + - "SET a = 1, b = 2, c = 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingInsertTargetsMultilineFalse() - { - // The INSERT target list is always emitted on a single line, so CommaPlacement = - // Leading has no visual effect regardless of MultilineInsertTargetsList. - var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineInsertTargetsList = false - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "INSERT INTO t (a, b, c)" + Environment.NewLine + - "VALUES (1, 2, 3);" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingInsertSourcesMultilineFalse() - { - // The INSERT source (VALUES) row list is always emitted multi-line (the generator - // does not gate it on MultilineInsertSourcesList), so setting that option to false - // does NOT collapse it to one line: CommaPlacement = Leading still applies to the - // row separators. The target column list stays on a single line because - // MultilineInsertTargetsList is left at its default (false). - var sql = "INSERT INTO t (a, b, c) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineInsertSourcesList = false - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "INSERT INTO t (a, b, c)" + Environment.NewLine + - "VALUES (1, 2, 3)" + Environment.NewLine + - ", (4, 5, 6)" + Environment.NewLine + - ", (7, 8, 9);" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingParenthesizedListAlwaysMultiline() - { - // The CREATE TABLE column list has no single-line toggle: it is always emitted - // multi-line. There is therefore no "Multiline = false" state for it, so - // CommaPlacement = Leading always applies (comma at indent - 2). - var sql = "CREATE TABLE t (a INT, b INT, c INT);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "CREATE TABLE t (" + Environment.NewLine + - " a INT" + Environment.NewLine + - " , b INT" + Environment.NewLine + - " , c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingIndentedOptionList() - { - // The WITH-parameter list of CREATE COLUMN MASTER KEY is generated through the indented - // multi-line comma-list path (GenerateCommaSeparatedList with insertNewLine and indent - // both true). With CommaPlacement = Leading the leading comma is emitted at the start - // of the next parameter's (indented) line. - var sql = "CREATE COLUMN MASTER KEY CMK1 WITH (KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE', KEY_PATH = 'some/path');"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading - }); - generator.GenerateScript(fragment, out var generated); - - // The continuation parameter's comma is emitted at the start of its (indented) line - // via the 4-arg GenerateCommaSeparatedList leading branch. The comma width is reserved - // inside the indentation, so the parameter stays aligned with the first parameter and - // the leading comma sits in the reserved columns before it. - string expected = - "CREATE COLUMN MASTER KEY CMK1" + Environment.NewLine + - "WITH (" + Environment.NewLine + - " KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE'" + Environment.NewLine + - " , KEY_PATH = 'some/path'" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSetClauseItemsIndented() - { - // With IndentSetClause = true the SET keyword is indented; CommaPlacement = Leading - // still aligns the items and places each comma two columns before them. - var sql = "UPDATE t SET a = 1, b = 2, c = 3;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - MultilineSetClauseItems = true, - IndentSetClause = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "UPDATE t" + Environment.NewLine + - " SET a = 1" + Environment.NewLine + - " , b = 2" + Environment.NewLine + - " , c = 3;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingCreateTableWithComments() - { - // PreserveComments + CommaPlacement.Leading in an indented (CREATE TABLE) column list: - // each trailing line comment stays on its column's line and the leading comma is - // emitted at the start of the next column's line (comma at indent - 2). Verifies the - // comment/comma-skip fix in the indent-based leading path, not just the SELECT list. - var sql = - "CREATE TABLE t (a INT, -- first" + Environment.NewLine + - "b INT, -- second" + Environment.NewLine + - "c INT);"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - PreserveComments = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "CREATE TABLE t (" + Environment.NewLine + - " a INT -- first" + Environment.NewLine + - " , b INT -- second" + Environment.NewLine + - " , c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingWithBlockCommentTrailingElement() - { - // PreserveComments + CommaPlacement.Leading with a block comment trailing an element. - // Block comments are emitted inline (a different path than the deferred '--' comments), - // so this confirms leading placement is not broken by an inline block comment. - var sql = "SELECT a /* note */, b, c FROM t;"; - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - PreserveComments = true - }); - generator.GenerateScript(fragment, out var generated); - - string expected = - "SELECT a /* note */" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - Assert.AreEqual(expected, generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSpaceCountZero() - { - // LeadingCommaSpaceCount = 0: the comma occupies a single column (no trailing space). - // Items stay aligned with the first element; only the comma column shifts. - const string selectSql = "SELECT a, b, c FROM t;"; - const string tableSql = "CREATE TABLE t (a INT, b INT, c INT);"; - - // Keyword-aligned list (SELECT): comma ends immediately before the aligned column. - string expectedSelect = - "SELECT a" + Environment.NewLine + - " ,b" + Environment.NewLine + - " ,c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - - // Indented list (CREATE TABLE): elements stay at indentation column 4; the comma is - // indented one column fewer (column 3) so the comma+item still occupy 4 columns. - string expectedTable = - "CREATE TABLE t (" + Environment.NewLine + - " a INT" + Environment.NewLine + - " ,b INT" + Environment.NewLine + - " ,c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - - AssertLeadingCommaSpaceCount(0, selectSql, expectedSelect); - AssertLeadingCommaSpaceCount(0, tableSql, expectedTable); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSpaceCountOne() - { - // LeadingCommaSpaceCount = 1 (the default): comma + one space, occupying 2 columns. - const string selectSql = "SELECT a, b, c FROM t;"; - const string tableSql = "CREATE TABLE t (a INT, b INT, c INT);"; - - string expectedSelect = - "SELECT a" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - - string expectedTable = - "CREATE TABLE t (" + Environment.NewLine + - " a INT" + Environment.NewLine + - " , b INT" + Environment.NewLine + - " , c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - - AssertLeadingCommaSpaceCount(1, selectSql, expectedSelect); - AssertLeadingCommaSpaceCount(1, tableSql, expectedTable); - } - - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestCommaPlacementLeadingSpaceCountTwo() - { - // LeadingCommaSpaceCount = 2: comma + two spaces, occupying 3 columns. - const string selectSql = "SELECT a, b, c FROM t;"; - const string tableSql = "CREATE TABLE t (a INT, b INT, c INT);"; - - string expectedSelect = - "SELECT a" + Environment.NewLine + - " , b" + Environment.NewLine + - " , c" + Environment.NewLine + - "FROM t;" + Environment.NewLine + Environment.NewLine; - - // Elements stay at indentation column 4; the comma is indented three columns fewer - // (column 1) so the comma plus its two trailing spaces still occupy 4 columns. - string expectedTable = - "CREATE TABLE t (" + Environment.NewLine + - " a INT" + Environment.NewLine + - " , b INT" + Environment.NewLine + - " , c INT" + Environment.NewLine + - ");" + Environment.NewLine + Environment.NewLine; - - AssertLeadingCommaSpaceCount(2, selectSql, expectedSelect); - AssertLeadingCommaSpaceCount(2, tableSql, expectedTable); - } - - // Generates the given SQL with CommaPlacement.Leading and the specified leading-comma space - // count, asserts the generated script matches the expectation, and that it reparses cleanly. - private static void AssertLeadingCommaSpaceCount(int spaceCount, string sql, string expected) - { - var parser = new TSql170Parser(true); - var fragment = parser.Parse(new StringReader(sql), out var errors); - Assert.AreEqual(0, errors.Count); - - var generator = new Sql170ScriptGenerator(new SqlScriptGeneratorOptions - { - CommaPlacement = CommaPlacement.Leading, - LeadingCommaSpaceCount = spaceCount - }); - generator.GenerateScript(fragment, out var generated); - - Assert.AreEqual(expected, generated, - "LeadingCommaSpaceCount=" + spaceCount + " produced unexpected output. Actual:\n" + generated); - - var reparser = new TSql170Parser(true); - reparser.Parse(new StringReader(generated), out var reErrors); - Assert.AreEqual(0, reErrors.Count, "Generated SQL must reparse. Actual:\n" + generated); - } - - #endregion } } diff --git a/Test/SqlDom/ScriptGenerator/WithOptionsListFormattingTests.cs b/Test/SqlDom/ScriptGenerator/WithOptionsListFormattingTests.cs new file mode 100644 index 00000000..0367c64a --- /dev/null +++ b/Test/SqlDom/ScriptGenerator/WithOptionsListFormattingTests.cs @@ -0,0 +1,647 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using static SqlStudio.Tests.UTSqlScriptDom.ScriptGeneratorTestHelper; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + // Tests for the MultilineWithOptionsList script-generation option, which controls whether the + // options in a WITH clause (index options, table hints, BACKUP/RESTORE options) or an OPTION + // clause (query hints) are written on a single line (default) or one per line. Kept in a + // dedicated file to avoid churn in ScriptGeneratorTests.cs. + // + // Work item: Formatter option: WITH clause options width + [TestClass] + public class WithOptionsListFormattingTests + { + // Builds options that isolate the WITH/OPTION option-list layout: clause bodies are not + // aligned and clauses are not broken onto their own lines, so the surrounding statement stays + // compact and the expectations focus on the option list itself. + private static SqlScriptGeneratorOptions MakeOptions(bool multilineWithOptionsList) + { + return new SqlScriptGeneratorOptions + { + MultilineWithOptionsList = multilineWithOptionsList, + AlignClauseBodies = false, + NewLineBeforeFromClause = false, + NewLineBeforeWhereClause = false, + MultilineSelectElementsList = false, + MultilineWherePredicatesList = false, + }; + } + + // ----------------------------------------------------------------------------------------- + // Default + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineWithOptionsListDefaultIsFalse() + { + Assert.IsFalse(new SqlScriptGeneratorOptions().MultilineWithOptionsList); + } + + // ----------------------------------------------------------------------------------------- + // CREATE INDEX (parenthesized index options) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsCreateIndexOptionsOnSingleLine() + { + const string input = "CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(false); + const string expected = +@" +CREATE INDEX i1 + ON t1(c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCreateIndexOptionsTrailingComma() + { + const string input = "CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(true); + const string expected = +@" +CREATE INDEX i1 + ON t1(c1) WITH ( + PAD_INDEX = ON, + FILLFACTOR = 50 +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCreateIndexOptionsLeadingComma() + { + // CommaPlacement = Leading applies within the options list: each option sits at the list + // indentation level and the comma is indented two characters fewer. + const string input = "CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = +@" +CREATE INDEX i1 + ON t1(c1) WITH ( + PAD_INDEX = ON + , FILLFACTOR = 50 +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCreateIndexOptionsNewLineBeforeOpenParenthesis() + { + // NewLineBeforeOpenParenthesisInMultilineList moves the open parenthesis onto its own line. + const string input = "CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(true); + options.NewLineBeforeOpenParenthesisInMultilineList = true; + const string expected = +@" +CREATE INDEX i1 + ON t1(c1) WITH +( + PAD_INDEX = ON, + FILLFACTOR = 50 +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCreateIndexOptionsCloseParenthesisOnLastItemLine() + { + // NewLineBeforeCloseParenthesisInMultilineList = false keeps the close parenthesis on the + // same line as the last option instead of on its own line. + const string input = "CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(true); + options.NewLineBeforeCloseParenthesisInMultilineList = false; + const string expected = +@" +CREATE INDEX i1 + ON t1(c1) WITH ( + PAD_INDEX = ON, + FILLFACTOR = 50);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCreateIndexCommentBeforeCloseParenthesisForcesNewLine() + { + const string input = +@"CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50 -- last option +);"; + var options = MakeOptions(true); + options.NewLineBeforeCloseParenthesisInMultilineList = false; + options.PreserveComments = true; + const string expected = +@" +CREATE INDEX i1 + ON t1(c1) WITH ( + PAD_INDEX = ON, + FILLFACTOR = 50 -- last option +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // ALTER INDEX ... REBUILD (index options WITHOUT a space before the parenthesis by default) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsAlterIndexRebuildOptionsOnSingleLine() + { + // The default single-line ALTER INDEX ... REBUILD form emits WITH(...) with no space + // before the open parenthesis; enabling the option must not change the default output. + const string input = "ALTER INDEX i1 ON t1 REBUILD WITH (ONLINE = ON, MAXDOP = 2);"; + var options = MakeOptions(false); + const string expected = +@" +ALTER INDEX i1 + ON t1 REBUILD WITH(ONLINE = ON, MAXDOP = 2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineAlterIndexRebuildOptions() + { + const string input = "ALTER INDEX i1 ON t1 REBUILD WITH (ONLINE = ON, MAXDOP = 2);"; + var options = MakeOptions(true); + const string expected = +@" +ALTER INDEX i1 + ON t1 REBUILD WITH ( + ONLINE = ON, + MAXDOP = 2 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // ALTER TABLE ... REBUILD (index options) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineAlterTableRebuildOptions() + { + const string input = "ALTER TABLE t1 REBUILD WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(true); + const string expected = +@" +ALTER TABLE t1 REBUILD WITH ( + PAD_INDEX = ON, + FILLFACTOR = 50 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Table hints (WITH (...)) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsTableHintsOnSingleLine() + { + const string input = "SELECT * FROM t1 WITH (NOLOCK, INDEX (i1));"; + var options = MakeOptions(false); + const string expected = "SELECT * FROM t1 WITH (NOLOCK, INDEX (i1));"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTableHints() + { + // The table hints align under the table reference, with each hint indented one level past + // that alignment point. + const string input = "SELECT * FROM t1 WITH (NOLOCK, INDEX (i1));"; + var options = MakeOptions(true); + const string expected = +@" +SELECT * FROM t1 WITH ( + NOLOCK, + INDEX (i1) + );"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineTableHintsLeadingComma() + { + const string input = "SELECT * FROM t1 WITH (NOLOCK, INDEX (i1));"; + var options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = +@" +SELECT * FROM t1 WITH ( + NOLOCK + , INDEX (i1) + );"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Query hints (OPTION (...)) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsQueryHintsOnSingleLine() + { + const string input = "SELECT * FROM t1 OPTION (RECOMPILE, MAXDOP 2);"; + var options = MakeOptions(false); + const string expected = +@" +SELECT * FROM t1 +OPTION (RECOMPILE, MAXDOP 2);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineQueryHints() + { + const string input = "SELECT * FROM t1 OPTION (RECOMPILE, MAXDOP 2);"; + var options = MakeOptions(true); + const string expected = +@" +SELECT * FROM t1 +OPTION ( + RECOMPILE, + MAXDOP 2 +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineQueryHintsLeadingComma() + { + const string input = "SELECT * FROM t1 OPTION (RECOMPILE, MAXDOP 2);"; + var options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = +@" +SELECT * FROM t1 +OPTION ( + RECOMPILE + , MAXDOP 2 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // BACKUP (non-parenthesized WITH options) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsBackupOptionsOnSingleLine() + { + const string input = "BACKUP DATABASE d1 TO DISK = 'd:' WITH BLOCKSIZE = 10, CHECKSUM;"; + var options = MakeOptions(false); + const string expected = +@" +BACKUP DATABASE d1 + TO DISK = 'd:' + WITH BLOCKSIZE = 10, CHECKSUM;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineBackupOptions() + { + // Each option is written on its own line, indented one level from the statement keyword + // (aligned beneath the WITH keyword). + const string input = "BACKUP DATABASE d1 TO DISK = 'd:' WITH BLOCKSIZE = 10, CHECKSUM;"; + var options = MakeOptions(true); + const string expected = +@" +BACKUP DATABASE d1 + TO DISK = 'd:' + WITH + BLOCKSIZE = 10, + CHECKSUM;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineBackupOptionsLeadingComma() + { + const string input = "BACKUP DATABASE d1 TO DISK = 'd:' WITH BLOCKSIZE = 10, CHECKSUM;"; + var options = MakeOptions(true); + options.CommaPlacement = CommaPlacement.Leading; + const string expected = +@" +BACKUP DATABASE d1 + TO DISK = 'd:' + WITH + BLOCKSIZE = 10 + , CHECKSUM;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // RESTORE (non-parenthesized WITH options) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsRestoreOptionsOnSingleLine() + { + const string input = "RESTORE DATABASE db1 FROM DISK = 'z:' WITH REPLACE, RECOVERY;"; + var options = MakeOptions(false); + const string expected = +@" +RESTORE DATABASE db1 FROM DISK = 'z:' + WITH REPLACE, RECOVERY;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineRestoreOptions() + { + const string input = "RESTORE DATABASE db1 FROM DISK = 'z:' WITH REPLACE, RECOVERY;"; + var options = MakeOptions(true); + const string expected = +@" +RESTORE DATABASE db1 FROM DISK = 'z:' + WITH + REPLACE, + RECOVERY;"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // CREATE SELECTIVE XML INDEX (trailing WITH index options) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineSelectiveXmlIndexOptions() + { + const string input = + "CREATE SELECTIVE XML INDEX sxi1 ON t1 (c1) " + + "FOR (path1 = '/a/b/c' AS SQL NVARCHAR(50)) " + + "WITH (DROP_EXISTING = ON, FILLFACTOR = 2);"; + var options = MakeOptions(true); + const string expected = +@" +CREATE SELECTIVE XML INDEX sxi1 ON t1(c1) +FOR( path1 = '/a/b/c' AS SQL NVARCHAR (50) +) +WITH ( + DROP_EXISTING = ON, + FILLFACTOR = 2 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Indentation: when IndentationMode is Tabs, the multiline option list is indented with tab + // characters rather than spaces. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineCreateIndexOptionsWithTabIndentation() + { + const string input = "CREATE INDEX i1 ON t1 (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50);"; + var options = MakeOptions(true); + options.IndentationMode = IndentationMode.Tabs; + // Explicit \t escapes (regular string, not verbatim) so the tab alignment characters are + // visible in source rather than hidden inside the literal. + const string expected = + "CREATE INDEX i1\n" + + "\tON t1(c1) WITH (\n" + + "\tPAD_INDEX = ON,\n" + + "\tFILLFACTOR = 50\n" + + ");"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Real-world: a production online index build whose long WITH option list is exactly the case + // this formatter option targets. One option per line makes the options readable and diffable. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineProductionOnlineIndexBuild() + { + const string input = + "CREATE NONCLUSTERED INDEX IX_SalesOrderHeader_CustomerID " + + "ON Sales.SalesOrderHeader (CustomerID) " + + "INCLUDE (OrderDate, TotalDue) " + + "WITH (PAD_INDEX = ON, FILLFACTOR = 80, ONLINE = ON, DATA_COMPRESSION = PAGE);"; + var options = MakeOptions(true); + const string expected = +@" +CREATE NONCLUSTERED INDEX IX_SalesOrderHeader_CustomerID + ON Sales.SalesOrderHeader(CustomerID) + INCLUDE(OrderDate, TotalDue) WITH ( + PAD_INDEX = ON, + FILLFACTOR = 80, + ONLINE = ON, + DATA_COMPRESSION = PAGE +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Shared GenerateIndexOptions entry points: inline index definitions and UNIQUE constraints + // in CREATE TABLE, and ALTER TABLE ... ALTER INDEX, all funnel through the same virtual + // GenerateIndexOptions method as CREATE INDEX, so the option applies to them too. These + // guard that the shared path stays multiline through those distinct entry points. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineInlineIndexDefinitionOptions() + { + const string input = + "CREATE TABLE t1 (c1 INT, INDEX ix1 NONCLUSTERED (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50));"; + var options = MakeOptions(true); + const string expected = +@" +CREATE TABLE t1 ( + c1 INT, + INDEX ix1 NONCLUSTERED (c1) WITH ( + PAD_INDEX = ON, + FILLFACTOR = 50 +) +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineUniqueConstraintOptions() + { + const string input = + "CREATE TABLE t1 (c1 INT, CONSTRAINT uq1 UNIQUE (c1) WITH (PAD_INDEX = ON, FILLFACTOR = 50));"; + var options = MakeOptions(true); + const string expected = +@" +CREATE TABLE t1 ( + c1 INT, + CONSTRAINT uq1 UNIQUE (c1) WITH ( + PAD_INDEX = ON, + FILLFACTOR = 50 +) +);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestDefaultKeepsAlterTableAlterIndexOptionsOnSingleLine() + { + // Guards the default (option off) rendering through the shared GenerateIndexOptions + // virtual chain for the ALTER TABLE ... ALTER INDEX entry point: WITH ( with a space. + const string input = + "ALTER TABLE t1 ALTER INDEX i1 REBUILD WITH (BUCKET_COUNT = 1);"; + var options = MakeOptions(false); + const string expected = +@" +ALTER TABLE t1 ALTER INDEX i1 REBUILD WITH (BUCKET_COUNT = 1);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineAlterTableAlterIndexOptions() + { + const string input = + "ALTER TABLE t1 ALTER INDEX i1 REBUILD WITH (BUCKET_COUNT = 1);"; + var options = MakeOptions(true); + const string expected = +@" +ALTER TABLE t1 ALTER INDEX i1 REBUILD WITH ( + BUCKET_COUNT = 1 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Interaction: combining MultilineWithOptionsList with another multiline layout option + // (MultilineSelectElementsList) must format both lists independently without interfering. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineWithOptionsListCombinedWithMultilineSelectElements() + { + const string input = + "SELECT c1, c2 FROM t1 OPTION (RECOMPILE, MAXDOP 2);"; + var options = MakeOptions(true); + options.MultilineSelectElementsList = true; + const string expected = +@" +SELECT c1, + c2 FROM t1 +OPTION ( + RECOMPILE, + MAXDOP 2 +);"; + + AssertGenerated(input, options, expected); + } + + // ----------------------------------------------------------------------------------------- + // Scope: the option must NOT affect the WITH keyword of a common table expression. + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestMultilineDoesNotAffectCommonTableExpression() + { + const string input = "WITH cte AS (SELECT 1 AS c) SELECT * FROM cte;"; + var options = MakeOptions(true); + const string expected = +@" +WITH cte +AS (SELECT 1 AS c) +SELECT * FROM cte;"; + + AssertGenerated(input, options, expected); + } + } +} diff --git a/Test/SqlDom/SparseMaskedColumnOrderRegressionTests.cs b/Test/SqlDom/SparseMaskedColumnOrderRegressionTests.cs new file mode 100644 index 00000000..349a1fd0 --- /dev/null +++ b/Test/SqlDom/SparseMaskedColumnOrderRegressionTests.cs @@ -0,0 +1,139 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; +using System.Collections.Generic; +using System.IO; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + public partial class SqlDomTests + { + /// + /// Regression test for https://github.com/microsoft/SqlScriptDOM/issues/216 + /// The Microsoft-documented column-definition order (SPARSE before MASKED WITH) + /// must parse cleanly, matching the already-working reversed order. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void SparseThenMaskedColumnOrderParses() + { + ParserTestUtils.ExecuteTestForParsers(parser => + { + string script = @"CREATE TABLE t (c varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS SPARSE MASKED WITH (FUNCTION = 'default()') NULL);"; + using (var scriptReader = new StringReader(script)) + { + parser.Parse(scriptReader, out IList errors); + Assert.AreEqual(0, errors.Count); + } + }, new TSql130Parser(true), new TSql140Parser(true), new TSql150Parser(true), new TSql160Parser(true), new TSql170Parser(true), new TSql180Parser(true), new TSqlFabricDWParser(true)); + } + + /// + /// Regression test for https://github.com/microsoft/SqlScriptDOM/issues/216 + /// Minimal reduction (no COLLATE) of the documented SPARSE-before-MASKED order. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void SparseThenMaskedColumnOrderWithoutCollateParses() + { + ParserTestUtils.ExecuteTestForParsers(parser => + { + string script = @"CREATE TABLE t (c varchar(100) SPARSE MASKED WITH (FUNCTION = 'default()') NULL);"; + using (var scriptReader = new StringReader(script)) + { + parser.Parse(scriptReader, out IList errors); + Assert.AreEqual(0, errors.Count); + } + }, new TSql130Parser(true), new TSql140Parser(true), new TSql150Parser(true), new TSql160Parser(true), new TSql170Parser(true), new TSql180Parser(true), new TSqlFabricDWParser(true)); + } + + /// + /// Regression guard for https://github.com/microsoft/SqlScriptDOM/issues/216 + /// The reversed (non-standard) MASKED-before-SPARSE order already parses today and + /// must keep parsing after the fix. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void MaskedThenSparseColumnOrderParses() + { + ParserTestUtils.ExecuteTestForParsers(parser => + { + string script = @"CREATE TABLE t (c varchar(100) MASKED WITH (FUNCTION = 'default()') SPARSE NULL);"; + using (var scriptReader = new StringReader(script)) + { + parser.Parse(scriptReader, out IList errors); + Assert.AreEqual(0, errors.Count); + } + }, new TSql130Parser(true), new TSql140Parser(true), new TSql150Parser(true), new TSql160Parser(true), new TSql170Parser(true), new TSql180Parser(true), new TSqlFabricDWParser(true)); + } + + /// + /// Round-trip guard for https://github.com/microsoft/SqlScriptDOM/issues/216 + /// Both orderings normalize to the documented SPARSE-before-MASKED order through the + /// script generator, and the generated script re-parses cleanly. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void SparseMaskedColumnOrderRoundTrips() + { + foreach (string script in new[] + { + @"CREATE TABLE t (c varchar(100) SPARSE MASKED WITH (FUNCTION = 'default()') NULL);", + @"CREATE TABLE t (c varchar(100) MASKED WITH (FUNCTION = 'default()') SPARSE NULL);" + }) + { + var parser = new TSql160Parser(true); + TSqlFragment fragment; + using (var scriptReader = new StringReader(script)) + { + fragment = parser.Parse(scriptReader, out IList errors); + Assert.AreEqual(0, errors.Count); + } + + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.Sql160); + scriptGen.GenerateScript(fragment, out string generated); + + // Generator always emits storage options (SPARSE) before MASKED WITH. + Assert.IsTrue(generated.IndexOf("SPARSE", System.StringComparison.Ordinal) < + generated.IndexOf("MASKED", System.StringComparison.Ordinal)); + + using (var generatedReader = new StringReader(generated)) + { + new TSql160Parser(true).Parse(generatedReader, out IList reparseErrors); + Assert.AreEqual(0, reparseErrors.Count); + } + } + } + + /// + /// Negative guard for https://github.com/microsoft/SqlScriptDOM/issues/216 + /// SPARSE predates SQL Server 2008, so TSql80/TSql90 must still reject it — the fix + /// must not accidentally enable SPARSE (or MASKED) on those versions. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void SparseMaskedColumnOrderRejectedBefore100() + { + ParserTestUtils.ExecuteTestForParsers(parser => + { + string script = @"CREATE TABLE t (c varchar(100) SPARSE MASKED WITH (FUNCTION = 'default()') NULL);"; + using (var scriptReader = new StringReader(script)) + { + parser.Parse(scriptReader, out IList errors); + Assert.IsTrue(errors.Count > 0); + } + }, new TSql80Parser(true), new TSql90Parser(true)); + } + } +} diff --git a/Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTests120.sql b/Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTests120.sql new file mode 100644 index 00000000..91e73061 --- /dev/null +++ b/Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTests120.sql @@ -0,0 +1,6 @@ +CREATE DATABASE [db1] COLLATE SQL_Latin1_General_CP1_CI_AS (EDITION = 'Standard') +GO +CREATE DATABASE hito COLLATE Japanese_Bushu_Kakusu_100_CS_AS_KS_WS (MAXSIZE = 500 MB, EDITION = 'GeneralPurpose', SERVICE_OBJECTIVE = 'GP_Gen5_8') +GO +CREATE DATABASE d1 (EDITION = 'business', SERVICE_OBJECTIVE = 'shared') COLLATE SQL_Latin1_General_CP1_CI_AS +GO diff --git a/Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql b/Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql new file mode 100644 index 00000000..91e73061 --- /dev/null +++ b/Test/SqlDom/TestScripts/CreateDatabaseCollateBeforeEditionTestsFabricDW.sql @@ -0,0 +1,6 @@ +CREATE DATABASE [db1] COLLATE SQL_Latin1_General_CP1_CI_AS (EDITION = 'Standard') +GO +CREATE DATABASE hito COLLATE Japanese_Bushu_Kakusu_100_CS_AS_KS_WS (MAXSIZE = 500 MB, EDITION = 'GeneralPurpose', SERVICE_OBJECTIVE = 'GP_Gen5_8') +GO +CREATE DATABASE d1 (EDITION = 'business', SERVICE_OBJECTIVE = 'shared') COLLATE SQL_Latin1_General_CP1_CI_AS +GO diff --git a/Test/SqlDom/TestScripts/CreateTableTests130.sql b/Test/SqlDom/TestScripts/CreateTableTests130.sql index 5ebb933a..f82a4331 100644 --- a/Test/SqlDom/TestScripts/CreateTableTests130.sql +++ b/Test/SqlDom/TestScripts/CreateTableTests130.sql @@ -395,6 +395,15 @@ CREATE TABLE t ( ); GO +-- Combines SPARSE and MASKED WITH on the same column, in both the documented +-- (SPARSE before MASKED) and reversed orders. See GitHub issue #216. +-- +CREATE TABLE t ( + COL0 VARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS SPARSE MASKED WITH (FUNCTION = 'default()') NULL, + COL1 VARCHAR(100) MASKED WITH (FUNCTION = 'default()') SPARSE NULL +); +GO + CREATE TABLE t ( COL0 INT NOT NULL, COL1 VARCHAR (20), diff --git a/Test/SqlDom/TestScripts/ModernGroupByAllTestsFabricDW.sql b/Test/SqlDom/TestScripts/ModernGroupByAllTestsFabricDW.sql new file mode 100644 index 00000000..5acd429b --- /dev/null +++ b/Test/SqlDom/TestScripts/ModernGroupByAllTestsFabricDW.sql @@ -0,0 +1,71 @@ +SELECT City, + Region, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL; +GO + +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +WHERE HireDate >= '19930101' +GROUP BY ALL +HAVING COUNT(*) > 5 +ORDER BY City; +GO + +SELECT Region, + YEAR(OrderDate) AS OrderYear, + Category, + COUNT(*) AS NumOrders, + SUM(Amount) AS Total +FROM Sales +WHERE Amount > 0 +GROUP BY ALL; +GO + +SELECT c.CustomerName, + COUNT(*) AS Orders +FROM Orders AS o + INNER JOIN + Customers AS c + ON o.CustomerId = c.CustomerId +GROUP BY ALL; +GO + +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL +ORDER BY City DESC; +GO + +SELECT * +FROM (SELECT City, + COUNT(*) AS Cnt + FROM dbo.Employees + GROUP BY ALL) AS t; +GO + +SELECT Region, + SUM(Amount) / COUNT(DISTINCT CustomerId) AS AvgSpend +FROM Sales +GROUP BY ALL; +GO + +CREATE VIEW v_GroupByAllView +AS +SELECT City, + COUNT(*) AS NumEmps +FROM dbo.Employees +GROUP BY ALL; +GO + +CREATE PROCEDURE usp_GroupByAll +AS +BEGIN + SELECT City, + COUNT(*) AS NumEmps + FROM dbo.Employees + GROUP BY ALL; +END diff --git a/Test/SqlDom/TestScripts/OrderByAllTestsFabricDW.sql b/Test/SqlDom/TestScripts/OrderByAllTestsFabricDW.sql new file mode 100644 index 00000000..89b452ff --- /dev/null +++ b/Test/SqlDom/TestScripts/OrderByAllTestsFabricDW.sql @@ -0,0 +1,95 @@ +SELECT c1, + c2 +FROM t1 +ORDER BY ALL; +GO + +SELECT c1, + c2 +FROM t1 +ORDER BY ALL ASC; +GO + +SELECT c1, + c2 +FROM t1 +ORDER BY ALL DESC; +GO + +SELECT * +FROM t1 +ORDER BY ALL; +GO + +SELECT c1, + c2 +FROM t1 +ORDER BY ALL +OFFSET 2 ROWS FETCH NEXT 5 ROWS ONLY; +GO + +SELECT c1 +FROM t1 +UNION ALL +SELECT c1 +FROM t2 +ORDER BY ALL; +GO + +SELECT * +FROM (SELECT TOP 5 c1, + c2 + FROM t1 + ORDER BY ALL) AS sub; +GO + +SELECT c1, + COUNT(*) AS Cnt +FROM t1 +GROUP BY c1 +ORDER BY ALL; +GO + +SELECT c1, + COUNT(*) AS Cnt +FROM t1 +GROUP BY c1 +HAVING COUNT(*) > 1 +ORDER BY ALL DESC; +GO + +SELECT a.c1, + b.c2 +FROM t1 AS a + INNER JOIN + t2 AS b + ON a.c1 = b.c1 +WHERE b.c2 > 0 +ORDER BY ALL; +GO + +SELECT c1, + COUNT(*) AS Cnt, + SUM(COUNT(*)) OVER (ORDER BY c1 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningCnt +FROM t1 +GROUP BY c1 +ORDER BY ALL; +GO + +CREATE VIEW v_OrderByAllView +AS +SELECT c1, + c2 +FROM t1 +ORDER BY ALL +OFFSET 0 ROWS; +GO + +CREATE PROCEDURE usp_OrderByAll +AS +BEGIN + SELECT c1, + c2 + FROM t1 + ORDER BY ALL; +END \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/SelectStatementTests.sql b/Test/SqlDom/TestScripts/SelectStatementTests.sql index 93b06f1d..2ed1979e 100644 --- a/Test/SqlDom/TestScripts/SelectStatementTests.sql +++ b/Test/SqlDom/TestScripts/SelectStatementTests.sql @@ -53,6 +53,8 @@ GO Select * from t1 group by c1; -- testing all Select * from t1 group by all c1; +-- testing all with multiple columns +Select * from t1 group by all c1, c2, c3; -- testing multiple expressions select * from t1 group by c1, c2, c3 -- testing with diff --git a/release-notes/180/180.102.0.md b/release-notes/180/180.102.0.md new file mode 100644 index 00000000..89fe2f46 --- /dev/null +++ b/release-notes/180/180.102.0.md @@ -0,0 +1,36 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.102.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* None + +#### .NET Framework +#### .NET Core + +### New Features +* Adds support for GROUP BY ALL and ORDER BY ALL in the Fabric DW parser. +* Adds the BuiltInFunctionCasing script generation option for controlling the casing of built-in function names. +* Adds the MultilineWithOptionsList script generation option for formatting WITH and OPTION clause options on separate lines. +* Adds the MultilineGroupByElementsList, MultilineHavingPredicatesList, MultilineOrderByElementsList, and MultilinePartitionByElementsList script generation options. +* Adds the NumNewlinesAfterBatchStatement and NumNewlinesAfterBatches script generation options. +* Adds the PersistTrailingGo script generation option for preserving trailing GO batch separators. +* Adds the TerminateBlockStatements script generation option for emitting semicolons after BEGIN...END and TRY...CATCH blocks. + +### Fixed +* Fixes INSERT VALUES formatting so row constructor parentheses align with the target column list. +* Fixes CREATE DATABASE parsing when COLLATE appears before Azure edition options. +* Fixes CREATE TABLE parsing when SPARSE appears before MASKED WITH in a column definition [#216](https://github.com/microsoft/SqlScriptDOM/issues/216). + +### Changes +* None + +### Known Issues +* None \ No newline at end of file From c122a7f9e69e9e98b0abbe7b69693ce23aaca829 Mon Sep 17 00:00:00 2001 From: Dan Fiedler <151573964+danfiedler-msft@users.noreply.github.com> Date: Thu, 10 Sep 2026 18:33:28 -0400 Subject: [PATCH 39/45] Pin GitHub Actions to full-length commit SHAs (#227) --- .github/dependabot.yml | 11 +++++++++++ .github/workflows/pr-validation.yml | 10 +++++----- 2 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..2c48305b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + groups: + github-actions: + patterns: ["*"] + schedule: + interval: "weekly" + cooldown: + default-days: 7 diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml index 9e3f2d7f..8a4aba5e 100644 --- a/.github/workflows/pr-validation.yml +++ b/.github/workflows/pr-validation.yml @@ -10,8 +10,8 @@ jobs: matrix: os: [windows-latest, ubuntu-latest] steps: - - uses: actions/checkout@v2 - - uses: actions/setup-dotnet@v2 + - uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2.8.0 + - uses: actions/setup-dotnet@8e6bd2905eef86446227f003dda1deb3916c4aaf # v2.2.1 with: global-json-file: global.json - name: Install dependencies @@ -20,7 +20,7 @@ jobs: run: dotnet build dirs.proj - name: Archive antlr log for troubleshooting if: ${{ failure() && matrix.os == 'ubuntu-latest' }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: antlr-log path: SqlScriptDom/NUL @@ -31,8 +31,8 @@ jobs: os: [windows-latest, ubuntu-latest] needs: build steps: - - uses: actions/checkout@v2 - - uses: actions/setup-dotnet@v2 + - uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2.8.0 + - uses: actions/setup-dotnet@8e6bd2905eef86446227f003dda1deb3916c4aaf # v2.2.1 with: global-json-file: global.json - name: Disable strong name validation From 8d8f667716e1868237814314070b7d54539d1c13 Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Mon, 14 Sep 2026 10:53:03 -0700 Subject: [PATCH 40/45] Updating the owners (#232) --- .github/CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1a133c2d..ae9e0439 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @dzsquared @zijchen @chlafreniere @llali @ssreerama @kburtram +* @llali @allancascante @kburtram @aaskhan @benjind From 2484dc0405bca081b7e67176cb4ce8423371f985 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Sep 2026 13:07:36 -0700 Subject: [PATCH 41/45] Bump the github-actions group across 1 directory with 3 updates (#231) Bumps the github-actions group with 3 updates in the / directory: [actions/checkout](https://github.com/actions/checkout), [actions/setup-dotnet](https://github.com/actions/setup-dotnet) and [actions/upload-artifact](https://github.com/actions/upload-artifact). Updates `actions/checkout` from 2.8.0 to 7.0.1 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/0717577d45739eb3c851188b29f50ed6c0b2194e...3d3c42e5aac5ba805825da76410c181273ba90b1) Updates `actions/setup-dotnet` from 2.2.1 to 6.0.0 - [Release notes](https://github.com/actions/setup-dotnet/releases) - [Commits](https://github.com/actions/setup-dotnet/compare/8e6bd2905eef86446227f003dda1deb3916c4aaf...a98b56852c35b8e3190ac28c8c2271da59106c68) Updates `actions/upload-artifact` from 4.6.2 to 7.0.1 - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/ea165f8d65b6e75b540449e92b4886f43607fa02...043fb46d1a93c77aae656e7c1c64a875d1fc6a0a) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: 7.0.1 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/setup-dotnet dependency-version: 6.0.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/upload-artifact dependency-version: 7.0.1 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/pr-validation.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml index 8a4aba5e..7d16e3c5 100644 --- a/.github/workflows/pr-validation.yml +++ b/.github/workflows/pr-validation.yml @@ -10,8 +10,8 @@ jobs: matrix: os: [windows-latest, ubuntu-latest] steps: - - uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2.8.0 - - uses: actions/setup-dotnet@8e6bd2905eef86446227f003dda1deb3916c4aaf # v2.2.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: global-json-file: global.json - name: Install dependencies @@ -20,7 +20,7 @@ jobs: run: dotnet build dirs.proj - name: Archive antlr log for troubleshooting if: ${{ failure() && matrix.os == 'ubuntu-latest' }} - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: antlr-log path: SqlScriptDom/NUL @@ -31,8 +31,8 @@ jobs: os: [windows-latest, ubuntu-latest] needs: build steps: - - uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2.8.0 - - uses: actions/setup-dotnet@8e6bd2905eef86446227f003dda1deb3916c4aaf # v2.2.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: global-json-file: global.json - name: Disable strong name validation From eaf3a6e8cf49350c7600bf70691de6314594ffba Mon Sep 17 00:00:00 2001 From: NAVEEN NAIK <71204882+ZEUSXXIV@users.noreply.github.com> Date: Thu, 1 Oct 2026 01:39:10 +0530 Subject: [PATCH 42/45] Add support for Query Hints for MS Fabric in TSql170Parser (#180) (#212) * Add support for Query Hints for MS Fabric in TSql170Parser (#180) * Add negative parser error tests and version-gating assertions for MS Fabric query hints --- .../Parser/TSql/CodeGenerationSupporter.cs | 3 +- SqlScriptDom/Parser/TSql/OptimizerHintKind.cs | 3 ++ SqlScriptDom/Parser/TSql/TSql170.g | 45 ++++++++++++++++--- SqlScriptDom/Parser/TSql/TSql180.g | 45 ++++++++++++++++--- SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 45 ++++++++++++++++--- ...SqlScriptGeneratorVisitor.OptimizerHint.cs | 18 +++++++- .../Baselines170/FabricQueryHints170.sql | 21 +++++++++ Test/SqlDom/Only170SyntaxTests.cs | 1 + Test/SqlDom/ParserErrorsTests.cs | 30 +++++++++++++ .../TestScripts/FabricQueryHints170.sql | 17 +++++++ 10 files changed, 208 insertions(+), 20 deletions(-) create mode 100644 Test/SqlDom/Baselines170/FabricQueryHints170.sql create mode 100644 Test/SqlDom/TestScripts/FabricQueryHints170.sql diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index 7bd0e484..fff679b0 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -1,4 +1,4 @@ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -972,6 +972,7 @@ internal static class CodeGenerationSupporter internal const string Signature = "SIGNATURE"; internal const string SimilarTo = "SIMILAR_TO"; internal const string Simple = "SIMPLE"; + internal const string Single = "SINGLE"; internal const string SingleBlob = "SINGLE_BLOB"; internal const string SingleClob = "SINGLE_CLOB"; internal const string SingleNClob = "SINGLE_NCLOB"; diff --git a/SqlScriptDom/Parser/TSql/OptimizerHintKind.cs b/SqlScriptDom/Parser/TSql/OptimizerHintKind.cs index 95b5187b..4b6673c4 100644 --- a/SqlScriptDom/Parser/TSql/OptimizerHintKind.cs +++ b/SqlScriptDom/Parser/TSql/OptimizerHintKind.cs @@ -59,6 +59,9 @@ public enum OptimizerHintKind NoPerformanceSpool = 34, Label = 35, + ForceSingleNodePlan = 36, + ForceDistributedPlan = 37, + ForTimestampAsOf = 38, } #pragma warning restore 1591 diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 302aa2af..48cf386e 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -22161,6 +22161,7 @@ hint returns [OptimizerHint vResult] | vResult = optimizeForOptimizerHint | vResult = tableHintsOptimizerHint | vResult = useHintClause + | vResult = forTimestampAsOfOptimizerHint ; tableHintsOptimizerHint returns [TableHintsOptimizerHint vResult = FragmentFactory.CreateFragment()] @@ -22202,12 +22203,31 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm vResult.HintKind = OptimizerHintKind.MergeUnion; UpdateTokenInfo(vResult, tMergeUnion); } - | tForce:Identifier Order - { - Match(tForce, CodeGenerationSupporter.Force); - vResult.HintKind = OptimizerHintKind.ForceOrder; - UpdateTokenInfo(vResult, tForce); - } + | {NextTokenMatches(CodeGenerationSupporter.Force)}? + tForce:Identifier ( + Order + { + Match(tForce, CodeGenerationSupporter.Force); + vResult.HintKind = OptimizerHintKind.ForceOrder; + UpdateTokenInfo(vResult, tForce); + } + | + Distributed tPlan1:Plan + { + Match(tForce, CodeGenerationSupporter.Force); + vResult.HintKind = OptimizerHintKind.ForceDistributedPlan; + UpdateTokenInfo(vResult, tForce); + } + | + tSingle:Identifier tNode:Identifier tPlan2:Plan + { + Match(tForce, CodeGenerationSupporter.Force); + Match(tSingle, CodeGenerationSupporter.Single); + Match(tNode, CodeGenerationSupporter.GraphNode); // NODE + vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; + UpdateTokenInfo(vResult, tForce); + } + ) | tHash:Identifier Group { Match(tHash, CodeGenerationSupporter.Hash); @@ -22384,6 +22404,19 @@ useHintClause returns [UseHintList vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tFor:For tTimestamp:Identifier tAs:As tOf:Of vValue = stringLiteral + { + Match(tTimestamp, CodeGenerationSupporter.TimeStamp); + vResult.HintKind = OptimizerHintKind.ForTimestampAsOf; + vResult.Value = vValue; + UpdateTokenInfo(vResult, tFor); + } + ; + createRuleStatement returns [CreateRuleStatement vResult = this.FragmentFactory.CreateFragment()] { SchemaObjectName vSchemaObjectName; diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index d6058b20..df96536f 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -22390,6 +22390,7 @@ hint returns [OptimizerHint vResult] | vResult = optimizeForOptimizerHint | vResult = tableHintsOptimizerHint | vResult = useHintClause + | vResult = forTimestampAsOfOptimizerHint ; tableHintsOptimizerHint returns [TableHintsOptimizerHint vResult = FragmentFactory.CreateFragment()] @@ -22431,12 +22432,31 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm vResult.HintKind = OptimizerHintKind.MergeUnion; UpdateTokenInfo(vResult, tMergeUnion); } - | tForce:Identifier Order - { - Match(tForce, CodeGenerationSupporter.Force); - vResult.HintKind = OptimizerHintKind.ForceOrder; - UpdateTokenInfo(vResult, tForce); - } + | {NextTokenMatches(CodeGenerationSupporter.Force)}? + tForce:Identifier ( + Order + { + Match(tForce, CodeGenerationSupporter.Force); + vResult.HintKind = OptimizerHintKind.ForceOrder; + UpdateTokenInfo(vResult, tForce); + } + | + Distributed tPlan1:Plan + { + Match(tForce, CodeGenerationSupporter.Force); + vResult.HintKind = OptimizerHintKind.ForceDistributedPlan; + UpdateTokenInfo(vResult, tForce); + } + | + tSingle:Identifier tNode:Identifier tPlan2:Plan + { + Match(tForce, CodeGenerationSupporter.Force); + Match(tSingle, CodeGenerationSupporter.Single); + Match(tNode, CodeGenerationSupporter.GraphNode); // NODE + vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; + UpdateTokenInfo(vResult, tForce); + } + ) | tHash:Identifier Group { Match(tHash, CodeGenerationSupporter.Hash); @@ -22613,6 +22633,19 @@ useHintClause returns [UseHintList vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tFor:For tTimestamp:Identifier tAs:As tOf:Of vValue = stringLiteral + { + Match(tTimestamp, CodeGenerationSupporter.TimeStamp); + vResult.HintKind = OptimizerHintKind.ForTimestampAsOf; + vResult.Value = vValue; + UpdateTokenInfo(vResult, tFor); + } + ; + createRuleStatement returns [CreateRuleStatement vResult = this.FragmentFactory.CreateFragment()] { SchemaObjectName vSchemaObjectName; diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index a3644ea3..5f7808dd 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -21956,6 +21956,7 @@ hint returns [OptimizerHint vResult] | vResult = optimizeForOptimizerHint | vResult = tableHintsOptimizerHint | vResult = useHintClause + | vResult = forTimestampAsOfOptimizerHint ; tableHintsOptimizerHint returns [TableHintsOptimizerHint vResult = FragmentFactory.CreateFragment()] @@ -21997,12 +21998,31 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm vResult.HintKind = OptimizerHintKind.MergeUnion; UpdateTokenInfo(vResult, tMergeUnion); } - | tForce:Identifier Order - { - Match(tForce, CodeGenerationSupporter.Force); - vResult.HintKind = OptimizerHintKind.ForceOrder; - UpdateTokenInfo(vResult, tForce); - } + | {NextTokenMatches(CodeGenerationSupporter.Force)}? + tForce:Identifier ( + Order + { + Match(tForce, CodeGenerationSupporter.Force); + vResult.HintKind = OptimizerHintKind.ForceOrder; + UpdateTokenInfo(vResult, tForce); + } + | + Distributed tPlan1:Plan + { + Match(tForce, CodeGenerationSupporter.Force); + vResult.HintKind = OptimizerHintKind.ForceDistributedPlan; + UpdateTokenInfo(vResult, tForce); + } + | + tSingle:Identifier tNode:Identifier tPlan2:Plan + { + Match(tForce, CodeGenerationSupporter.Force); + Match(tSingle, CodeGenerationSupporter.Single); + Match(tNode, CodeGenerationSupporter.GraphNode); // NODE + vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; + UpdateTokenInfo(vResult, tForce); + } + ) | tHash:Identifier Group { Match(tHash, CodeGenerationSupporter.Hash); @@ -22179,6 +22199,19 @@ useHintClause returns [UseHintList vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tFor:For tTimestamp:Identifier tAs:As tOf:Of vValue = stringLiteral + { + Match(tTimestamp, CodeGenerationSupporter.TimeStamp); + vResult.HintKind = OptimizerHintKind.ForTimestampAsOf; + vResult.Value = vValue; + UpdateTokenInfo(vResult, tFor); + } + ; + createRuleStatement returns [CreateRuleStatement vResult = this.FragmentFactory.CreateFragment()] { SchemaObjectName vSchemaObjectName; diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs index 8f61d188..92068d15 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs @@ -105,7 +105,16 @@ partial class SqlScriptGeneratorVisitor new IdentifierGenerator(CodeGenerationSupporter.NoPerformanceSpool), }}, { OptimizerHintKind.Label, new List() { new IdentifierGenerator(CodeGenerationSupporter.Label, true), - new KeywordGenerator(TSqlTokenType.EqualsSign) }} + new KeywordGenerator(TSqlTokenType.EqualsSign) }}, + { OptimizerHintKind.ForceSingleNodePlan, new List( ) { + new IdentifierGenerator(CodeGenerationSupporter.Force, true), + new IdentifierGenerator(CodeGenerationSupporter.Single, true), + new IdentifierGenerator(CodeGenerationSupporter.GraphNode, true), + new KeywordGenerator(TSqlTokenType.Plan) }}, + { OptimizerHintKind.ForceDistributedPlan, new List( ) { + new IdentifierGenerator(CodeGenerationSupporter.Force, true), + new KeywordGenerator(TSqlTokenType.Distributed, true), + new KeywordGenerator(TSqlTokenType.Plan) }} }; public override void ExplicitVisit(LiteralOptimizerHint node) @@ -122,6 +131,13 @@ public override void ExplicitVisit(LiteralOptimizerHint node) GenerateSpaceAndKeyword(TSqlTokenType.Plan); } } + else if (node.HintKind == OptimizerHintKind.ForTimestampAsOf) + { + GenerateKeyword(TSqlTokenType.For); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.TimeStamp); + GenerateSpaceAndKeyword(TSqlTokenType.As); + GenerateSpaceAndKeyword(TSqlTokenType.Of); + } else { List generators = GetValueForEnumKey(_optimizerHintKindsGenerators, node.HintKind); diff --git a/Test/SqlDom/Baselines170/FabricQueryHints170.sql b/Test/SqlDom/Baselines170/FabricQueryHints170.sql new file mode 100644 index 00000000..fb6678eb --- /dev/null +++ b/Test/SqlDom/Baselines170/FabricQueryHints170.sql @@ -0,0 +1,21 @@ +SELECT OrderDateKey, + SUM(SalesAmount) AS TotalSales +FROM FactInternetSales +GROUP BY OrderDateKey +ORDER BY OrderDateKey +OPTION (FOR TIMESTAMP AS OF '2024-03-13T19:39:35.28'); + +SELECT OrderDateKey, + SalesAmount +FROM FactInternetSales +OPTION (FORCE SINGLE NODE PLAN); + +SELECT OrderDateKey, + SalesAmount +FROM FactInternetSales +OPTION (FORCE DISTRIBUTED PLAN); + +SELECT OrderDateKey, + SalesAmount +FROM FactInternetSales +OPTION (FORCE DISTRIBUTED PLAN, FOR TIMESTAMP AS OF '2024-03-13T19:39:35.28'); diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 322f993e..6c6aa482 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -41,6 +41,7 @@ public partial class SqlDomTests new ParserTest170("VectorSearchCrossApplyTests170.sql", nErrors80: 1, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1, nErrors160: 1), // Complex query with VECTOR types - parses syntactically in all versions (optimization fix), but VECTOR type only valid in TSql170 new ParserTest170("ComplexQueryTests170.sql"), + new ParserTest170("FabricQueryHints170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), // Comment preservation tests - basic SQL syntax works in all versions new ParserTest170("SingleLineCommentTests170.sql"), new ParserTest170("MultiLineCommentTests170.sql") diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 26e48488..00db16fb 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -8290,5 +8290,35 @@ public void TopWithTiesAndApproximateError180() "SELECT TOP 10 WITH TIES WITH APPROXIMATE * FROM MyTable ORDER BY id;", new ParserErrorInfo(24, "SQL46010", "WITH")); } + + /// + /// Negative test for Fabric Query Hints - syntax error (TSql170) + /// Verifies malformed hints produce expected parser errors + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void FabricQueryHintsErrorTest170() + { + // Missing NODE keyword in FORCE SINGLE NODE PLAN + ParserTestUtils.ErrorTest170( + "SELECT OrderDateKey FROM FactInternetSales OPTION (FORCE SINGLE PLAN);", + new ParserErrorInfo(64, "SQL46010", "PLAN")); + + // Missing PLAN keyword in FORCE DISTRIBUTED PLAN + ParserTestUtils.ErrorTest170( + "SELECT OrderDateKey FROM FactInternetSales OPTION (FORCE DISTRIBUTED);", + new ParserErrorInfo(68, "SQL46010", ")")); + + // Non-string literal in FOR TIMESTAMP AS OF + ParserTestUtils.ErrorTest170( + "SELECT OrderDateKey FROM FactInternetSales OPTION (FOR TIMESTAMP AS OF 12345);", + new ParserErrorInfo(71, "SQL46010", "12345")); + + // Missing OF keyword in FOR TIMESTAMP AS OF + ParserTestUtils.ErrorTest170( + "SELECT OrderDateKey FROM FactInternetSales OPTION (FOR TIMESTAMP AS '2024-03-13T19:39:35.28');", + new ParserErrorInfo(68, "SQL46010", "'2024-03-13T19:39:35.28'")); + } } } diff --git a/Test/SqlDom/TestScripts/FabricQueryHints170.sql b/Test/SqlDom/TestScripts/FabricQueryHints170.sql new file mode 100644 index 00000000..222a0116 --- /dev/null +++ b/Test/SqlDom/TestScripts/FabricQueryHints170.sql @@ -0,0 +1,17 @@ +SELECT OrderDateKey, SUM(SalesAmount) AS TotalSales +FROM FactInternetSales +GROUP BY OrderDateKey +ORDER BY OrderDateKey +OPTION (FOR TIMESTAMP AS OF '2024-03-13T19:39:35.28'); + +SELECT OrderDateKey, SalesAmount +FROM FactInternetSales +OPTION (FORCE SINGLE NODE PLAN); + +SELECT OrderDateKey, SalesAmount +FROM FactInternetSales +OPTION (FORCE DISTRIBUTED PLAN); + +SELECT OrderDateKey, SalesAmount +FROM FactInternetSales +OPTION (FORCE DISTRIBUTED PLAN, FOR TIMESTAMP AS OF '2024-03-13T19:39:35.28'); From bd65d41d0d0db1e7a54a0d4434563dedaba9d409 Mon Sep 17 00:00:00 2001 From: allancascante Date: Mon, 12 Oct 2026 16:32:07 -0600 Subject: [PATCH 43/45] Dev/allancascante/sync release 180.140.0 (#234) Sync released ScriptDOM 180.140.0 changes and add release notes. Add Fabric DW AI ON ERROR support and join/query hints. Fix quoted WINDOW references, GROUP BY ALL source ranges, and U+FFFF lexer handling. Fix preserved comment ordering and column alias style. Include previously missed released ROLLBACK transaction-priority parsing and APPLY/CROSS JOIN newline formatting. Add regression tests and update baselines. --------- Co-authored-by: Allan Cascante <120929896+acascante_microsoft@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/CODEOWNERS | 2 +- SqlScriptDom/Parser/TSql/Ast.xml | 21 +- .../Parser/TSql/CodeGenerationSupporter.cs | 1 + SqlScriptDom/Parser/TSql/JoinHint.cs | 10 +- SqlScriptDom/Parser/TSql/TSql160.g | 4 +- SqlScriptDom/Parser/TSql/TSql170.g | 10 +- SqlScriptDom/Parser/TSql/TSql180.g | 15 +- .../Parser/TSql/TSql80ParserBaseInternal.cs | 5 +- SqlScriptDom/Parser/TSql/TSqlFabricDW.g | 227 ++++++++++--- .../Parser/TSql/TSqlLexerBaseInternal.cs | 59 +++- .../Parser/TSql/VectorMetricTypeHelper.cs | 2 - ...ratorVisitor.AiAnalyzeSentimentFunction.cs | 1 + ...riptGeneratorVisitor.AiClassifyFunction.cs | 1 + ...criptGeneratorVisitor.AiExtractFunction.cs | 1 + ...ptGeneratorVisitor.AiFixGrammarFunction.cs | 1 + ...ratorVisitor.AiGenerateResponseFunction.cs | 1 + ...iptGeneratorVisitor.AiSummarizeFunction.cs | 1 + ...iptGeneratorVisitor.AiTranslateFunction.cs | 41 +++ ...Visitor.AlterTableAddClusterByStatement.cs | 2 +- .../SqlScriptGeneratorVisitor.Comments.cs | 139 +++++++- ...SqlScriptGeneratorVisitor.CommonPhrases.cs | 49 ++- .../SqlScriptGeneratorVisitor.FromClause.cs | 10 +- ...SqlScriptGeneratorVisitor.OptimizerHint.cs | 25 +- .../SqlScriptGeneratorVisitor.OverClause.cs | 4 +- ...SqlScriptGeneratorVisitor.QualifiedJoin.cs | 14 +- ...GeneratorVisitor.SelectScalarExpression.cs | 36 +- ...lScriptGeneratorVisitor.UnqualifiedJoin.cs | 3 +- .../SqlScriptGeneratorVisitor.Utils.cs | 37 +- .../Settings/SqlScriptGeneratorOptions.xml | 2 +- SqlScriptDom/antlr/antlr/CharScanner.cs | 50 ++- SqlScriptDom/antlr/antlr/InputBuffer.cs | 9 +- .../antlr/antlr/MismatchedCharException.cs | 33 +- .../antlr/NoViableAltForCharException.cs | 26 +- Test/SqlDom/Baselines110/OffsetClause.sql | 9 +- .../Baselines130/FromClauseTests130.sql | 17 +- .../Baselines150/FromClauseTests150.sql | 12 +- .../WindowClauseQuotedNameTests160.sql | 46 +++ .../Baselines170/AiGenerateChunksTests170.sql | 24 +- .../Baselines170/ComplexQueryTests170.sql | 83 +++-- .../VectorSearchApproximateTests170.sql | 60 ++-- .../VectorSearchCrossApplyTests170.sql | 15 +- .../WindowClauseQuotedNameTests160.sql | 46 +++ ...atabaseScopedConfigTxnPriorityTests180.sql | 13 + .../WindowClauseQuotedNameTests160.sql | 46 +++ Test/SqlDom/Baselines90/FromClauseTests90.sql | 9 +- .../BaselinesCommon/FromClauseTests.sql | 57 +++- .../BaselinesCommon/SelectStatementTests.sql | 3 +- .../AiAnalyzeSentimentTestsFabricDW.sql | 8 +- .../AiClassifyTestsFabricDW.sql | 8 +- .../AiExtractTestsFabricDW.sql | 8 +- .../AiFixGrammarTestsFabricDW.sql | 8 +- .../AiGenerateResponseTestsFabricDW.sql | 8 +- .../AiSummarizeTestsFabricDW.sql | 8 +- .../AiTranslateTestsFabricDW.sql | 10 +- ...CreateAlterTableClusterByTestsFabricDW.sql | 13 +- .../QueryHintsTestsFabricDW.sql | 41 +++ .../WindowClauseQuotedNameTests160.sql | 46 +++ Test/SqlDom/CommonSyntaxTests.cs | 3 +- Test/SqlDom/Only160SyntaxTests.cs | 1 + Test/SqlDom/Only170SyntaxTests.cs | 1 + Test/SqlDom/Only180SyntaxTests.cs | 4 +- Test/SqlDom/OnlyFabricDWSyntaxTests.cs | 128 ++++++- Test/SqlDom/ParserErrorsTests.cs | 124 ++++++- .../ScriptGenerator/ColumnAliasStyleTests.cs | 72 ++++ .../ScriptGenerator/CommaPlacementTests.cs | 231 ++++++++++++- .../IdentifierFormattingTests.cs | 49 ++- .../JoinClauseFormattingTests.cs | 130 ++++++- .../AiAnalyzeSentimentTestsFabricDW.sql | 8 +- .../TestScripts/AiClassifyTestsFabricDW.sql | 7 +- .../TestScripts/AiExtractTestsFabricDW.sql | 7 +- .../TestScripts/AiFixGrammarTestsFabricDW.sql | 8 +- .../AiGenerateResponseTestsFabricDW.sql | 5 +- .../TestScripts/AiSummarizeTestsFabricDW.sql | 8 +- .../TestScripts/AiTranslateTestsFabricDW.sql | 6 +- ...atabaseScopedConfigTxnPriorityTests180.sql | 20 ++ ...CreateAlterTableClusterByTestsFabricDW.sql | 13 +- .../TestScripts/QueryHintsTestsFabricDW.sql | 41 +++ .../WindowClauseQuotedNameTests160.sql | 46 +++ Test/SqlDom/UnicodeNonCharacterLexerTests.cs | 319 ++++++++++++++++++ release-notes/180/180.140.0.md | 33 ++ 80 files changed, 2397 insertions(+), 307 deletions(-) create mode 100644 Test/SqlDom/Baselines160/WindowClauseQuotedNameTests160.sql create mode 100644 Test/SqlDom/Baselines170/WindowClauseQuotedNameTests160.sql create mode 100644 Test/SqlDom/Baselines180/AlterDatabaseScopedConfigTxnPriorityTests180.sql create mode 100644 Test/SqlDom/Baselines180/WindowClauseQuotedNameTests160.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/QueryHintsTestsFabricDW.sql create mode 100644 Test/SqlDom/BaselinesFabricDW/WindowClauseQuotedNameTests160.sql create mode 100644 Test/SqlDom/TestScripts/AlterDatabaseScopedConfigTxnPriorityTests180.sql create mode 100644 Test/SqlDom/TestScripts/QueryHintsTestsFabricDW.sql create mode 100644 Test/SqlDom/TestScripts/WindowClauseQuotedNameTests160.sql create mode 100644 Test/SqlDom/UnicodeNonCharacterLexerTests.cs create mode 100644 release-notes/180/180.140.0.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ae9e0439..99189c13 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @llali @allancascante @kburtram @aaskhan @benjind +* @llali @allancascante @kburtram @aaskhan @benjind @mhyon diff --git a/SqlScriptDom/Parser/TSql/Ast.xml b/SqlScriptDom/Parser/TSql/Ast.xml index e9c2d9eb..3e2f628f 100644 --- a/SqlScriptDom/Parser/TSql/Ast.xml +++ b/SqlScriptDom/Parser/TSql/Ast.xml @@ -3562,6 +3562,7 @@ + @@ -4827,34 +4828,52 @@ + + - + + + + + + + + + + + + + + + + + diff --git a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs index fff679b0..35093c7a 100644 --- a/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs +++ b/SqlScriptDom/Parser/TSql/CodeGenerationSupporter.cs @@ -870,6 +870,7 @@ internal static class CodeGenerationSupporter internal const string RemoteServiceName = "REMOTE_SERVICE_NAME"; internal const string Remove = "REMOVE"; internal const string Reorganize = "REORGANIZE"; + internal const string Redistribute = "REDISTRIBUTE"; internal const string Repeatable = "REPEATABLE"; internal const string RepeatableRead = "REPEATABLEREAD"; internal const string Replace = "REPLACE"; diff --git a/SqlScriptDom/Parser/TSql/JoinHint.cs b/SqlScriptDom/Parser/TSql/JoinHint.cs index be171367..fde9a4b2 100644 --- a/SqlScriptDom/Parser/TSql/JoinHint.cs +++ b/SqlScriptDom/Parser/TSql/JoinHint.cs @@ -30,6 +30,14 @@ public enum JoinHint /// /// REMOTE was used. /// - Remote = 4 + Remote = 4, + /// + /// REPLICATE was used. + /// + Replicate = 5, + /// + /// REDISTRIBUTE was used. + /// + Redistribute = 6 } } diff --git a/SqlScriptDom/Parser/TSql/TSql160.g b/SqlScriptDom/Parser/TSql/TSql160.g index 32b8d2cd..b3c9079f 100644 --- a/SqlScriptDom/Parser/TSql/TSql160.g +++ b/SqlScriptDom/Parser/TSql/TSql160.g @@ -32292,7 +32292,7 @@ regularBuiltInFunctionCall [FunctionCall vParent] UpdateTokenInfo(vParent,tRParen); } ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? @@ -32323,7 +32323,7 @@ ignoreRespectNullsRegularBuiltInFunctionCall [FunctionCall vParent] ignoreRespectNulls [vParent] )? ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? diff --git a/SqlScriptDom/Parser/TSql/TSql170.g b/SqlScriptDom/Parser/TSql/TSql170.g index 48cf386e..6ea56745 100644 --- a/SqlScriptDom/Parser/TSql/TSql170.g +++ b/SqlScriptDom/Parser/TSql/TSql170.g @@ -22209,14 +22209,14 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm { Match(tForce, CodeGenerationSupporter.Force); vResult.HintKind = OptimizerHintKind.ForceOrder; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } | Distributed tPlan1:Plan { Match(tForce, CodeGenerationSupporter.Force); vResult.HintKind = OptimizerHintKind.ForceDistributedPlan; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } | tSingle:Identifier tNode:Identifier tPlan2:Plan @@ -22225,7 +22225,7 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm Match(tSingle, CodeGenerationSupporter.Single); Match(tNode, CodeGenerationSupporter.GraphNode); // NODE vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } ) | tHash:Identifier Group @@ -33460,7 +33460,7 @@ regularBuiltInFunctionCall [FunctionCall vParent] UpdateTokenInfo(vParent,tRParen); } ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? @@ -33491,7 +33491,7 @@ ignoreRespectNullsRegularBuiltInFunctionCall [FunctionCall vParent] ignoreRespectNulls [vParent] )? ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? diff --git a/SqlScriptDom/Parser/TSql/TSql180.g b/SqlScriptDom/Parser/TSql/TSql180.g index df96536f..cbb915fe 100644 --- a/SqlScriptDom/Parser/TSql/TSql180.g +++ b/SqlScriptDom/Parser/TSql/TSql180.g @@ -2873,6 +2873,11 @@ alterDatabaseScopedGenericOption[bool forSecondary] returns [GenericConfiguratio } vResult.GenericOptionState = vValue; } + | + tRollback:Rollback + { + vResult.GenericOptionState = CreateIdentifierOrScalarExpressionFromIdentifier(CreateIdentifierFromToken(tRollback)); + } | vValue = stringOrSignedIntegerOrIdentifier { @@ -22438,14 +22443,14 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm { Match(tForce, CodeGenerationSupporter.Force); vResult.HintKind = OptimizerHintKind.ForceOrder; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } | Distributed tPlan1:Plan { Match(tForce, CodeGenerationSupporter.Force); vResult.HintKind = OptimizerHintKind.ForceDistributedPlan; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } | tSingle:Identifier tNode:Identifier tPlan2:Plan @@ -22454,7 +22459,7 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm Match(tSingle, CodeGenerationSupporter.Single); Match(tNode, CodeGenerationSupporter.GraphNode); // NODE vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } ) | tHash:Identifier Group @@ -33698,7 +33703,7 @@ regularBuiltInFunctionCall [FunctionCall vParent] UpdateTokenInfo(vParent,tRParen); } ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? @@ -33729,7 +33734,7 @@ ignoreRespectNullsRegularBuiltInFunctionCall [FunctionCall vParent] ignoreRespectNulls [vParent] )? ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? diff --git a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs index 5607c181..4c2c626a 100644 --- a/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSql80ParserBaseInternal.cs @@ -2365,12 +2365,15 @@ internal static ParseError ProcessTokenStreamRecognitionException(antlr.TokenStr antlr.NoViableAltForCharException notViableAltForCharException = exception.recog as antlr.NoViableAltForCharException; if (notViableAltForCharException != null) { + string foundChar = notViableAltForCharException.foundChar == antlr.CharScanner.EOF_CHAR + ? "" + : Convert.ToChar(notViableAltForCharException.foundChar).ToString(); return TSql80ParserBaseInternal.CreateParseError("SQL46010", lastOffset, notViableAltForCharException.getLine(), notViableAltForCharException.getColumn(), TSqlParserResource.SQL46010Message, - notViableAltForCharException.foundChar.ToString()); + foundChar); } // TODO, sacaglar: This is translated into an internal error. Is there a runtime log for this? diff --git a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g index 5f7808dd..b3125b2c 100644 --- a/SqlScriptDom/Parser/TSql/TSqlFabricDW.g +++ b/SqlScriptDom/Parser/TSql/TSqlFabricDW.g @@ -535,9 +535,6 @@ ctasCreateTableStatement [CreateTableStatement vParent] { vParent.SelectStatement = vSelectStatement; } - { - CheckCtasStatementHasDistributionOption(vParent); - } ; ///////////////////////////////////////////////// @@ -19536,28 +19533,37 @@ qualifiedJoin[SubDmlFlags subDmlFlags, ref TableReference vResult] ; joinHint[QualifiedJoin vParent] +{ + IntegerLiteral vColumnsCount; +} : ( tId1:Identifier ( - tId2:Identifier + LeftParenthesis vColumnsCount = integer RightParenthesis { - Match(tId1,CodeGenerationSupporter.Local); - vParent.JoinHint = JoinHintHelper.Instance.ParseOption(tId2); - if (vParent.JoinHint == JoinHint.Remote) - { - ThrowIncorrectSyntaxErrorException(tId2); - } - } - | - tMerge:Merge - { - Match(tId1,CodeGenerationSupporter.Local); - vParent.JoinHint = JoinHint.Merge; + Match(tId1,CodeGenerationSupporter.Redistribute); + vParent.JoinHint = JoinHint.Redistribute; + vParent.JoinHintColumnsCount = vColumnsCount; } | /* empty */ { - vParent.JoinHint = JoinHintHelper.Instance.ParseOption(tId1); + if (TryMatch(tId1, CodeGenerationSupporter.Replicate)) + { + vParent.JoinHint = JoinHint.Replicate; + } + else if (TryMatch(tId1, CodeGenerationSupporter.Redistribute)) + { + vParent.JoinHint = JoinHint.Redistribute; + } + else + { + vParent.JoinHint = JoinHintHelper.Instance.ParseOption(tId1); + if (vParent.JoinHint == JoinHint.Remote) + { + ThrowIncorrectSyntaxErrorException(tId1); + } + } } ) ) @@ -21417,9 +21423,10 @@ groupByClause returns [GroupByClause vResult = FragmentFactory.CreateFragment()] +{ + Literal vValue; +} + : tFor:For tTimestamp:Identifier As Of vValue = stringLiteral + { + Match(tTimestamp, CodeGenerationSupporter.TimeStamp); + vResult.HintKind = OptimizerHintKind.ForTimestampAsOf; + UpdateTokenInfo(vResult, tFor); + vResult.Value = vValue; + } + ; + tableHintsOptimizerHint returns [TableHintsOptimizerHint vResult = FragmentFactory.CreateFragment()] { SchemaObjectName vSchemaObjectName; @@ -22004,14 +22024,14 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm { Match(tForce, CodeGenerationSupporter.Force); vResult.HintKind = OptimizerHintKind.ForceOrder; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } | Distributed tPlan1:Plan { Match(tForce, CodeGenerationSupporter.Force); vResult.HintKind = OptimizerHintKind.ForceDistributedPlan; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } | tSingle:Identifier tNode:Identifier tPlan2:Plan @@ -22020,7 +22040,7 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm Match(tSingle, CodeGenerationSupporter.Single); Match(tNode, CodeGenerationSupporter.GraphNode); // NODE vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; - UpdateTokenInfo(vResult, tForce); + UpdateTokenInfo(vResult, tForce); } ) | tHash:Identifier Group @@ -22071,7 +22091,16 @@ simpleOptimizerHint returns [OptimizerHint vResult = FragmentFactory.CreateFragm Match(tFirstWord, CodeGenerationSupporter.Optimize); Match(tSecondWord, CodeGenerationSupporter.Correlated); vResult.HintKind = OptimizerHintKind.OptimizeCorrelatedUnionAll; - UpdateTokenInfo(vResult, tUnion2); + UpdateTokenInfo(vResult, tUnion2); + } + | tNodeWord:Identifier tPlanSingleNode:Plan + { + Match(tFirstWord, CodeGenerationSupporter.Force); + Match(tSecondWord, CodeGenerationSupporter.Single); + Match(tNodeWord, CodeGenerationSupporter.GraphNode); + vResult.HintKind = OptimizerHintKind.ForceSingleNodePlan; + UpdateTokenInfo(vResult, tFirstWord); + UpdateTokenInfo(vResult, tPlanSingleNode); } ) | tMonoHint:Identifier @@ -22199,19 +22228,6 @@ useHintClause returns [UseHintList vResult = FragmentFactory.CreateFragment()] -{ - Literal vValue; -} - : tFor:For tTimestamp:Identifier tAs:As tOf:Of vValue = stringLiteral - { - Match(tTimestamp, CodeGenerationSupporter.TimeStamp); - vResult.HintKind = OptimizerHintKind.ForTimestampAsOf; - vResult.Value = vValue; - UpdateTokenInfo(vResult, tFor); - } - ; - createRuleStatement returns [CreateRuleStatement vResult = this.FragmentFactory.CreateFragment()] { SchemaObjectName vSchemaObjectName; @@ -28027,6 +28043,8 @@ alterTableStatement returns [AlterTableStatement vResult = null] | vResult=alterTableDropTableElementStatement | {NextTokenMatches(CodeGenerationSupporter.Switch)}? vResult=alterTableSwitchStatement + | {NextTokenMatches(CodeGenerationSupporter.Cluster, 3)}? + vResult=alterTableAddClusterByStatement | ( (With vExistingRowsCheck = constraintEnforcement)? ( @@ -28047,7 +28065,6 @@ alterTableStatement returns [AlterTableStatement vResult = null] {NextTokenMatches(CodeGenerationSupporter.FileTableNamespace, 2)}? vResult=alterTableFileTableNamespaceStatement | vResult=alterTableSetStatement - | vResult=alterTableAddClusterByStatement ) { // Update position later, because instantiation is lazy @@ -28194,10 +28211,10 @@ alterTableAddClusterByStatement returns [AlterTableAddClusterByStatement vResult { ClusterByTableOption vClusterByOption; } - : tAdd:Add LeftParenthesis vClusterByOption = clusterByTableOption + : tWith:With LeftParenthesis vClusterByOption = clusterByTableOption { vResult.ClusterByOption = vClusterByOption; - UpdateTokenInfo(vResult, tAdd); + UpdateTokenInfo(vResult, tWith); } tRParen:RightParenthesis { @@ -32296,10 +32313,11 @@ withinGroupClause returns [WithinGroupClause vResult = FragmentFactory.CreateFra } ; -// AI_ANALYZE_SENTIMENT() +// AI_ANALYZE_SENTIMENT( [(ERROR | NULL | DEFAULT ) ON ERROR]) aiAnalyzeSentimentFunctionCall returns [AIAnalyzeSentimentFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vInput; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32310,15 +32328,25 @@ aiAnalyzeSentimentFunctionCall returns [AIAnalyzeSentimentFunctionCall vResult = { vResult.Input = vInput; } - RightParenthesis + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } ; -// AI_CLASSIFY(, [, ... up to 21]) +// AI_CLASSIFY(, [, ... up to 20] [(ERROR | NULL | DEFAULT ) ON ERROR]) // Input and labels accept any expression; type constraints are deferred to semantic/type phase. aiClassifyFunctionCall returns [AIClassifyFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vExpr; int labelsCount = 0; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32336,29 +32364,36 @@ aiClassifyFunctionCall returns [AIClassifyFunctionCall vResult = this.FragmentFa AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); labelsCount = 1; } - // additional labels up to 21 total + // additional labels up to 20 total ( Comma vExpr = expression { ++labelsCount; - if (labelsCount > 21) + if (labelsCount > 20) {ThrowParseErrorException("SQL46010", vExpr, TSqlParserResource.SQL46010Message, CodeGenerationSupporter.AIClassify); } AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); } )* + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? tRParen:RightParenthesis { UpdateTokenInfo(vResult, tRParen); } ; -// AI_EXTRACT(, [, ... up to 21]) +// AI_EXTRACT(, [, ... up to 20] [(ERROR | NULL | DEFAULT ) ON ERROR]) // Input and labels accept any expression; type constraints are deferred to semantic/type phase. aiExtractFunctionCall returns [AIExtractFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vExpr; int labelsCount = 0; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32376,27 +32411,34 @@ aiExtractFunctionCall returns [AIExtractFunctionCall vResult = this.FragmentFact AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); labelsCount = 1; } - // additional labels up to 21 total + // additional labels up to 20 total ( Comma vExpr = expression { ++labelsCount; - if (labelsCount > 21) + if (labelsCount > 20) {ThrowParseErrorException("SQL46010", vExpr, TSqlParserResource.SQL46010Message, CodeGenerationSupporter.AIExtract); } AddAndUpdateTokenInfo(vResult, vResult.Labels, vExpr); } )* + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? tRParen:RightParenthesis { UpdateTokenInfo(vResult, tRParen); } ; -// AI_FIX_GRAMMAR() +// AI_FIX_GRAMMAR( [(ERROR | NULL | DEFAULT ) ON ERROR]) aiFixGrammarFunctionCall returns [AIFixGrammarFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vInput; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32407,14 +32449,24 @@ aiFixGrammarFunctionCall returns [AIFixGrammarFunctionCall vResult = this.Fragme { vResult.Input = vInput; } - RightParenthesis + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } ; -// AI_GENERATE_RESPONSE([, ]) +// AI_GENERATE_RESPONSE([, ] [(ERROR | NULL | DEFAULT ) ON ERROR]) aiGenerateResponseFunctionCall returns [AIGenerateResponseFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vPart1; ScalarExpression vPart2; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32431,13 +32483,23 @@ aiGenerateResponseFunctionCall returns [AIGenerateResponseFunctionCall vResult = vResult.PromptPart2 = vPart2; } )? - RightParenthesis + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } ; -// AI_SUMMARIZE() +// AI_SUMMARIZE( [(ERROR | NULL | DEFAULT ) ON ERROR]) aiSummarizeFunctionCall returns [AISummarizeFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vInput; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32448,14 +32510,24 @@ aiSummarizeFunctionCall returns [AISummarizeFunctionCall vResult = this.Fragment { vResult.Input = vInput; } - RightParenthesis + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } ; -// AI_TRANSLATE(, ) +// AI_TRANSLATE(, [(ERROR | NULL | DEFAULT ) ON ERROR]) aiTranslateFunctionCall returns [AITranslateFunctionCall vResult = this.FragmentFactory.CreateFragment()] { ScalarExpression vInput; ScalarExpression vLang; + AIOnErrorClause vOnErrorClause; } : tFunc:Identifier LeftParenthesis { @@ -32470,7 +32542,50 @@ aiTranslateFunctionCall returns [AITranslateFunctionCall vResult = this.Fragment { vResult.Language = vLang; } - RightParenthesis + ( + vOnErrorClause = aiOnErrorClause + { + vResult.OnErrorClause = vOnErrorClause; + } + )? + tRParen:RightParenthesis + { + UpdateTokenInfo(vResult, tRParen); + } + ; + +aiOnErrorClause returns [AIOnErrorClause vResult = null] +{ + StringLiteral vDefaultValue; +} + : + ( + tErrorAction:Identifier + { + Match(tErrorAction, CodeGenerationSupporter.Error); + vResult = this.FragmentFactory.CreateFragment(); + UpdateTokenInfo(vResult, tErrorAction); + } + | + tNull:Null + { + vResult = this.FragmentFactory.CreateFragment(); + UpdateTokenInfo(vResult, tNull); + } + | + tDefault:Default vDefaultValue=stringLiteral + { + AIDefaultOnErrorClause vDefaultClause = this.FragmentFactory.CreateFragment(); + vDefaultClause.Value = vDefaultValue; + vResult = vDefaultClause; + UpdateTokenInfo(vResult, tDefault); + } + ) + On tError:Identifier + { + Match(tError, CodeGenerationSupporter.Error); + UpdateTokenInfo(vResult, tError); + } ; // INVOKE_EXTERNAL_API('', '' [, [, ... ]]) @@ -32604,7 +32719,7 @@ regularBuiltInFunctionCall [FunctionCall vParent] UpdateTokenInfo(vParent,tRParen); } ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? @@ -32635,7 +32750,7 @@ ignoreRespectNullsRegularBuiltInFunctionCall [FunctionCall vParent] ignoreRespectNulls [vParent] )? ( - {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier)) || + {(LA(1)==Over && (LA(2)==LeftParenthesis || LA(2)==Identifier || LA(2)==QuotedIdentifier)) || (NextTokenMatches(CodeGenerationSupporter.Within) && LA(2)==Group && LA(3)==LeftParenthesis) }? withinGroupOrOverClause [vParent] )? diff --git a/SqlScriptDom/Parser/TSql/TSqlLexerBaseInternal.cs b/SqlScriptDom/Parser/TSql/TSqlLexerBaseInternal.cs index 2835996d..76d5c3fd 100644 --- a/SqlScriptDom/Parser/TSql/TSqlLexerBaseInternal.cs +++ b/SqlScriptDom/Parser/TSql/TSqlLexerBaseInternal.cs @@ -34,6 +34,13 @@ public void InitializeForNewInput(int startOffset, int startLine, int startColum private int _complexTokenStartOffset = 0; protected int _currentLineStartOffset = 0; + /// + /// The kind of complex token currently being scanned. Recorded while scanning so + /// that, if end-of-input is reached before the token is closed, the correct + /// unterminated-token error can be raised (see ). + /// + private TokenKind _complexTokenKind = TokenKind.Common; + /// /// Used to be able to handle GO statement. /// @@ -55,6 +62,8 @@ public override void newline() protected internal override IToken makeToken(int t) { + // A token was produced successfully, so we are no longer inside a complex token. + _complexTokenKind = TokenKind.Common; return new TSqlParserToken( (TSqlTokenType)t, CurrentOffset - text.Length, @@ -80,6 +89,9 @@ protected enum TokenKind /// protected void checkEOF(TokenKind currentToken) { + // Remember which complex token we are scanning so handlePrematureEof can raise + // the right error if the closing delimiter is never found. + _complexTokenKind = currentToken; if (LA(1) == EOF_CHAR) { uponEOF(); @@ -94,17 +106,17 @@ protected void checkEOF(TokenKind currentToken) case TokenKind.QuotedIdentifier: error = TSql80ParserBaseInternal.CreateParseError("SQL46031", _complexTokenStartOffset, inputState.tokenStartLine, inputState.tokenStartColumn, - TSqlParserResource.SQL46031Message, getText().TrimEnd(EOF_CHAR)); + TSqlParserResource.SQL46031Message, getText()); break; case TokenKind.SqlCommandIdentifier: error = TSql80ParserBaseInternal.CreateParseError("SQL46033", _complexTokenStartOffset, inputState.tokenStartLine, inputState.tokenStartColumn, - TSqlParserResource.SQL46033Message, getText().TrimEnd(EOF_CHAR)); + TSqlParserResource.SQL46033Message, getText()); break; case TokenKind.String: error = TSql80ParserBaseInternal.CreateParseError("SQL46030", _complexTokenStartOffset, inputState.tokenStartLine, inputState.tokenStartColumn, - TSqlParserResource.SQL46030Message, getText().TrimEnd(EOF_CHAR)); + TSqlParserResource.SQL46030Message, getText()); break; case TokenKind.Common: default: @@ -121,6 +133,47 @@ protected void checkEOF(TokenKind currentToken) protected void beginComplexToken() { _complexTokenStartOffset = CurrentOffset; + // Record the kind of complex token from its opening delimiter so the correct + // unterminated-token error can still be raised when the token has no content + // before end-of-input (e.g. a lone quote at the end of the script). The + // content-loop checkEOF call is not reached at genuine EOF because the EOF + // sentinel is no longer a member of the content token sets. + switch (cached_LA1) + { + case '\'': // ascii string literal opens with ' + case 'n': // unicode string literal opens with n' (lexer is case-insensitive) + _complexTokenKind = TokenKind.String; + break; + case '[': + case '"': // delimited identifier opens with [ or " + _complexTokenKind = TokenKind.QuotedIdentifier; + break; + case '/': // multi-line comment opens with /* + _complexTokenKind = TokenKind.MultiLineComment; + break; + case '$': // sql command identifier opens with $( + _complexTokenKind = TokenKind.SqlCommandIdentifier; + break; + default: + _complexTokenKind = TokenKind.Common; + break; + } + } + + /// + /// Called by the lexer base when a character match fails at end-of-input. If we + /// are scanning a complex token (string literal, delimited identifier, or + /// multi-line comment), raise the specific unterminated-token error rather than a + /// generic mismatch. The EOF sentinel is no longer a member of the content token + /// sets, so the in-loop checkEOF call is not reached at genuine end-of-input; this + /// hook fires when the closing delimiter match fails instead. + /// + protected override void handlePrematureEof() + { + if (inputState.guessing == 0) + { + checkEOF(_complexTokenKind); + } } internal static bool IsValueTooLargeForTokenInteger(string source) diff --git a/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs b/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs index 6b1479ad..7043439f 100644 --- a/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs +++ b/SqlScriptDom/Parser/TSql/VectorMetricTypeHelper.cs @@ -6,8 +6,6 @@ -using static Microsoft.SqlServer.TransactSql.ScriptDom.SensitivityClassification; - namespace Microsoft.SqlServer.TransactSql.ScriptDom { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs index e5846571..553b2466 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiAnalyzeSentimentFunction.cs @@ -22,6 +22,7 @@ public override void ExplicitVisit(AIAnalyzeSentimentFunctionCall node) } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs index d6997cba..702f6b6d 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiClassifyFunction.cs @@ -38,6 +38,7 @@ public override void ExplicitVisit(AIClassifyFunctionCall node) } } + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs index 7ba23ad1..d0508e62 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiExtractFunction.cs @@ -39,6 +39,7 @@ public override void ExplicitVisit(AIExtractFunctionCall node) } } + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs index 3d9f8b34..909f938c 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiFixGrammarFunction.cs @@ -22,6 +22,7 @@ public override void ExplicitVisit(AIFixGrammarFunctionCall node) } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs index b9affe86..f101d745 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiGenerateResponseFunction.cs @@ -33,6 +33,7 @@ public override void ExplicitVisit(AIGenerateResponseFunctionCall node) GenerateFragmentIfNotNull(node.PromptPart2); } + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs index 3d73ae5a..5f5a3af1 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiSummarizeFunction.cs @@ -23,6 +23,7 @@ public override void ExplicitVisit(AISummarizeFunctionCall node) } GenerateSymbol(TSqlTokenType.LeftParenthesis); GenerateFragmentIfNotNull(node.Input); + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs index 10c56ed2..f6239179 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AiTranslateFunction.cs @@ -3,6 +3,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ +using System; using Microsoft.SqlServer.TransactSql.ScriptDom; namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator @@ -28,7 +29,47 @@ public override void ExplicitVisit(AITranslateFunctionCall node) GenerateSymbol(TSqlTokenType.Comma); GenerateSpace(); GenerateFragmentIfNotNull(node.Language); + GenerateSpaceAndFragmentIfNotNull(node.OnErrorClause); GenerateSymbol(TSqlTokenType.RightParenthesis); } + + /// + /// Emits ERROR ON ERROR behavior for AI functions. + /// + /// The error behavior clause to generate. + public override void ExplicitVisit(AIErrorOnErrorClause node) + { + GenerateIdentifier(CodeGenerationSupporter.Error); + GenerateSpaceAndKeyword(TSqlTokenType.On); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Error); + } + + /// + /// Emits NULL ON ERROR behavior for AI functions. + /// + /// The null behavior clause to generate. + public override void ExplicitVisit(AINullOnErrorClause node) + { + GenerateKeyword(TSqlTokenType.Null); + GenerateSpaceAndKeyword(TSqlTokenType.On); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Error); + } + + /// + /// Emits DEFAULT 'literal' ON ERROR behavior for AI functions. + /// + /// The default behavior clause to generate. + public override void ExplicitVisit(AIDefaultOnErrorClause node) + { + if (node.Value == null) + { + throw new InvalidOperationException("AIDefaultOnErrorClause.Value is required."); + } + + GenerateKeyword(TSqlTokenType.Default); + GenerateSpaceAndFragmentIfNotNull(node.Value); + GenerateSpaceAndKeyword(TSqlTokenType.On); + GenerateSpaceAndIdentifier(CodeGenerationSupporter.Error); + } } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddClusterByStatement.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddClusterByStatement.cs index b3356359..1f9beb06 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddClusterByStatement.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.AlterTableAddClusterByStatement.cs @@ -18,7 +18,7 @@ public override void ExplicitVisit(AlterTableAddClusterByStatement node) NewLineAndIndent(); - GenerateKeyword(TSqlTokenType.Add); + GenerateKeyword(TSqlTokenType.With); GenerateSpace(); if (node.ClusterByOption != null) { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs index ef0e005a..6f95d447 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Comments.cs @@ -103,6 +103,16 @@ protected void EmitLeadingComments(TSqlFragment fragment) /// /// The fragment about to be generated. protected void EmitGapComments(TSqlFragment fragment) + { + EmitGapComments(fragment, null); + } + + /// + /// Emits comments that appear before the current fragment, aligned at the specified point. + /// + /// The fragment about to be generated. + /// The alignment point for each emitted comment. + protected void EmitGapComments(TSqlFragment fragment, AlignmentPoint commentAlignmentPoint) { if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) { @@ -122,6 +132,11 @@ protected void EmitGapComments(TSqlFragment fragment) var token = _currentTokenStream[i]; if (IsCommentToken(token) && !_emittedComments.Contains(token)) { + if (commentAlignmentPoint != null) + { + Mark(commentAlignmentPoint); + } + EmitCommentToken(token, isLeading: true); _emittedComments.Add(token); _lastProcessedTokenIndex = i; @@ -162,6 +177,49 @@ protected void EmitPendingGapComments() } } + /// + /// Indicates whether a comment appears next in the original script, before the next SQL + /// keyword or expression. Spaces and line breaks between the current position and the + /// comment are ignored. + /// + /// + /// After the select list in: + /// + /// SELECT a, b + /// -- comment + /// FROM t + /// + /// this method returns , allowing the caller to put the comment on + /// its own line before emitting the FROM keyword. + /// + /// + /// when the next meaningful content to preserve is a comment; + /// otherwise, . + /// + protected bool HasPendingGapComments() + { + if (!_options.PreserveComments || _currentTokenStream == null) + { + return false; + } + + for (int i = _lastProcessedTokenIndex + 1; i < _currentTokenStream.Count; i++) + { + var token = _currentTokenStream[i]; + if (IsCommentToken(token) && !_emittedComments.Contains(token)) + { + return true; + } + + if (token.TokenType != TSqlTokenType.WhiteSpace) + { + return false; + } + } + + return false; + } + /// /// Emits trailing comments after the fragment, ONLY on the same line. /// Comments on their own line are left as gap comments for the next fragment. @@ -457,6 +515,16 @@ protected void UpdateLastProcessedIndex(TSqlFragment fragment) /// /// The fragment about to be generated. protected void HandleCommentsBeforeFragment(TSqlFragment fragment) + { + HandleCommentsBeforeFragment(fragment, null); + } + + /// + /// Handles comments before a fragment and aligns gap comments at the specified point. + /// + /// The fragment about to be generated. + /// The alignment point for gap comments. + protected void HandleCommentsBeforeFragment(TSqlFragment fragment, AlignmentPoint commentAlignmentPoint) { if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) { @@ -471,7 +539,76 @@ protected void HandleCommentsBeforeFragment(TSqlFragment fragment) } // Emit any comments in the gap between last processed token and this fragment - EmitGapComments(fragment); + EmitGapComments(fragment, commentAlignmentPoint); + } + + /// + /// Emits comments before a list item, including comments that the parser records at the + /// beginning of the item's own source range. + /// + /// The list item about to be generated. + /// The alignment point for emitted comments. + protected bool HandleCommentsBeforeListItem(TSqlFragment fragment, AlignmentPoint commentAlignmentPoint) + { + if (!_options.PreserveComments || _currentTokenStream == null || fragment == null) + { + return false; + } + + int emittedCommentCount = _emittedComments.Count; + HandleCommentsBeforeFragment(fragment, commentAlignmentPoint); + + int firstTokenIndex = fragment.FirstTokenIndex; + if (firstTokenIndex < 0 && fragment is ProcedureParameter parameter && parameter.VariableName != null) + { + firstTokenIndex = parameter.VariableName.FirstTokenIndex; + } + + if (firstTokenIndex < 0 || firstTokenIndex >= _currentTokenStream.Count) + { + return _emittedComments.Count > emittedCommentCount; + } + + int firstGapTokenIndex = firstTokenIndex; + while (firstGapTokenIndex > 0) + { + var precedingToken = _currentTokenStream[firstGapTokenIndex - 1]; + if (precedingToken.TokenType != TSqlTokenType.WhiteSpace && + precedingToken.TokenType != TSqlTokenType.Comma && + !IsCommentToken(precedingToken)) + { + break; + } + + firstGapTokenIndex--; + } + + for (int i = firstGapTokenIndex; i < firstTokenIndex; i++) + { + var token = _currentTokenStream[i]; + if (token.TokenType == TSqlTokenType.WhiteSpace || token.TokenType == TSqlTokenType.Comma) + { + continue; + } + + if (!IsCommentToken(token)) + { + break; + } + + if (!_emittedComments.Contains(token)) + { + Mark(commentAlignmentPoint); + EmitCommentToken(token, isLeading: true); + _emittedComments.Add(token); + if (i > _lastProcessedTokenIndex) + { + _lastProcessedTokenIndex = i; + } + } + } + + return _emittedComments.Count > emittedCommentCount; } /// diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs index 16bbaec0..e2a87111 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CommonPhrases.cs @@ -485,7 +485,54 @@ protected void GenerateProcedureOrFunctionParameters(IList p else { // The option produces its own leading new line before the first parameter. - GenerateFragmentList(parameters, ListGenerationOption.MultipleLineProcedureParameterOption); + if (_options.PreserveComments && _options.CommaPlacement == CommaPlacement.Leading) + { + GenerateMultilineProcedureParametersWithLeadingCommas(parameters); + } + else + { + GenerateFragmentList(parameters, ListGenerationOption.MultipleLineProcedureParameterOption); + } + } + } + + private void GenerateMultilineProcedureParametersWithLeadingCommas( + IList parameters) + { + PushNamedAlignmentScope(); + try + { + AlignmentPoint items = new AlignmentPoint(); + + for (int index = 0; index < parameters.Count; index++) + { + ProcedureParameter parameter = parameters[index]; + NewLine(); + + if (index == 0) + { + Indent(); + if (HandleCommentsBeforeListItem(parameter, items)) + { + Indent(); + } + Mark(items); + } + else + { + HandleCommentsBeforeListItem(parameter, items); + int indentColumns = _options.IndentationSize; + Indent(indentColumns >= LeadingCommaWidth ? indentColumns - LeadingCommaWidth : 0); + GenerateSymbol(TSqlTokenType.Comma); + GenerateLeadingCommaSpace(); + } + + GenerateFragmentIfNotNull(parameter); + } + } + finally + { + PopNamedAlignmentScope(); } } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs index c7c2fc6c..7e005bdc 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.FromClause.cs @@ -22,7 +22,15 @@ protected void GenerateFromClause(FromClause fromClause, AlignmentPoint clauseBo IList tableSources = fromClause.TableReferences; if (tableSources.Count > 0) { - GenerateSeparatorForFromClause(); + if (HasPendingGapComments()) + { + NewLine(); + } + else + { + GenerateSeparatorForFromClause(); + } + EmitPendingGapComments(); AlignmentPoint start = new AlignmentPoint(); MarkAndPushAlignmentPoint(start); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs index 92068d15..901b5e5e 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OptimizerHint.cs @@ -31,6 +31,20 @@ partial class SqlScriptGeneratorVisitor { OptimizerHintKind.ForceOrder, new List( ) { new IdentifierGenerator(CodeGenerationSupporter.Force, true), new KeywordGenerator(TSqlTokenType.Order), }}, + { OptimizerHintKind.ForceSingleNodePlan, new List( ) { + new IdentifierGenerator(CodeGenerationSupporter.Force, true), + new IdentifierGenerator(CodeGenerationSupporter.Single, true), + new IdentifierGenerator(CodeGenerationSupporter.GraphNode, true), + new KeywordGenerator(TSqlTokenType.Plan), }}, + { OptimizerHintKind.ForceDistributedPlan, new List( ) { + new IdentifierGenerator(CodeGenerationSupporter.Force, true), + new KeywordGenerator(TSqlTokenType.Distributed, true), + new KeywordGenerator(TSqlTokenType.Plan), }}, + { OptimizerHintKind.ForTimestampAsOf, new List( ) { + new KeywordGenerator(TSqlTokenType.For, true), + new IdentifierGenerator(CodeGenerationSupporter.TimeStamp, true), + new KeywordGenerator(TSqlTokenType.As, true), + new KeywordGenerator(TSqlTokenType.Of), }}, { OptimizerHintKind.HashGroup, new List( ) { new IdentifierGenerator(CodeGenerationSupporter.Hash, true), new KeywordGenerator(TSqlTokenType.Group), }}, @@ -105,16 +119,7 @@ partial class SqlScriptGeneratorVisitor new IdentifierGenerator(CodeGenerationSupporter.NoPerformanceSpool), }}, { OptimizerHintKind.Label, new List() { new IdentifierGenerator(CodeGenerationSupporter.Label, true), - new KeywordGenerator(TSqlTokenType.EqualsSign) }}, - { OptimizerHintKind.ForceSingleNodePlan, new List( ) { - new IdentifierGenerator(CodeGenerationSupporter.Force, true), - new IdentifierGenerator(CodeGenerationSupporter.Single, true), - new IdentifierGenerator(CodeGenerationSupporter.GraphNode, true), - new KeywordGenerator(TSqlTokenType.Plan) }}, - { OptimizerHintKind.ForceDistributedPlan, new List( ) { - new IdentifierGenerator(CodeGenerationSupporter.Force, true), - new KeywordGenerator(TSqlTokenType.Distributed, true), - new KeywordGenerator(TSqlTokenType.Plan) }} + new KeywordGenerator(TSqlTokenType.EqualsSign) }} }; public override void ExplicitVisit(LiteralOptimizerHint node) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs index a9d8a42a..a52d748d 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.OverClause.cs @@ -18,9 +18,7 @@ public override void ExplicitVisit(OverClause node) if (windowNameExists && !windowSpecExist) { - // An unparenthesized "OVER window_name" reference must be a plain identifier; it - // cannot be bracketed or recased. (Inside "OVER (window_name ...)" it may be.) - GenerateWithoutIdentifierFormatting(() => GenerateSpaceAndFragmentIfNotNull(node.WindowName)); + GenerateSpaceAndFragmentIfNotNull(node.WindowName); } else { diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs index 19de7755..19b2421a 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.QualifiedJoin.cs @@ -44,7 +44,19 @@ public override void ExplicitVisit(QualifiedJoin node) if (node.JoinHint != JoinHint.None) { GenerateSpace(); - JoinHintHelper.Instance.GenerateSourceForOption(_writer, node.JoinHint); + if (node.JoinHint == JoinHint.Replicate) + { + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.Replicate); + } + else if (node.JoinHint == JoinHint.Redistribute) + { + GenerateIdentifierWithoutCasing(CodeGenerationSupporter.Redistribute); + GenerateParenthesisedFragmentIfNotNull(node.JoinHintColumnsCount); + } + else + { + JoinHintHelper.Instance.GenerateSourceForOption(_writer, node.JoinHint); + } } GenerateSpaceAndKeyword(TSqlTokenType.Join); diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs index 7797f9cd..8666c42b 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.SelectScalarExpression.cs @@ -24,12 +24,46 @@ public override void ExplicitVisit(SelectScalarExpression node) if (node.ColumnName != null) { - GenerateSpaceAndKeyword(TSqlTokenType.As); + if (ShouldGenerateAsKeywordForColumnAlias(node)) + { + GenerateSpaceAndKeyword(TSqlTokenType.As); + } GenerateSpaceAndFragmentIfNotNull(node.ColumnName); } } } + private bool ShouldGenerateAsKeywordForColumnAlias(SelectScalarExpression node) + { + if (_options.ColumnAliasStyle != ColumnAliasStyle.Preserve) + { + return true; + } + + if (node?.Expression == null || node.ColumnName == null || node.ScriptTokenStream == null) + { + return true; + } + + int expressionIndex = node.Expression.LastTokenIndex; + int aliasIndex = node.ColumnName.FirstTokenIndex; + if (expressionIndex < 0 || aliasIndex < 0 || expressionIndex >= aliasIndex || + aliasIndex >= node.ScriptTokenStream.Count) + { + return true; + } + + for (int tokenIndex = expressionIndex + 1; tokenIndex < aliasIndex; tokenIndex++) + { + if (node.ScriptTokenStream[tokenIndex].TokenType == TSqlTokenType.As) + { + return true; + } + } + + return false; + } + // Determines whether a column alias should be rendered as "alias = expression" // (as opposed to "expression AS alias") based on the ColumnAliasStyle option. private bool UseEqualsSignForColumnAlias(SelectScalarExpression node) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs index 519d5941..cc3792ad 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.UnqualifiedJoin.cs @@ -28,13 +28,14 @@ public override void ExplicitVisit(UnqualifiedJoin node) { GenerateFragmentIfNotNull(node.FirstTableReference); + GenerateNewLineOrSpace(_options.NewLineBeforeJoinClause); + // Emit any pending gap comments before JOIN keywords EmitPendingGapComments(); List generators = GetValueForEnumKey(_unqualifiedJoinTypeGenerators, node.UnqualifiedJoinType); if (generators != null) { - GenerateSpace(); GenerateTokenList(generators); } diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs index cdefa265..b9d79dd5 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.Utils.cs @@ -460,24 +460,29 @@ protected void GenerateFragmentList(IList list, ListGenerationOption optio for (int indentIterator = 0; indentIterator < option.MultipleIndentItems; indentIterator++) Indent(); } - else if (option.MultipleIndentItems >= 1) - { - // Leading comma placement in an indented list: reserve the comma width inside - // the indentation so the item stays at the normal list indentation column and - // the comma is indented LeadingCommaWidth characters fewer. - int listIndentColumns = option.MultipleIndentItems * _options.IndentationSize; - Indent(listIndentColumns >= LeadingCommaWidth ? listIndentColumns - LeadingCommaWidth : 0); - - GenerateSymbol(TSqlTokenType.Comma); - GenerateLeadingCommaSpace(); - } else { - // Leading comma placement in a keyword-aligned list (no fixed indentation, e.g. - // the SELECT column list): the comma is emitted as a right-aligned separator so - // it ends exactly before the aligned item column, keeping items aligned with - // the first element and the comma just before each of them. - GenerateRightAlignedCommaSeparator(); + HandleCommentsBeforeListItem(item, items); + + if (option.MultipleIndentItems >= 1) + { + // Leading comma placement in an indented list: reserve the comma width inside + // the indentation so the item stays at the normal list indentation column and + // the comma is indented LeadingCommaWidth characters fewer. + int listIndentColumns = option.MultipleIndentItems * _options.IndentationSize; + Indent(listIndentColumns >= LeadingCommaWidth ? listIndentColumns - LeadingCommaWidth : 0); + + GenerateSymbol(TSqlTokenType.Comma); + GenerateLeadingCommaSpace(); + } + else + { + // Leading comma placement in a keyword-aligned list (no fixed indentation, e.g. + // the SELECT column list): the comma is emitted as a right-aligned separator so + // it ends exactly before the aligned item column, keeping items aligned with + // the first element and the comma just before each of them. + GenerateRightAlignedCommaSeparator(); + } } if (option.NewLineBeforeItems) diff --git a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml index a7c86591..2ee4a866 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml +++ b/SqlScriptDom/ScriptDom/SqlServer/Settings/SqlScriptGeneratorOptions.xml @@ -49,7 +49,7 @@ IncludeSemicolons_Title IncludeSemiColons_Description - Gets or sets a boolean indicating if a semi colon should be included after each statement + DEPRECATED: This option is non-functional and always behaves as if set to true. Semicolons are always included after statements regardless of this setting. This property is retained for API compatibility only and will be removed in a future version. Gets or sets a boolean indicating if a semicolon terminator is written after a BEGIN...END block and after the END CATCH of a BEGIN TRY...END TRY BEGIN CATCH...END CATCH block. When false (the default), these blocks are written without a terminator, preserving the previous script-generation behavior. When true, a semicolon is appended, so a terminator supplied in the source script survives a parse and generate round-trip. END TRY is never terminated because it is internal to the TRY...CATCH block. diff --git a/SqlScriptDom/antlr/antlr/CharScanner.cs b/SqlScriptDom/antlr/antlr/CharScanner.cs index 004c5e39..9957a077 100644 --- a/SqlScriptDom/antlr/antlr/CharScanner.cs +++ b/SqlScriptDom/antlr/antlr/CharScanner.cs @@ -28,7 +28,11 @@ namespace antlr internal abstract class CharScanner : TokenStream { internal const char NO_CHAR = (char) (0); - public static readonly char EOF_CHAR = Char.MaxValue; + // EOF is represented by a value OUTSIDE the 16-bit char range so that a real + // character equal to U+FFFF (char.MaxValue) in the input is not mistaken for + // end-of-input. Real EOF is produced only by the input buffer once the + // underlying reader is exhausted (detected by stream position, not by value). + public const int EOF_CHAR = Char.MaxValue + 1; // NOTE, olegr: Appears to be not used... //// Used to store event delegates @@ -64,10 +68,12 @@ internal abstract class CharScanner : TokenStream /// Used for creating Token instances. protected TokenCreator tokenCreator; - /// Used for caching lookahead characters. - protected char cached_LA1; - protected char cached_LA2; - protected char cached_LA3; + /// Used for caching lookahead characters. Typed as int so the + /// out-of-char-range EOF_CHAR sentinel can be represented distinctly from a + /// real U+FFFF character. + protected int cached_LA1; + protected int cached_LA2; + protected int cached_LA3; protected bool caseSensitive = true; protected bool caseSensitiveLiterals = true; @@ -149,13 +155,13 @@ public virtual void consume() { if (caseSensitive) { - append(cached_LA1); + append((char) cached_LA1); } else { // use input.LA(), not LA(), to get original case // CharScanner.LA() would toLower it. - append(inputState.input.LA(1)); + append((char) inputState.input.LA(1)); } if (cached_LA1 == '\t') { @@ -259,7 +265,7 @@ public virtual IToken getTokenObject() return returnToken_; } - public virtual char LA(int i) + public virtual int LA(int i) { if (i == 1) { @@ -328,6 +334,10 @@ public virtual void match(int c) { if (cached_LA1 != c) { + if (cached_LA1 == EOF_CHAR) + { + handlePrematureEof(); + } throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), false, this); } consume(); @@ -337,6 +347,10 @@ public virtual void match(BitSet b) { if (!b.member(cached_LA1)) { + if (cached_LA1 == EOF_CHAR) + { + handlePrematureEof(); + } throw new MismatchedCharException(cached_LA1, b, false, this); } consume(); @@ -349,6 +363,10 @@ public virtual void match(string s) { if (cached_LA1 != s[i]) { + if (cached_LA1 == EOF_CHAR) + { + handlePrematureEof(); + } throw new MismatchedCharException(cached_LA1, s[i], false, this); } consume(); @@ -383,6 +401,15 @@ public virtual void matchRange(char c1, char c2) matchRange((int) c1, (int) c2); } + /// + /// Hook invoked when a character match fails because the next lookahead is the + /// EOF sentinel. Subclasses can override to raise a context-specific error + /// (e.g. an unterminated string literal, delimited identifier, or comment). + /// + protected virtual void handlePrematureEof() + { + } + public virtual void newline() { inputState.line++; @@ -594,8 +621,13 @@ public virtual int testLiteralsTable(string someText, int ttype) } // Override this method to get more specific case handling - public virtual char toLower(int c) + public virtual int toLower(int c) { + // Keep any out-of-range sentinel unchanged before converting to char. + // EOF_CHAR is above the range; the lower-bound check also prevents a + // negative sentinel from being narrowed. + if (c < 0 || c > Char.MaxValue) + return c; return Char.ToLower(Convert.ToChar(c), System.Globalization.CultureInfo.InvariantCulture); } diff --git a/SqlScriptDom/antlr/antlr/InputBuffer.cs b/SqlScriptDom/antlr/antlr/InputBuffer.cs index 1417db58..5f3eb42f 100644 --- a/SqlScriptDom/antlr/antlr/InputBuffer.cs +++ b/SqlScriptDom/antlr/antlr/InputBuffer.cs @@ -68,7 +68,7 @@ public virtual void commit() } /*Mark another character for deferred consumption */ - public virtual char consume() + public virtual int consume() { numToConsume++; return LA(1); @@ -107,10 +107,13 @@ public virtual bool isMarked() } /*Get a lookahead character */ - public virtual char LA(int i) + public virtual int LA(int i) { fill(i); - return (char) queue[markerOffset + i - 1]; + // Entries are boxed char values for real input and a boxed int sentinel + // (CharScanner.EOF_CHAR) for end-of-input; Convert.ToInt32 handles both so a + // real U+FFFF (65535) stays distinct from the EOF sentinel (65536). + return Convert.ToInt32(queue[markerOffset + i - 1]); } /*Return an integer marker that can be used to rewind the buffer to diff --git a/SqlScriptDom/antlr/antlr/MismatchedCharException.cs b/SqlScriptDom/antlr/antlr/MismatchedCharException.cs index 691fd271..0874bd3f 100644 --- a/SqlScriptDom/antlr/antlr/MismatchedCharException.cs +++ b/SqlScriptDom/antlr/antlr/MismatchedCharException.cs @@ -152,6 +152,36 @@ public MismatchedCharException(char c, BitSet set_, bool matchNot, CharScanner s scanner = scanner_; } + // int overloads so the lexer can pass a lookahead that may be the + // out-of-char-range EOF sentinel without a cast/overflow at the call site. + public MismatchedCharException(int c, char lower, char upper_, bool matchNot, CharScanner scanner_) : + base("Mismatched char", scanner_.getFilename(), scanner_.getLine(), scanner_.getColumn()) + { + mismatchType = matchNot ? CharTypeEnum.NotRangeType : CharTypeEnum.RangeType; + foundChar = c; + expecting = lower; + upper = upper_; + scanner = scanner_; + } + + public MismatchedCharException(int c, char expecting_, bool matchNot, CharScanner scanner_) : + base("Mismatched char", scanner_.getFilename(), scanner_.getLine(), scanner_.getColumn()) + { + mismatchType = matchNot ? CharTypeEnum.NotCharType : CharTypeEnum.CharType; + foundChar = c; + expecting = expecting_; + scanner = scanner_; + } + + public MismatchedCharException(int c, BitSet set_, bool matchNot, CharScanner scanner_) : + base("Mismatched char", scanner_.getFilename(), scanner_.getLine(), scanner_.getColumn()) + { + mismatchType = matchNot ? CharTypeEnum.NotSetType : CharTypeEnum.SetType; + foundChar = c; + bset = set_; + scanner = scanner_; + } + protected MismatchedCharException(SerializationInfo info, StreamingContext context) : base(info, context) { } @@ -165,8 +195,7 @@ private static void appendCharName(StringBuilder sb, int c) { switch (c) { - case 65535 : - // 65535 = (char) -1 = EOF + case CharScanner.EOF_CHAR : sb.Append("''"); break; case '\n' : diff --git a/SqlScriptDom/antlr/antlr/NoViableAltForCharException.cs b/SqlScriptDom/antlr/antlr/NoViableAltForCharException.cs index 7f452c70..6b017bfc 100644 --- a/SqlScriptDom/antlr/antlr/NoViableAltForCharException.cs +++ b/SqlScriptDom/antlr/antlr/NoViableAltForCharException.cs @@ -23,7 +23,7 @@ namespace antlr [Serializable] internal class NoViableAltForCharException : RecognitionException { - public char foundChar; + public int foundChar; public NoViableAltForCharException(char c, CharScanner scanner) : base("NoViableAlt", scanner.getFilename(), scanner.getLine(), scanner.getColumn()) @@ -37,6 +37,20 @@ public NoViableAltForCharException(char c, string fileName, int line, int column foundChar = c; } + // int overloads so the generated lexer can pass a lookahead that may be the + // out-of-char-range EOF sentinel without a cast/overflow at the call site. + public NoViableAltForCharException(int c, CharScanner scanner) : + base("NoViableAlt", scanner.getFilename(), scanner.getLine(), scanner.getColumn()) + { + foundChar = c; + } + + public NoViableAltForCharException(int c, string fileName, int line, int column) : + base("NoViableAlt", fileName, line, column) + { + foundChar = c; + } + protected NoViableAltForCharException(SerializationInfo info, StreamingContext context) : base(info, context) { } @@ -54,16 +68,20 @@ override public string Message // But java seems to lack something isprint-ish.. // so we do it manually. This is probably too restrictive. - if ((foundChar >= ' ') && (foundChar <= '~')) + if (foundChar == CharScanner.EOF_CHAR) + { + mesg.Append(""); + } + else if ((foundChar >= ' ') && (foundChar <= '~')) { mesg.Append('\''); - mesg.Append(foundChar); + mesg.Append((char) foundChar); mesg.Append('\''); } else { mesg.Append("0x"); - mesg.Append(((int)foundChar).ToString("X", CultureInfo.InvariantCulture)); + mesg.Append(foundChar.ToString("X", CultureInfo.InvariantCulture)); } return mesg.ToString(); } diff --git a/Test/SqlDom/Baselines110/OffsetClause.sql b/Test/SqlDom/Baselines110/OffsetClause.sql index 43cc3b8e..d7749ca5 100644 --- a/Test/SqlDom/Baselines110/OffsetClause.sql +++ b/Test/SqlDom/Baselines110/OffsetClause.sql @@ -41,10 +41,11 @@ ORDER BY a OFFSET (sum(5)) ROWS FETCH NEXT 6 ROWS ONLY; SELECT * -FROM t1 CROSS APPLY (SELECT * - FROM sys.objects - ORDER BY 1 - OFFSET offset ROWS FETCH NEXT first ROWS ONLY) AS t1; +FROM t1 + CROSS APPLY (SELECT * + FROM sys.objects + ORDER BY 1 + OFFSET offset ROWS FETCH NEXT first ROWS ONLY) AS t1; INSERT INTO t SELECT * diff --git a/Test/SqlDom/Baselines130/FromClauseTests130.sql b/Test/SqlDom/Baselines130/FromClauseTests130.sql index 88aed9e5..9bf8769d 100644 --- a/Test/SqlDom/Baselines130/FromClauseTests130.sql +++ b/Test/SqlDom/Baselines130/FromClauseTests130.sql @@ -25,7 +25,8 @@ SELECT * FROM OPENJSON (@var, N'$') WITH (a INT, b VARCHAR (400), c NVARCHAR (MAX) COLLATE Latin1_General_Bin2 N'$.b.c'); SELECT * -FROM Orders CROSS APPLY OPENJSON (Orders.Data, N'$.orderLineItems') WITH (ProductId VARCHAR (200) N'$.productId'); +FROM Orders + CROSS APPLY OPENJSON (Orders.Data, N'$.orderLineItems') WITH (ProductId VARCHAR (200) N'$.productId'); SELECT * FROM OPENJSON (col, N'$') WITH (a INT, b VARCHAR (400), c NVARCHAR (MAX) COLLATE Latin1_General_Bin2 N'$.b.c'); @@ -58,19 +59,23 @@ SELECT * FROM string_split (NULL, N','); SELECT t2.value -FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-') AS t1 CROSS APPLY String_Split (t1.value, ' ') AS t2; +FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-') AS t1 + CROSS APPLY String_Split (t1.value, ' ') AS t2; SELECT t2.ordinal -FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-', 1) AS t1 CROSS APPLY String_Split (t1.ordinal, ' ') AS t2; +FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-', 1) AS t1 + CROSS APPLY String_Split (t1.ordinal, ' ') AS t2; SELECT value -FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) CROSS APPLY STRING_SPLIT (col, ','); +FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) + CROSS APPLY STRING_SPLIT (col, ','); SELECT ordinal -FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) CROSS APPLY STRING_SPLIT (col, ',', 1); +FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) + CROSS APPLY STRING_SPLIT (col, ',', 1); SELECT * FROM [STRING_SPLIT] (@var, @sep); SELECT * -FROM "STRING_SPLIT" (@var, @sep); +FROM "STRING_SPLIT" (@var, @sep); \ No newline at end of file diff --git a/Test/SqlDom/Baselines150/FromClauseTests150.sql b/Test/SqlDom/Baselines150/FromClauseTests150.sql index b7a5b474..6f2b8b15 100644 --- a/Test/SqlDom/Baselines150/FromClauseTests150.sql +++ b/Test/SqlDom/Baselines150/FromClauseTests150.sql @@ -11,16 +11,20 @@ SELECT ordinal FROM STRING_SPLIT (N'Lorem ipsum dolor sit amet.', N' ', 1); SELECT t2.value -FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-', 0) AS t1 CROSS APPLY String_Split (t1.value, ' ') AS t2; +FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-', 0) AS t1 + CROSS APPLY String_Split (t1.value, ' ') AS t2; SELECT t2.ordinal -FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-', 1) AS t1 CROSS APPLY String_Split (t1.ordinal, ' ') AS t2; +FROM String_Split ('Lorem-ipsum dolor-sit amet.', '-', 1) AS t1 + CROSS APPLY String_Split (t1.ordinal, ' ') AS t2; SELECT value -FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) CROSS APPLY STRING_SPLIT (col, ',', 0); +FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) + CROSS APPLY STRING_SPLIT (col, ',', 0); SELECT ordinal -FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) CROSS APPLY STRING_SPLIT (col, ',', 1); +FROM (VALUES ('Lorem ipsum'), ('dolor sit amet.')) AS x(col) + CROSS APPLY STRING_SPLIT (col, ',', 1); SELECT * FROM CHANGETABLE(CHANGES t1, 10, FORCESEEK) AS a; diff --git a/Test/SqlDom/Baselines160/WindowClauseQuotedNameTests160.sql b/Test/SqlDom/Baselines160/WindowClauseQuotedNameTests160.sql new file mode 100644 index 00000000..8a5ee8a2 --- /dev/null +++ b/Test/SqlDom/Baselines160/WindowClauseQuotedNameTests160.sql @@ -0,0 +1,46 @@ +CREATE PROCEDURE [dbo].[ExampleProc] +AS +BEGIN + SELECT ROW_NUMBER() OVER [win] AS [RowNum], + SUM([Amount]) OVER [win] AS [RunningTotal] + FROM [dbo].[Transactions] + WINDOW [win] AS (PARTITION BY [AccountID] ORDER BY [TransactionDate]); +END + + +GO +SELECT COUNT(*) OVER [win] +FROM t1 +WINDOW [win] AS (PARTITION BY c1); + + +GO +SELECT LAST_VALUE(c1) IGNORE NULLS OVER [win] +FROM t1 +WINDOW [win] AS (ORDER BY c2); + + +GO +SELECT LAG(c1) OVER [my win] +FROM t1 +WINDOW [my win] AS (ORDER BY c2); + + +GO +SELECT SUM(c1) OVER [select] +FROM t1 +WINDOW [select] AS (PARTITION BY c2); + + +GO +SELECT SUM(c1) OVER "win" +FROM t1 +WINDOW "win" AS (PARTITION BY c2); + + +GO +CREATE VIEW v1 +AS +SELECT AVG(c1) OVER [win] AS a +FROM t1 +WINDOW [win] AS ([base] ORDER BY c2), [base] AS (PARTITION BY c3); diff --git a/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql b/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql index ef7cb3c0..d1a3530f 100644 --- a/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql +++ b/Test/SqlDom/Baselines170/AiGenerateChunksTests170.sql @@ -20,13 +20,16 @@ SELECT * FROM AI_GENERATE_CHUNKS (SOURCE = NULL, CHUNK_TYPE = fixed, CHUNK_SIZE = 5); SELECT * -FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t1.c1, CHUNK_TYPE = fixed, CHUNK_SIZE = 10); +FROM t1 + CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t1.c1, CHUNK_TYPE = fixed, CHUNK_SIZE = 10); SELECT * -FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = t1.c1); +FROM t1 + CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = t1.c1); SELECT * -FROM t1 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = t1.c1); +FROM t1 + CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = 'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = 10, OVERLAP = t1.c1); SELECT * FROM AI_GENERATE_CHUNKS (SOURCE = N'some text', CHUNK_TYPE = fixed, CHUNK_SIZE = NULL); @@ -53,7 +56,8 @@ CREATE VIEW v_GeneratedChunksFromTable AS SELECT t2.Id, chunks.* -FROM t2 CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t2.Text, CHUNK_TYPE = fixed, CHUNK_SIZE = 5) AS chunks; +FROM t2 + CROSS APPLY AI_GENERATE_CHUNKS (SOURCE = t2.Text, CHUNK_TYPE = fixed, CHUNK_SIZE = 5) AS chunks; GO CREATE PROCEDURE usp_GenerateChunks @@ -79,17 +83,21 @@ CREATE TABLE dbo.AI_GENERATE_CHUNKS ( ); SELECT SOURCE -FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS(target); +FROM userTable + CROSS APPLY dbo.AI_GENERATE_CHUNKS(target); SELECT SOURCE -FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS](SOURCE); +FROM userTable + CROSS APPLY dbo.[AI_GENERATE_CHUNKS](SOURCE); SELECT SOURCE -FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS([SOURCE]); +FROM userTable + CROSS APPLY dbo.AI_GENERATE_CHUNKS([SOURCE]); SELECT SOURCE -FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS]([SOURCE]); +FROM userTable + CROSS APPLY dbo.[AI_GENERATE_CHUNKS]([SOURCE]); SELECT * FROM dbo.AI_GENERATE_CHUNKS(3); \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/ComplexQueryTests170.sql b/Test/SqlDom/Baselines170/ComplexQueryTests170.sql index 3e2cb7bc..581b6752 100644 --- a/Test/SqlDom/Baselines170/ComplexQueryTests170.sql +++ b/Test/SqlDom/Baselines170/ComplexQueryTests170.sql @@ -1,8 +1,9 @@ SELECT 139 AS [p_1_0] -FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN (([dbo].[table_6] AS [alias_1_4] - RIGHT OUTER JOIN - [dbo].[table_3] AS [alias_1_5] - ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3))))); +FROM ([dbo].[table_0] AS [alias_1_0] + CROSS JOIN (([dbo].[table_6] AS [alias_1_4] + RIGHT OUTER JOIN + [dbo].[table_3] AS [alias_1_5] + ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3))))); SELECT CAST ('test' AS VECTOR(3, Float32)); @@ -15,34 +16,40 @@ SELECT 1 WHERE col IN (SELECT CAST ('test' AS VECTOR(3, Float32))); SELECT CAST ($492050157978986.2129 AS MONEY) AS [p_0_0] -FROM ([dbo].[table_6] AS [alias_0_0] CROSS JOIN [dbo].[table_4] AS [alias_0_1]) +FROM ([dbo].[table_6] AS [alias_0_0] + CROSS JOIN [dbo].[table_4] AS [alias_0_1]) WHERE (NOT (SYSDATETIME() IN (SELECT 139 AS [p_1_0] - FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN ([dbo].[table_6] AS [alias_1_1] - LEFT OUTER JOIN - ([dbo].[table_6] AS [alias_1_2] - INNER JOIN - ([dbo].[table_5] AS [alias_1_3] CROSS APPLY ([dbo].[table_6] AS [alias_1_4] - RIGHT OUTER JOIN - [dbo].[table_3] AS [alias_1_5] - ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3, Float32)))) - ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) - ON [alias_1_1].[c_1] = CONVERT (VECTOR(77), '[-7.230808E+08,4.075427E+08]')))) + FROM ([dbo].[table_0] AS [alias_1_0] + CROSS JOIN ([dbo].[table_6] AS [alias_1_1] + LEFT OUTER JOIN + ([dbo].[table_6] AS [alias_1_2] + INNER JOIN + ([dbo].[table_5] AS [alias_1_3] + CROSS APPLY ([dbo].[table_6] AS [alias_1_4] + RIGHT OUTER JOIN + [dbo].[table_3] AS [alias_1_5] + ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3, Float32)))) + ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) + ON [alias_1_1].[c_1] = CONVERT (VECTOR(77), '[-7.230808E+08,4.075427E+08]')))) OR (CONVERT (BIGINT, CONVERT (INT, 8)) >= 157) OR (140 <= 19))); SELECT CAST ($492050157978986.2129 AS MONEY) AS [p_0_0] -FROM ([dbo].[table_6] AS [alias_0_0] CROSS JOIN [dbo].[table_4] AS [alias_0_1]) +FROM ([dbo].[table_6] AS [alias_0_0] + CROSS JOIN [dbo].[table_4] AS [alias_0_1]) WHERE (NOT (SYSDATETIME() IN (SELECT 139 AS [p_1_0] - FROM ([dbo].[table_0] AS [alias_1_0] CROSS JOIN ([dbo].[table_6] AS [alias_1_1] - LEFT OUTER JOIN - ([dbo].[table_6] AS [alias_1_2] - INNER JOIN - ([dbo].[table_5] AS [alias_1_3] CROSS APPLY ([dbo].[table_6] AS [alias_1_4] - RIGHT OUTER JOIN - [dbo].[table_3] AS [alias_1_5] - ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3)))) - ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) - ON [alias_1_1].[c_1] = CONVERT (VECTOR(77), '[-7.230808E+08,4.075427E+08]')))) + FROM ([dbo].[table_0] AS [alias_1_0] + CROSS JOIN ([dbo].[table_6] AS [alias_1_1] + LEFT OUTER JOIN + ([dbo].[table_6] AS [alias_1_2] + INNER JOIN + ([dbo].[table_5] AS [alias_1_3] + CROSS APPLY ([dbo].[table_6] AS [alias_1_4] + RIGHT OUTER JOIN + [dbo].[table_3] AS [alias_1_5] + ON [alias_1_4].[c_19] = CAST ('[-6.464173E+08,1.040823E+07,1.699169E+08]' AS VECTOR(3)))) + ON [alias_1_2].[c_14] = [alias_1_3].[c_13]) + ON [alias_1_1].[c_1] = CONVERT (VECTOR(77), '[-7.230808E+08,4.075427E+08]')))) OR (CONVERT (BIGINT, CONVERT (INT, 8)) >= 157) OR (140 <= 19))); @@ -50,17 +57,19 @@ SELECT TOP 100 t1.order_id, t1.customer_id, t2.product_name, t3.category_name -FROM ([dbo].[orders] AS t1 CROSS JOIN ([dbo].[order_items] AS t2 - LEFT OUTER JOIN - ([dbo].[products] AS t3 - INNER JOIN - ([dbo].[categories] AS t4 CROSS APPLY ([dbo].[suppliers] AS t5 - RIGHT OUTER JOIN - [dbo].[regions] AS t6 - ON t5.region_id = t6.id - AND t5.active = 1)) - ON t3.category_id = t4.id) - ON t2.product_id = t3.id)) +FROM ([dbo].[orders] AS t1 + CROSS JOIN ([dbo].[order_items] AS t2 + LEFT OUTER JOIN + ([dbo].[products] AS t3 + INNER JOIN + ([dbo].[categories] AS t4 + CROSS APPLY ([dbo].[suppliers] AS t5 + RIGHT OUTER JOIN + [dbo].[regions] AS t6 + ON t5.region_id = t6.id + AND t5.active = 1)) + ON t3.category_id = t4.id) + ON t2.product_id = t3.id)) WHERE (t1.order_date >= '2025-01-01' AND t2.quantity > 0 AND EXISTS (SELECT 1 diff --git a/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql b/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql index 958e8a47..563d5fff 100644 --- a/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql +++ b/Test/SqlDom/Baselines170/VectorSearchApproximateTests170.sql @@ -1,13 +1,14 @@ SELECT TOP 10 WITH APPROXIMATE qt.qid, src.id, ann.distance -FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( - TABLE = graphnode AS src, - COLUMN = embedding, - SIMILAR_TO = qt.qembedding, - METRIC = 'euclidean', - TOP_N = 10 - ) AS ann +FROM QueryTable AS qt + CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann ORDER BY ann.distance; @@ -15,13 +16,14 @@ GO SELECT TOP 10 WITH APPROXIMATE qt.qid, src.id, ann.distance -FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( - TABLE = graphnode AS src, - COLUMN = embedding, - SIMILAR_TO = qt.qembedding, - METRIC = 'euclidean', - TOP_N = 10 - ) AS ann +FROM QueryTable AS qt + CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann ORDER BY ann.distance; @@ -29,13 +31,14 @@ GO SELECT qt.qid, src.id, ann.distance -FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( - TABLE = graphnode AS src, - COLUMN = embedding, - SIMILAR_TO = qt.qembedding, - METRIC = 'euclidean', - TOP_N = 10 - ) AS ann +FROM QueryTable AS qt + CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann ORDER BY ann.distance FETCH APPROXIMATE NEXT 10 ROWS ONLY; @@ -44,12 +47,13 @@ GO SELECT qt.qid, src.id, ann.distance -FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( - TABLE = graphnode AS src, - COLUMN = embedding, - SIMILAR_TO = qt.qembedding, - METRIC = 'euclidean', - TOP_N = 10 - ) AS ann +FROM QueryTable AS qt + CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = 10 + ) AS ann ORDER BY ann.distance FETCH APPROXIMATE NEXT 10 ROWS ONLY; \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql b/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql index 3e715b61..e22e5886 100644 --- a/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql +++ b/Test/SqlDom/Baselines170/VectorSearchCrossApplyTests170.sql @@ -3,10 +3,11 @@ DECLARE @qv AS VECTOR(1536); SELECT qt.qid, src.id, ann.distance -FROM QueryTable AS qt CROSS APPLY VECTOR_SEARCH( - TABLE = graphnode AS src, - COLUMN = embedding, - SIMILAR_TO = qt.qembedding, - METRIC = 'euclidean', - TOP_N = dbo.qt.top_n - ) AS ann; +FROM QueryTable AS qt + CROSS APPLY VECTOR_SEARCH( + TABLE = graphnode AS src, + COLUMN = embedding, + SIMILAR_TO = qt.qembedding, + METRIC = 'euclidean', + TOP_N = dbo.qt.top_n + ) AS ann; \ No newline at end of file diff --git a/Test/SqlDom/Baselines170/WindowClauseQuotedNameTests160.sql b/Test/SqlDom/Baselines170/WindowClauseQuotedNameTests160.sql new file mode 100644 index 00000000..8a5ee8a2 --- /dev/null +++ b/Test/SqlDom/Baselines170/WindowClauseQuotedNameTests160.sql @@ -0,0 +1,46 @@ +CREATE PROCEDURE [dbo].[ExampleProc] +AS +BEGIN + SELECT ROW_NUMBER() OVER [win] AS [RowNum], + SUM([Amount]) OVER [win] AS [RunningTotal] + FROM [dbo].[Transactions] + WINDOW [win] AS (PARTITION BY [AccountID] ORDER BY [TransactionDate]); +END + + +GO +SELECT COUNT(*) OVER [win] +FROM t1 +WINDOW [win] AS (PARTITION BY c1); + + +GO +SELECT LAST_VALUE(c1) IGNORE NULLS OVER [win] +FROM t1 +WINDOW [win] AS (ORDER BY c2); + + +GO +SELECT LAG(c1) OVER [my win] +FROM t1 +WINDOW [my win] AS (ORDER BY c2); + + +GO +SELECT SUM(c1) OVER [select] +FROM t1 +WINDOW [select] AS (PARTITION BY c2); + + +GO +SELECT SUM(c1) OVER "win" +FROM t1 +WINDOW "win" AS (PARTITION BY c2); + + +GO +CREATE VIEW v1 +AS +SELECT AVG(c1) OVER [win] AS a +FROM t1 +WINDOW [win] AS ([base] ORDER BY c2), [base] AS (PARTITION BY c3); diff --git a/Test/SqlDom/Baselines180/AlterDatabaseScopedConfigTxnPriorityTests180.sql b/Test/SqlDom/Baselines180/AlterDatabaseScopedConfigTxnPriorityTests180.sql new file mode 100644 index 00000000..046a0c4f --- /dev/null +++ b/Test/SqlDom/Baselines180/AlterDatabaseScopedConfigTxnPriorityTests180.sql @@ -0,0 +1,13 @@ +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MODE = OFF; + +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MODE = ROLLBACK; + +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MODE = BLOCK; + +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 5000; + +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 0; + +ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET TXN_PRIORITY_MODE = PRIMARY; + +ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 1000; diff --git a/Test/SqlDom/Baselines180/WindowClauseQuotedNameTests160.sql b/Test/SqlDom/Baselines180/WindowClauseQuotedNameTests160.sql new file mode 100644 index 00000000..8a5ee8a2 --- /dev/null +++ b/Test/SqlDom/Baselines180/WindowClauseQuotedNameTests160.sql @@ -0,0 +1,46 @@ +CREATE PROCEDURE [dbo].[ExampleProc] +AS +BEGIN + SELECT ROW_NUMBER() OVER [win] AS [RowNum], + SUM([Amount]) OVER [win] AS [RunningTotal] + FROM [dbo].[Transactions] + WINDOW [win] AS (PARTITION BY [AccountID] ORDER BY [TransactionDate]); +END + + +GO +SELECT COUNT(*) OVER [win] +FROM t1 +WINDOW [win] AS (PARTITION BY c1); + + +GO +SELECT LAST_VALUE(c1) IGNORE NULLS OVER [win] +FROM t1 +WINDOW [win] AS (ORDER BY c2); + + +GO +SELECT LAG(c1) OVER [my win] +FROM t1 +WINDOW [my win] AS (ORDER BY c2); + + +GO +SELECT SUM(c1) OVER [select] +FROM t1 +WINDOW [select] AS (PARTITION BY c2); + + +GO +SELECT SUM(c1) OVER "win" +FROM t1 +WINDOW "win" AS (PARTITION BY c2); + + +GO +CREATE VIEW v1 +AS +SELECT AVG(c1) OVER [win] AS a +FROM t1 +WINDOW [win] AS ([base] ORDER BY c2), [base] AS (PARTITION BY c3); diff --git a/Test/SqlDom/Baselines90/FromClauseTests90.sql b/Test/SqlDom/Baselines90/FromClauseTests90.sql index dc17df21..1a22eecf 100644 --- a/Test/SqlDom/Baselines90/FromClauseTests90.sql +++ b/Test/SqlDom/Baselines90/FromClauseTests90.sql @@ -10,7 +10,8 @@ FROM t1 AS table1 TABLESAMPLE (12 + 3 ROWS); GO SELECT * -FROM master..sysprocesses AS p CROSS APPLY ::fn_get_sql (p.sql_handle); +FROM master..sysprocesses AS p + CROSS APPLY ::fn_get_sql (p.sql_handle); SELECT * FROM ::f1 (a.b * (12 + 20)); @@ -61,7 +62,8 @@ FROM st PIVOT (AVG (.st.StandardCost) FOR st.DaysToManufacture IN ([0], [1])) AS GO SELECT * -FROM t1 PIVOT (dbo.f (c1) FOR [if] IN (a)) AS PTable CROSS JOIN t2 UNPIVOT (c2 FOR T2 IN ([a], b)) AS UPTable; +FROM t1 PIVOT (dbo.f (c1) FOR [if] IN (a)) AS PTable + CROSS JOIN t2 UNPIVOT (c2 FOR T2 IN ([a], b)) AS UPTable; SELECT * FROM t1 @@ -73,7 +75,8 @@ FROM t1 ON t1.c1 = t10.c1 PIVOT (dbo.f (c1) FOR [if] IN (a)) AS PTable; SELECT * -FROM t1 CROSS APPLY t2 UNPIVOT (q FOR n IN (t1.c0, c1)) AS a; +FROM t1 + CROSS APPLY t2 UNPIVOT (q FOR n IN (t1.c0, c1)) AS a; SELECT * FROM (SELECT * diff --git a/Test/SqlDom/BaselinesCommon/FromClauseTests.sql b/Test/SqlDom/BaselinesCommon/FromClauseTests.sql index 907f9d24..f8361572 100644 --- a/Test/SqlDom/BaselinesCommon/FromClauseTests.sql +++ b/Test/SqlDom/BaselinesCommon/FromClauseTests.sql @@ -47,7 +47,8 @@ SELECT c1 FROM t1 WITH (HOLDLOCK, READPAST, INDEX (0)); SELECT * -FROM t1 WITH (NOLOCK) CROSS APPLY dbo.tvf WITH (NOLOCK); +FROM t1 WITH (NOLOCK) + CROSS APPLY dbo.tvf WITH (NOLOCK); SELECT c1 FROM t1 AS table1 WITH (INDEX (0, 1, ind2), HOLDLOCK, NOLOCK, PAGLOCK, READCOMMITTED, READPAST, READUNCOMMITTED, REPEATABLEREAD, ROWLOCK, SERIALIZABLE, TABLOCK, TABLOCKX, UPDLOCK, XLOCK, NOWAIT), t2 WITH (NOWAIT); @@ -68,25 +69,38 @@ FROM @var1, @var2 AS [table 1], @var3 AS table2; GO SELECT * -FROM t1 CROSS JOIN t10; +FROM t1 + CROSS JOIN t10; SELECT * -FROM t1 CROSS JOIN (t10 CROSS JOIN t11); +FROM t1 + CROSS JOIN (t10 + CROSS JOIN t11); SELECT * -FROM (((t1 CROSS JOIN ((t10 CROSS JOIN t11))))); +FROM (((t1 + CROSS JOIN ((t10 + CROSS JOIN t11))))); SELECT * -FROM t1 CROSS APPLY (t10 CROSS APPLY t11); +FROM t1 + CROSS APPLY (t10 + CROSS APPLY t11); SELECT * -FROM (((t1 CROSS APPLY ((t10 CROSS APPLY t11))))); +FROM (((t1 + CROSS APPLY ((t10 + CROSS APPLY t11))))); SELECT * -FROM t1 OUTER APPLY (t10 OUTER APPLY t11); +FROM t1 + OUTER APPLY (t10 + OUTER APPLY t11); SELECT * -FROM (((t1 OUTER APPLY ((t10 OUTER APPLY t11))))); +FROM (((t1 + OUTER APPLY ((t10 + OUTER APPLY t11))))); SELECT * FROM t1 @@ -240,7 +254,8 @@ FROM (SELECT c1 AS a, SELECT * FROM (SELECT * - FROM t1) AS t10(c1, c2) CROSS JOIN t2; + FROM t1) AS t10(c1, c2) + CROSS JOIN t2; SELECT * FROM ((SELECT * @@ -265,13 +280,15 @@ FROM { OJ t1 ON c1 < 10 }; SELECT * -FROM { OJ t1 CROSS JOIN t2 +FROM { OJ t1 + CROSS JOIN t2 INNER JOIN t2 ON c1 < 10 }; SELECT * -FROM { OJ (t1 CROSS JOIN t2) +FROM { OJ (t1 + CROSS JOIN t2) INNER JOIN t2 ON c1 < 10 }; @@ -279,18 +296,22 @@ FROM { OJ (t1 CROSS JOIN t2) SELECT * FROM t1 INNER JOIN - { OJ t1 CROSS JOIN t2 + { OJ t1 + CROSS JOIN t2 INNER JOIN t2 ON c1 < 10 } - ON c1 < 10 CROSS JOIN t3; + ON c1 < 10 + CROSS JOIN t3; SELECT jc.[JobCandidateID] -FROM [HumanResources].[JobCandidate] AS jc CROSS APPLY jc.[Resume].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; +FROM [HumanResources].[JobCandidate] AS jc + CROSS APPLY jc.[Resume].nodes(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume"; /Resume/Employment') AS Employment(ref); SELECT ecp.* -FROM sys.dm_exec_cached_plans AS ecp OUTER APPLY sys.dm_exec_plan_attributes(ecp.plan_handle) AS epa; +FROM sys.dm_exec_cached_plans AS ecp + OUTER APPLY sys.dm_exec_plan_attributes(ecp.plan_handle) AS epa; SELECT au_id FROM [dbo].[Authors] AS auth WITH (NOLOCK) @@ -303,7 +324,8 @@ SELECT * FROM t AS s WITH (NOLOCK); SELECT * -FROM t1 WITH (NOLOCK) CROSS APPLY dbo.tvf WITH (NOLOCK); +FROM t1 WITH (NOLOCK) + CROSS APPLY dbo.tvf WITH (NOLOCK); SELECT * FROM t AS s WITH (NOLOCK); @@ -312,5 +334,4 @@ SELECT * FROM t WITH (NOLOCK); SELECT * -FROM t AS s WITH (NOLOCK); - +FROM t AS s WITH (NOLOCK); \ No newline at end of file diff --git a/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql b/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql index ee84ff09..ee133580 100644 --- a/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql +++ b/Test/SqlDom/BaselinesCommon/SelectStatementTests.sql @@ -133,7 +133,8 @@ ORDER BY c1, c2 ASC, c3 DESC; SELECT c1, c2 -FROM t1 CROSS JOIN t2 +FROM t1 + CROSS JOIN t2 UNION SELECT * FROM t2 diff --git a/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql index 7c2656f9..2b577a6f 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiAnalyzeSentimentTestsFabricDW.sql @@ -12,6 +12,12 @@ SELECT AI_ANALYZE_SENTIMENT(@s0 + 'a'); SELECT AI_ANALYZE_SENTIMENT('b' + 'a'); +SELECT AI_ANALYZE_SENTIMENT('text' ERROR ON ERROR); + +SELECT AI_ANALYZE_SENTIMENT('text' NULL ON ERROR); + +SELECT AI_ANALYZE_SENTIMENT('text' DEFAULT 'Sentiment unavailable' ON ERROR); + SELECT * FROM AI_ANALYZE_SENTIMENT((SELECT t.text_col FROM dbo.Texts AS t)); @@ -23,5 +29,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_ANALYZE_SENTIMENT(@s)); + RETURN (AI_ANALYZE_SENTIMENT(@s DEFAULT N'Sentiment unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql index 4703721d..97282021 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiClassifyTestsFabricDW.sql @@ -15,6 +15,12 @@ SELECT * FROM AI_CLASSIFY((SELECT t.text_col FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); +SELECT AI_CLASSIFY('text', 'spam' ERROR ON ERROR); + +SELECT AI_CLASSIFY('text', 'spam', 'ham' NULL ON ERROR); + +SELECT AI_CLASSIFY(@s, 'topic', 'sentiment', 'intent' DEFAULT 'Classification unavailable' ON ERROR); + GO CREATE OR ALTER FUNCTION dbo.fx @@ -22,5 +28,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_CLASSIFY(@s, 'labelA', 'labelB')); + RETURN (AI_CLASSIFY(@s, 'labelA', 'labelB' DEFAULT N'Classification unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql index 4af178b7..ce3b3ab2 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiExtractTestsFabricDW.sql @@ -15,6 +15,12 @@ SELECT * FROM AI_EXTRACT((SELECT t.text_col FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); +SELECT AI_EXTRACT('text', 'spam' ERROR ON ERROR); + +SELECT AI_EXTRACT('text', 'spam', 'ham' NULL ON ERROR); + +SELECT AI_EXTRACT(@s, 'topic', 'sentiment', 'intent' DEFAULT 'Extraction unavailable' ON ERROR); + GO CREATE OR ALTER FUNCTION dbo.fx @@ -22,5 +28,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_EXTRACT(@s, 'labelA', 'labelB')); + RETURN (AI_EXTRACT(@s, 'labelA', 'labelB' DEFAULT N'Extraction unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql index 7e6225a6..8bfef169 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiFixGrammarTestsFabricDW.sql @@ -12,6 +12,12 @@ SELECT AI_FIX_GRAMMAR(@s0 + 'a'); SELECT AI_FIX_GRAMMAR('b' + 'a'); +SELECT AI_FIX_GRAMMAR('text' ERROR ON ERROR); + +SELECT AI_FIX_GRAMMAR('text' NULL ON ERROR); + +SELECT AI_FIX_GRAMMAR('text' DEFAULT 'Correction unavailable' ON ERROR); + SELECT * FROM AI_FIX_GRAMMAR((SELECT t.text_col FROM dbo.Texts AS t)); @@ -23,5 +29,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_FIX_GRAMMAR(@s)); + RETURN (AI_FIX_GRAMMAR(@s DEFAULT N'Correction unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql index 5a0a6b55..34b13559 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiGenerateResponseTestsFabricDW.sql @@ -10,6 +10,12 @@ SELECT AI_GENERATE_RESPONSE(@p1 + 'part1', @p2); SELECT AI_GENERATE_RESPONSE('b' + 'a'); +SELECT AI_GENERATE_RESPONSE('Hello' ERROR ON ERROR); + +SELECT AI_GENERATE_RESPONSE('Question:', ' What is the time?' NULL ON ERROR); + +SELECT AI_GENERATE_RESPONSE(@p1, @p2 DEFAULT 'Response unavailable' ON ERROR); + SELECT * FROM AI_GENERATE_RESPONSE((SELECT t.text_col FROM dbo.Texts AS t)); @@ -21,5 +27,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_GENERATE_RESPONSE(@p)); + RETURN (AI_GENERATE_RESPONSE(@p DEFAULT N'Response unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql index fbb972d0..89911348 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiSummarizeTestsFabricDW.sql @@ -12,6 +12,12 @@ SELECT AI_SUMMARIZE(@s0 + 'a'); SELECT AI_SUMMARIZE('b' + 'a'); +SELECT AI_SUMMARIZE('text' ERROR ON ERROR); + +SELECT AI_SUMMARIZE('text' NULL ON ERROR); + +SELECT AI_SUMMARIZE('text' DEFAULT 'Summary unavailable' ON ERROR); + SELECT * FROM AI_SUMMARIZE((SELECT t.text_col FROM dbo.Texts AS t)); @@ -23,5 +29,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_SUMMARIZE(@s)); + RETURN (AI_SUMMARIZE(@s DEFAULT N'Summary unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql index 10b497d3..e8c16a4d 100644 --- a/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/AiTranslateTestsFabricDW.sql @@ -13,6 +13,14 @@ SELECT AI_TRANSLATE(@s, @lang); SELECT AI_TRANSLATE(@s + 'a', @lang + 'a'); +SELECT AI_TRANSLATE('Hello world', 'es' ERROR ON ERROR); + +SELECT AI_TRANSLATE('Hello world', 'es' NULL ON ERROR); + +SELECT AI_TRANSLATE('Hello world', 'es' DEFAULT 'Translation unavailable' ON ERROR); + +SELECT AI_TRANSLATE(@s, @lang DEFAULT N'Translation unavailable' ON ERROR); + SELECT * FROM AI_TRANSLATE((SELECT t.text_col FROM dbo.Texts AS t), 'e' + 's'); @@ -24,7 +32,7 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_TRANSLATE(@s, 'fr')); + RETURN (AI_TRANSLATE(@s, 'fr' DEFAULT N'Translation unavailable' ON ERROR)); END diff --git a/Test/SqlDom/BaselinesFabricDW/CreateAlterTableClusterByTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/CreateAlterTableClusterByTestsFabricDW.sql index 05f8e022..b2102240 100644 --- a/Test/SqlDom/BaselinesFabricDW/CreateAlterTableClusterByTestsFabricDW.sql +++ b/Test/SqlDom/BaselinesFabricDW/CreateAlterTableClusterByTestsFabricDW.sql @@ -25,14 +25,21 @@ WITH (CLUSTER BY (ProductID)); GO ALTER TABLE Customers - ADD (CLUSTER BY (CustomerID)); + WITH (CLUSTER BY (CustomerID)); GO ALTER TABLE sales.Orders - ADD (CLUSTER BY (CustomerID, OrderDate)); + WITH (CLUSTER BY (CustomerID, OrderDate)); GO ALTER TABLE Inventory - ADD (CLUSTER BY (ProductID)); \ No newline at end of file + WITH (CLUSTER BY (ProductID)); + + +GO +CREATE TABLE CustomersClustered +WITH (CLUSTER BY (CustomerID)) AS +SELECT * +FROM Customers; \ No newline at end of file diff --git a/Test/SqlDom/BaselinesFabricDW/QueryHintsTestsFabricDW.sql b/Test/SqlDom/BaselinesFabricDW/QueryHintsTestsFabricDW.sql new file mode 100644 index 00000000..4b2e7d80 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/QueryHintsTestsFabricDW.sql @@ -0,0 +1,41 @@ +SELECT * +FROM t1 + INNER HASH JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT * +FROM t1 + INNER REPLICATE JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT * +FROM t1 + INNER REDISTRIBUTE JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT * +FROM t1 + INNER REDISTRIBUTE(2) JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT c1 +FROM t1 +OPTION (FORCE SINGLE NODE PLAN); +GO + +SELECT c1 +FROM t1 +OPTION (FORCE DISTRIBUTED PLAN); +GO + +SELECT c1 +FROM t1 +OPTION (FOR TIMESTAMP AS OF '2024-05-01T10:00:00'); \ No newline at end of file diff --git a/Test/SqlDom/BaselinesFabricDW/WindowClauseQuotedNameTests160.sql b/Test/SqlDom/BaselinesFabricDW/WindowClauseQuotedNameTests160.sql new file mode 100644 index 00000000..8a5ee8a2 --- /dev/null +++ b/Test/SqlDom/BaselinesFabricDW/WindowClauseQuotedNameTests160.sql @@ -0,0 +1,46 @@ +CREATE PROCEDURE [dbo].[ExampleProc] +AS +BEGIN + SELECT ROW_NUMBER() OVER [win] AS [RowNum], + SUM([Amount]) OVER [win] AS [RunningTotal] + FROM [dbo].[Transactions] + WINDOW [win] AS (PARTITION BY [AccountID] ORDER BY [TransactionDate]); +END + + +GO +SELECT COUNT(*) OVER [win] +FROM t1 +WINDOW [win] AS (PARTITION BY c1); + + +GO +SELECT LAST_VALUE(c1) IGNORE NULLS OVER [win] +FROM t1 +WINDOW [win] AS (ORDER BY c2); + + +GO +SELECT LAG(c1) OVER [my win] +FROM t1 +WINDOW [my win] AS (ORDER BY c2); + + +GO +SELECT SUM(c1) OVER [select] +FROM t1 +WINDOW [select] AS (PARTITION BY c2); + + +GO +SELECT SUM(c1) OVER "win" +FROM t1 +WINDOW "win" AS (PARTITION BY c2); + + +GO +CREATE VIEW v1 +AS +SELECT AVG(c1) OVER [win] AS a +FROM t1 +WINDOW [win] AS ([base] ORDER BY c2), [base] AS (PARTITION BY c3); diff --git a/Test/SqlDom/CommonSyntaxTests.cs b/Test/SqlDom/CommonSyntaxTests.cs index 8b280db9..b00a0054 100644 --- a/Test/SqlDom/CommonSyntaxTests.cs +++ b/Test/SqlDom/CommonSyntaxTests.cs @@ -247,7 +247,8 @@ public void CommonSyntaxInFabricDWParserTest() "IntegerTests.sql", "TSqlParserTestScript1.sql", "TSqlParserTestScript2.sql", - "ExpressionTests.sql" + "ExpressionTests.sql", + "FromClauseTests.sql" }; foreach (ParserTest ti in CommonTestInfos) diff --git a/Test/SqlDom/Only160SyntaxTests.cs b/Test/SqlDom/Only160SyntaxTests.cs index 9feb8687..2fa962d3 100644 --- a/Test/SqlDom/Only160SyntaxTests.cs +++ b/Test/SqlDom/Only160SyntaxTests.cs @@ -21,6 +21,7 @@ public partial class SqlDomTests new ParserTest160("CreateUserFromExternalProvider160.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 1, nErrors140: 1, nErrors150: 1), new ParserTest160("CreateExternalTableStatementTests160.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2), new ParserTest160("WindowClauseTests160.sql", nErrors80: 16, nErrors90: 15, nErrors100: 15, nErrors110: 15, nErrors120: 15, nErrors130: 15, nErrors140: 15, nErrors150: 15), + new ParserTest160("WindowClauseQuotedNameTests160.sql", nErrors80: 7, nErrors90: 7, nErrors100: 7, nErrors110: 7, nErrors120: 7, nErrors130: 7, nErrors140: 7, nErrors150: 7), new ParserTest160("CreateExternalDataSourceStatementTests160.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0), new ParserTest160("CreateDatabaseTests160.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4), new ParserTest160("CreateLedgerTableTests160.sql", nErrors80: 14, nErrors90: 14, nErrors100: 14, nErrors110: 14, nErrors120: 14, nErrors130: 14, nErrors140: 14, nErrors150: 14), diff --git a/Test/SqlDom/Only170SyntaxTests.cs b/Test/SqlDom/Only170SyntaxTests.cs index 6c6aa482..147d80fe 100644 --- a/Test/SqlDom/Only170SyntaxTests.cs +++ b/Test/SqlDom/Only170SyntaxTests.cs @@ -25,6 +25,7 @@ public partial class SqlDomTests new ParserTest170("JsonObjectAggOverClause170.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("ComplexJsonObjectFunctionTests170.sql"), new ParserTest170("TrimFromReturnTests160.sql"), + new ParserTest170("WindowClauseQuotedNameTests160.sql"), new ParserTest170("AiGenerateEmbeddingsTests170.sql", nErrors80: 14, nErrors90: 11, nErrors100: 11, nErrors110: 11, nErrors120: 11, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11), new ParserTest170("CreateExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4), new ParserTest170("AlterExternalModelStatementTests170.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5), diff --git a/Test/SqlDom/Only180SyntaxTests.cs b/Test/SqlDom/Only180SyntaxTests.cs index e26be85e..d8a26449 100644 --- a/Test/SqlDom/Only180SyntaxTests.cs +++ b/Test/SqlDom/Only180SyntaxTests.cs @@ -14,8 +14,10 @@ public partial class SqlDomTests { new ParserTest180("AutomaticIndexCompactionTests180.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2), new ParserTest180("TrimFromReturnTests160.sql"), - new ParserTest180("PersistSamplePercentStatisticsTests130.sql"), + new ParserTest180("WindowClauseQuotedNameTests160.sql"), new ParserTest180("CreateSemanticIndexTests180.sql"), + new ParserTest180("AlterDatabaseScopedConfigTxnPriorityTests180.sql", nErrors80: 7, nErrors90: 7, nErrors100: 7, nErrors110: 7, nErrors120: 7, nErrors130: 1, nErrors140: 1, nErrors150: 1, nErrors160: 1, nErrors170: 1), + new ParserTest180("PersistSamplePercentStatisticsTests130.sql"), new ParserTest180("CreateDatabaseCollateBeforeEditionTests120.sql", nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0) }; diff --git a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs index e3a53fef..84a94eae 100644 --- a/Test/SqlDom/OnlyFabricDWSyntaxTests.cs +++ b/Test/SqlDom/OnlyFabricDWSyntaxTests.cs @@ -1,4 +1,6 @@ -using Microsoft.SqlServer.TransactSql.ScriptDom; +using System; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.VisualStudio.TestTools.UnitTesting; using SqlStudio.Tests.AssemblyTools.TestCategory; @@ -11,28 +13,136 @@ public partial class SqlDomTests { new ParserTestFabricDW("CloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4, nErrors180: 4), new ParserTestFabricDW("CreateAlterExternalDataSourceTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("CreateAlterTableClusterByTestsFabricDW.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 6, nErrors180: 6), + new ParserTestFabricDW("CreateAlterTableClusterByTestsFabricDW.sql", nErrors80: 7, nErrors90: 7, nErrors100: 7, nErrors110: 7, nErrors120: 7, nErrors130: 7, nErrors140: 7, nErrors150: 7, nErrors160: 7, nErrors170: 7, nErrors180: 7), new ParserTestFabricDW("CreateExternalTableStatementTestsFabricDW.sql", nErrors80: 2, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("CreateProcedureCloneTableTestsFabricDW.sql", nErrors80: 4, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 4, nErrors140: 4, nErrors150: 4, nErrors160: 4, nErrors170: 4, nErrors180: 4), new ParserTestFabricDW("IdentityColumnTestsFabricDW.sql", nErrors80: 0, nErrors90: 0, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("NestedCTETestsFabricDW.sql", nErrors80: 1, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 2, nErrors140: 2, nErrors150: 2, nErrors160: 2, nErrors170: 2, nErrors180: 2), new ParserTestFabricDW("ScalarFunctionTestsFabricDW.sql", nErrors80: 3, nErrors90: 2, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("CreateEventSessionNotLikePredicate.sql", nErrors80: 2, nErrors90: 1, nErrors100: 1, nErrors110: 1, nErrors120: 1, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiAnalyzeSentimentTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiClassifyTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiExtractTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiFixGrammarTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), - new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 2, nErrors110: 2, nErrors120: 2, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), + new ParserTestFabricDW("AiAnalyzeSentimentTestsFabricDW.sql", nErrors80: 5, nErrors90: 1, nErrors100: 5, nErrors110: 5, nErrors120: 5, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5, nErrors170: 5, nErrors180: 5), + new ParserTestFabricDW("AiClassifyTestsFabricDW.sql", nErrors80: 5, nErrors90: 1, nErrors100: 5, nErrors110: 5, nErrors120: 5, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5, nErrors170: 5, nErrors180: 5), + new ParserTestFabricDW("AiExtractTestsFabricDW.sql", nErrors80: 5, nErrors90: 1, nErrors100: 5, nErrors110: 5, nErrors120: 5, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5, nErrors170: 5, nErrors180: 5), + new ParserTestFabricDW("AiFixGrammarTestsFabricDW.sql", nErrors80: 5, nErrors90: 1, nErrors100: 5, nErrors110: 5, nErrors120: 5, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5, nErrors170: 5, nErrors180: 5), + new ParserTestFabricDW("AiGenerateResponseTestsFabricDW.sql", nErrors80: 6, nErrors90: 1, nErrors100: 5, nErrors110: 5, nErrors120: 5, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5, nErrors170: 5, nErrors180: 5), + new ParserTestFabricDW("AiSummarizeTestsFabricDW.sql", nErrors80: 5, nErrors90: 1, nErrors100: 5, nErrors110: 5, nErrors120: 5, nErrors130: 5, nErrors140: 5, nErrors150: 5, nErrors160: 5, nErrors170: 5, nErrors180: 5), + new ParserTestFabricDW("AiTranslateTestsFabricDW.sql", nErrors80: 3, nErrors90: 1, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 6, nErrors180: 6), new ParserTestFabricDW("InvokeExternalApiTestsFabricDW.sql", nErrors80: 2, nErrors90: 1, nErrors100: 0, nErrors110: 0, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("ExternalFunctionTestsFabricDW.sql", nErrors80: 12, nErrors90: 4, nErrors100: 4, nErrors110: 4, nErrors120: 4, nErrors130: 11, nErrors140: 11, nErrors150: 11, nErrors160: 11, nErrors170: 11, nErrors180: 0), new ParserTestFabricDW("CreateDatabaseCollateBeforeEditionTestsFabricDW.sql", nErrors80: 3, nErrors90: 3, nErrors100: 3, nErrors110: 3, nErrors120: 0, nErrors130: 0, nErrors140: 0, nErrors150: 0, nErrors160: 0, nErrors170: 0, nErrors180: 0), new ParserTestFabricDW("ModernGroupByAllTestsFabricDW.sql", nErrors80: 9, nErrors90: 9, nErrors100: 9, nErrors110: 9, nErrors120: 9, nErrors130: 9, nErrors140: 9, nErrors150: 9, nErrors160: 9, nErrors170: 9, nErrors180: 9), new ParserTestFabricDW("OrderByAllTestsFabricDW.sql", nErrors80: 13, nErrors90: 13, nErrors100: 13, nErrors110: 13, nErrors120: 13, nErrors130: 13, nErrors140: 13, nErrors150: 13, nErrors160: 13, nErrors170: 13, nErrors180: 13), + new ParserTestFabricDW("QueryHintsTestsFabricDW.sql", nErrors80: 6, nErrors90: 6, nErrors100: 6, nErrors110: 6, nErrors120: 6, nErrors130: 6, nErrors140: 6, nErrors150: 6, nErrors160: 6, nErrors170: 3, nErrors180: 3), + new ParserTestFabricDW("WindowClauseQuotedNameTests160.sql", nErrors80: 7, nErrors90: 7, nErrors100: 7, nErrors110: 7, nErrors120: 7, nErrors130: 7, nErrors140: 7, nErrors150: 7, nErrors160: 0, nErrors170: 0, nErrors180: 0), }; + [DataTestMethod] + [DataRow("GROUP BY ALL")] + [DataRow("GROUP BY ALL City")] + [DataRow("GROUP BY City")] + [DataRow("ORDER BY ALL")] + [DataRow("ORDER BY ALL ASC")] + [DataRow("ORDER BY ALL DESC")] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void FabricDWGroupingAndOrderingTokenRanges(string clauseText) + { + string selectText = "SELECT TOP 100 City, COUNT(*) AS Cnt FROM dbo.Employees " + clauseText; + string sql = "CREATE VIEW dbo.TestView AS " + selectText + ";"; + var parser = new TSqlFabricDWParser(true); + using (var reader = new StringReader(sql)) + { + var script = (TSqlScript)parser.Parse(reader, out var errors); + Assert.AreEqual(0, errors.Count); + var view = (CreateViewStatement)script.Batches[0].Statements[0]; + var query = (QuerySpecification)view.SelectStatement.QueryExpression; + TSqlFragment clause = query.GroupByClause != null + ? (TSqlFragment)query.GroupByClause + : query.OrderByClause; + + Assert.AreEqual(clauseText, sql.Substring(clause.StartOffset, clause.FragmentLength)); + Assert.AreEqual(selectText, sql.Substring(query.StartOffset, query.FragmentLength)); + Assert.AreEqual(selectText, sql.Substring(view.SelectStatement.StartOffset, view.SelectStatement.FragmentLength)); + Assert.AreEqual(clause.LastTokenIndex, query.LastTokenIndex); + Assert.AreEqual(clause.LastTokenIndex, view.SelectStatement.LastTokenIndex); + } + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiTranslateOnErrorClauseAstShape() + { + const string sql = + "SELECT AI_TRANSLATE('text', 'es' ERROR ON ERROR);" + + "SELECT AI_TRANSLATE('text', 'es' NULL ON ERROR);" + + "SELECT AI_TRANSLATE('text', 'es' DEFAULT 'fallback' ON ERROR);"; + + var parser = new TSqlFabricDWParser(true); + var script = (TSqlScript)parser.Parse(new StringReader(sql), out var errors); + + Assert.AreEqual(0, errors.Count); + + var errorFunction = GetAiTranslateFunction(script, 0); + Assert.IsInstanceOfType(errorFunction.OnErrorClause, typeof(AIErrorOnErrorClause)); + + var nullFunction = GetAiTranslateFunction(script, 1); + Assert.IsInstanceOfType(nullFunction.OnErrorClause, typeof(AINullOnErrorClause)); + + var defaultFunction = GetAiTranslateFunction(script, 2); + Assert.IsInstanceOfType(defaultFunction.OnErrorClause, typeof(AIDefaultOnErrorClause)); + Assert.AreEqual( + "fallback", + ((AIDefaultOnErrorClause)defaultFunction.OnErrorClause).Value.Value); + } + + private static AITranslateFunctionCall GetAiTranslateFunction(TSqlScript script, int statementIndex) + { + var selectStatement = (SelectStatement)script.Batches[0].Statements[statementIndex]; + var query = (QuerySpecification)selectStatement.QueryExpression; + return (AITranslateFunctionCall)((SelectScalarExpression)query.SelectElements[0]).Expression; + } + + [DataTestMethod] + [DataRow("AI_ANALYZE_SENTIMENT('text')")] + [DataRow("AI_FIX_GRAMMAR('text' ERROR ON ERROR)")] + [DataRow("AI_GENERATE_RESPONSE('prompt', 'data' NULL ON ERROR)")] + [DataRow("AI_SUMMARIZE('text' DEFAULT 'fallback' ON ERROR)")] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void FabricDWAiFunctionTokenRanges(string functionText) + { + string sql = "SELECT " + functionText; + var parser = new TSqlFabricDWParser(true); + using (var reader = new StringReader(sql)) + { + var script = (TSqlScript)parser.Parse(reader, out var errors); + Assert.AreEqual(0, errors.Count); + var select = (SelectStatement)script.Batches[0].Statements[0]; + var function = ((SelectScalarExpression)((QuerySpecification)select.QueryExpression).SelectElements[0]).Expression; + + Assert.AreEqual(functionText, sql.Substring(function.StartOffset, function.FragmentLength)); + Assert.AreEqual(sql, sql.Substring(select.StartOffset, select.FragmentLength)); + Assert.AreEqual(function.LastTokenIndex, select.LastTokenIndex); + } + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void AiDefaultOnErrorClauseRequiresValue() + { + var function = new AISummarizeFunctionCall + { + Input = new StringLiteral { Value = "text" }, + OnErrorClause = new AIDefaultOnErrorClause(), + }; + + SqlScriptGenerator scriptGen = ParserTestUtils.CreateScriptGen(SqlVersion.SqlFabricDW); + Assert.ThrowsException(() => scriptGen.GenerateScript(function, out string _)); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] diff --git a/Test/SqlDom/ParserErrorsTests.cs b/Test/SqlDom/ParserErrorsTests.cs index 00db16fb..17988e56 100644 --- a/Test/SqlDom/ParserErrorsTests.cs +++ b/Test/SqlDom/ParserErrorsTests.cs @@ -7258,6 +7258,56 @@ FROM @SalesData ParserTestUtils.ErrorTestFabricDW(scalarFunctionSyntax4, new ParserErrorInfo(scalarFunctionSyntax4.IndexOf("NULL"), "SQL46010", "NULL")); } + /// + /// Negative tests for join hints and query hints in Fabric DW. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void QueryHintsNegativeTestsFabricDW() + { + // REMOTE join hint is not supported in Fabric DW + // + string remoteJoinHint = "SELECT * FROM t1 INNER REMOTE JOIN t2 ON t1.c1 = t2.c1"; + ParserTestUtils.ErrorTestFabricDW(remoteJoinHint, new ParserErrorInfo(remoteJoinHint.IndexOf("REMOTE"), "SQL46010", "REMOTE")); + + // LOCAL-prefixed join hints are not supported in Fabric DW + // + string localHashJoinHint = "SELECT * FROM t1 INNER LOCAL HASH JOIN t2 ON t1.c1 = t2.c1"; + ParserTestUtils.ErrorTestFabricDW(localHashJoinHint, new ParserErrorInfo(localHashJoinHint.IndexOf("HASH"), "SQL46010", "HASH")); + + string localMergeJoinHint = "SELECT * FROM t1 INNER LOCAL MERGE JOIN t2 ON t1.c1 = t2.c1"; + ParserTestUtils.ErrorTestFabricDW(localMergeJoinHint, new ParserErrorInfo(localMergeJoinHint.IndexOf("MERGE"), "SQL46010", "MERGE")); + + // Only REDISTRIBUTE accepts a (columns_count) argument + // + string replicateWithCount = "SELECT * FROM t1 INNER REPLICATE (2) JOIN t2 ON t1.c1 = t2.c1"; + ParserTestUtils.ErrorTestFabricDW(replicateWithCount, new ParserErrorInfo(replicateWithCount.IndexOf("REPLICATE"), "SQL46005", "REDISTRIBUTE", "REPLICATE")); + + // REDISTRIBUTE columns count must be an integer literal + // + string redistributeNonInteger = "SELECT * FROM t1 INNER REDISTRIBUTE ('a') JOIN t2 ON t1.c1 = t2.c1"; + ParserTestUtils.ErrorTestFabricDW(redistributeNonInteger, new ParserErrorInfo(redistributeNonInteger.IndexOf("'a'"), "SQL46010", "'a'")); + + // FORCE DISTRIBUTED PLAN must start with FORCE + // + string keepDistributedPlan = "SELECT c1 FROM t1 OPTION (KEEP DISTRIBUTED PLAN)"; + ParserTestUtils.ErrorTestFabricDW(keepDistributedPlan, new ParserErrorInfo(keepDistributedPlan.IndexOf("KEEP"), "SQL46010", "KEEP")); + + // FORCE SINGLE NODE PLAN requires the NODE keyword + // + string forceSingleNodesPlan = "SELECT c1 FROM t1 OPTION (FORCE SINGLE NODES PLAN)"; + ParserTestUtils.ErrorTestFabricDW(forceSingleNodesPlan, new ParserErrorInfo(forceSingleNodesPlan.IndexOf("NODES"), "SQL46005", "NODE", "NODES")); + + // FOR TIMESTAMP AS OF requires the TIMESTAMP keyword and a string literal + // + string forTimestamps = "SELECT c1 FROM t1 OPTION (FOR TIMESTAMPS AS OF '2024-05-01T10:00:00')"; + ParserTestUtils.ErrorTestFabricDW(forTimestamps, new ParserErrorInfo(forTimestamps.IndexOf("TIMESTAMPS"), "SQL46005", "TIMESTAMP", "TIMESTAMPS")); + + string forTimestampNonString = "SELECT c1 FROM t1 OPTION (FOR TIMESTAMP AS OF 123)"; + ParserTestUtils.ErrorTestFabricDW(forTimestampNonString, new ParserErrorInfo(forTimestampNonString.IndexOf("123"), "SQL46010", "123")); + } + /// /// Negative tests for Scalar Functions in Fabric DW. /// @@ -7902,6 +7952,11 @@ public void AiAnalyzeSentimentNegativeTestsFabricDw() ParserTestUtils.ErrorTestFabricDW( "SELECT AI_ANALYZE_SENTIMENT('1', '2')", new ParserErrorInfo(31, "SQL46010", ",")); + + // ON ERROR clause must follow the last argument + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_ANALYZE_SENTIMENT('1' NULL ON ERROR, '2')", + new ParserErrorInfo(45, "SQL46010", ",")); } /// @@ -7922,10 +7977,19 @@ public void AiClassifyNegativeTestsFabricDw() "SELECT AI_CLASSIFY('1')", new ParserErrorInfo(22, "SQL46010", ")")); + // Up to 20 labels are allowed + ParserTestUtils.ErrorTestFabricDW( + $"SELECT AI_CLASSIFY({string.Join(", ", Enumerable.Repeat("'1'", 21))} NULL ON ERROR)"); + // Too many arguments ParserTestUtils.ErrorTestFabricDW( - $"SELECT AI_CLASSIFY({string.Join(", ", Enumerable.Repeat("'1'", 23))})", - new ParserErrorInfo(129, "SQL46010", "AI_CLASSIFY")); + $"SELECT AI_CLASSIFY({string.Join(", ", Enumerable.Repeat("'1'", 22))})", + new ParserErrorInfo(124, "SQL46010", "AI_CLASSIFY")); + + // ON ERROR clause must follow the last argument + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_CLASSIFY('1', '2', '3' NULL ON ERROR, '4')", + new ParserErrorInfo(46, "SQL46010", ",")); } /// @@ -7946,10 +8010,19 @@ public void AiExtractNegativeTestsFabricDw() "SELECT AI_EXTRACT('1')", new ParserErrorInfo(21, "SQL46010", ")")); + // Up to 20 labels are allowed + ParserTestUtils.ErrorTestFabricDW( + $"SELECT AI_EXTRACT({string.Join(", ", Enumerable.Repeat("'1'", 21))} NULL ON ERROR)"); + // Too many arguments ParserTestUtils.ErrorTestFabricDW( - $"SELECT AI_EXTRACT({string.Join(", ", Enumerable.Repeat("'1'", 23))})", - new ParserErrorInfo(128, "SQL46010", "AI_EXTRACT")); + $"SELECT AI_EXTRACT({string.Join(", ", Enumerable.Repeat("'1'", 22))})", + new ParserErrorInfo(123, "SQL46010", "AI_EXTRACT")); + + // ON ERROR clause must follow the last argument + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_EXTRACT('1', '2', '3' NULL ON ERROR, '4')", + new ParserErrorInfo(45, "SQL46010", ",")); } /// @@ -7969,6 +8042,11 @@ public void AiFixGrammarNegativeTestsFabricDw() ParserTestUtils.ErrorTestFabricDW( "SELECT AI_FIX_GRAMMAR('1', '2')", new ParserErrorInfo(25, "SQL46010", ",")); + + // ON ERROR clause must follow the last argument + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_FIX_GRAMMAR('1' NULL ON ERROR, '2')", + new ParserErrorInfo(39, "SQL46010", ",")); } /// @@ -7988,6 +8066,11 @@ public void AiGenerateResponseNegativeTestsFabricDw() ParserTestUtils.ErrorTestFabricDW( "SELECT AI_GENERATE_RESPONSE('1', '2', '3')", new ParserErrorInfo(36, "SQL46010", ",")); + + // ON ERROR clause must follow the last argument + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_GENERATE_RESPONSE('1' NULL ON ERROR, '2')", + new ParserErrorInfo(45, "SQL46010", ",")); } /// @@ -8007,6 +8090,11 @@ public void AiSummarizeNegativeTestsFabricDw() ParserTestUtils.ErrorTestFabricDW( "SELECT AI_SUMMARIZE('1', '2')", new ParserErrorInfo(23, "SQL46010", ",")); + + // ON ERROR clause must follow the last argument + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_SUMMARIZE('1' NULL ON ERROR, '2')", + new ParserErrorInfo(37, "SQL46010", ",")); } /// @@ -8031,6 +8119,34 @@ public void AiTranslateNegativeTestsFabricDw() ParserTestUtils.ErrorTestFabricDW( "SELECT AI_TRANSLATE('1', '2', '3')", new ParserErrorInfo(28, "SQL46010", ",")); + + // DEFAULT requires a string literal + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('hello', 'es' DEFAULT ON ERROR)", + new ParserErrorInfo(42, "SQL46010", "ON")); + + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('hello', 'es' DEFAULT @fallback ON ERROR)", + new ParserErrorInfo(42, "SQL46010", "@fallback")); + + // The behavior must be followed by ON ERROR + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('hello', 'es' NULL)", + new ParserErrorInfo(38, "SQL46010", ")")); + + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('hello', 'es' NULL ON NULL)", + new ParserErrorInfo(42, "SQL46010", "NULL")); + + // Only ERROR, NULL, or DEFAULT are valid behaviors + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('hello', 'es' IGNORE ON ERROR)", + new ParserErrorInfo(34, "SQL46005", "ERROR", "IGNORE")); + + // Only one ON ERROR clause is allowed + ParserTestUtils.ErrorTestFabricDW( + "SELECT AI_TRANSLATE('hello', 'es' NULL ON ERROR NULL ON ERROR)", + new ParserErrorInfo(48, "SQL46010", "NULL")); } /// diff --git a/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs b/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs index 158ca0af..67b54481 100644 --- a/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs +++ b/Test/SqlDom/ScriptGenerator/ColumnAliasStyleTests.cs @@ -314,6 +314,25 @@ public void TestColumnAliasStylePreserveMixedForms() Assert.AreEqual(expected, generated); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveKeepsAliasesWithoutAsKeyword() + { + string generated = Generate( + "SELECT col1 = a, bb AS c, d col3, ee [col 4] FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + + string expected = + "SELECT col1 = a," + Environment.NewLine + + " bb AS c," + Environment.NewLine + + " d col3," + Environment.NewLine + + " ee [col 4]" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] @@ -406,6 +425,43 @@ public void TestColumnAliasStylePreserveOnProgrammaticallyBuiltFragmentRendersAs Assert.AreEqual(expected, generated); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveWithAliasIndexOutsideTokenStreamRendersAsKeyword() + { + var tokenStream = new List + { + new TSqlParserToken(TSqlTokenType.Identifier, "a") + }; + var expression = new ColumnReferenceExpression + { + FirstTokenIndex = 0, + LastTokenIndex = 0, + MultiPartIdentifier = new MultiPartIdentifier { Identifiers = { new Identifier { Value = "a" } } } + }; + var columnName = new IdentifierOrValueExpression + { + FirstTokenIndex = tokenStream.Count, + Identifier = new Identifier { Value = "x" } + }; + var scalar = new SelectScalarExpression + { + ScriptTokenStream = tokenStream, + Expression = expression, + ColumnName = columnName + }; + var query = new QuerySpecification(); + query.SelectElements.Add(scalar); + var select = new SelectStatement { QueryExpression = query }; + + var generator = new Sql170ScriptGenerator( + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve }); + generator.GenerateScript(select, out string generated); + + Assert.AreEqual("SELECT a AS x", generated); + } + // --------------------------------------------------------------------------------------- // Context-scoping tests: the "alias = expression" form is valid ONLY in a SELECT // projection list. OUTPUT, OUTPUT INTO and RECEIVE reuse SelectScalarExpression but their @@ -573,5 +629,21 @@ public void TestColumnAliasStylePreserveWithCommentsKeepsCommentInPlace() Assert.AreEqual(expected, generated); } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestColumnAliasStylePreserveKeepsCommentBeforeAliasWithoutAsKeyword() + { + string generated = Generate( + "SELECT CAST(a AS int) /* mid */ result FROM t;", + new SqlScriptGeneratorOptions { ColumnAliasStyle = ColumnAliasStyle.Preserve, PreserveComments = true }); + + string expected = + "SELECT CAST (a AS INT) /* mid */ result" + Environment.NewLine + + "FROM t;" + Environment.NewLine + Environment.NewLine; + + Assert.AreEqual(expected, generated); + } } } diff --git a/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs b/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs index c48dc771..2e247691 100644 --- a/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs +++ b/Test/SqlDom/ScriptGenerator/CommaPlacementTests.cs @@ -274,7 +274,8 @@ SELECT a public void TestCommaPlacementLeadingWithPreserveCommentsDoesNotAbsorbComma() { // A line comment after an element must not absorb the following leading comma. - const string input = @"SELECT col1, -- first column + const string input = @" +SELECT col1, -- first column col2, -- second column col3 FROM t;"; @@ -296,7 +297,8 @@ SELECT col1 -- first column [SqlStudioTestCategory(Category.UnitTest)] public void TestCommaPlacementTrailingWithPreserveCommentsKeepsCommentsAfterComma() { - const string input = @"SELECT col1, -- first column + const string input = @" +SELECT col1, -- first column col2, -- second column col3 FROM t;"; @@ -333,6 +335,126 @@ public void TestCommaPlacementTrailingWithCommentBeforeCommaForcesNewLine() AssertGenerated(input, options, expected); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingPreservesCommentBeforeFromClause() + { + const string input = @" +SELECT a +, b +-- comment +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + CommaPlacement = CommaPlacement.Leading, + LeadingCommaSpaceCount = 0, + NewLineBeforeFromClause = false, + PreserveComments = true, + }; + const string expected = @" +SELECT a + ,b +-- comment +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingPreservesCommentBeforeFromClause() + { + const string input = @" +SELECT a, +b +-- comment +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + CommaPlacement = CommaPlacement.Trailing, + NewLineBeforeFromClause = false, + PreserveComments = true, + }; + const string expected = @" +SELECT a, + b +-- comment +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingPreservesCommentsAroundSelectElements() + { + const string input = @" +-- before select +SELECT +-- before first column +a -- after first column +-- between first and second column +,b -- after second column +,c -- after third column +-- before from +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + CommaPlacement = CommaPlacement.Leading, + LeadingCommaSpaceCount = 0, + NewLineBeforeFromClause = true, + PreserveComments = true, + }; + const string expected = @" +-- before select +SELECT -- before first column + a -- after first column + -- between first and second column + ,b -- after second column + ,c -- after third column +-- before from +FROM t;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingPreservesCommentsAroundSelectElements() + { + const string input = @" +-- before select +SELECT +-- before first column +a, -- after first column +-- between first and second column +b, -- after second column +c -- after third column +-- before from +FROM t;"; + var options = new SqlScriptGeneratorOptions + { + AlignClauseBodies = false, + CommaPlacement = CommaPlacement.Trailing, + NewLineBeforeFromClause = true, + PreserveComments = true, + }; + const string expected = @" +-- before select +SELECT -- before first column + a, -- after first column + -- between first and second column + b, -- after second column + c -- after third column +-- before from +FROM t;"; + AssertGenerated(input, options, expected); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] @@ -500,6 +622,111 @@ a INT -- first AssertGenerated(input, options, expected); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingProcedureParametersPreservesCommentBeforeParameter() + { + const string input = @"CREATE PROCEDURE p @a INT, +-- before second parameter +@b INT AS SELECT 1;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineProcedureParametersList = true, + PreserveComments = true, + }; + const string expected = @" +CREATE PROCEDURE p + @a INT + -- before second parameter + , @b INT +AS +SELECT 1;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingProcedureParametersPreservesCommentsAroundParameters() + { + const string input = @"CREATE PROCEDURE p +-- before first parameter +@a INT, -- after first parameter +-- before second parameter +@b INT -- after second parameter +AS SELECT 1;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + MultilineProcedureParametersList = true, + PreserveComments = true, + }; + const string expected = @" +CREATE PROCEDURE p + -- before first parameter + @a INT -- after first parameter + -- before second parameter + , @b INT -- after second parameter +AS +SELECT 1;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementLeadingProcedureParametersWithSmallIndentation() + { + const string input = @"CREATE PROCEDURE p @a INT, +-- before second parameter +@b INT AS SELECT 1;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Leading, + IndentationSize = 1, + MultilineProcedureParametersList = true, + PreserveComments = true, + }; + const string expected = @" +CREATE PROCEDURE p + @a INT + -- before second parameter +, @b INT +AS +SELECT 1;"; + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCommaPlacementTrailingProcedureParametersPreservesCommentsAroundParameters() + { + const string input = @"CREATE PROCEDURE p +-- before first parameter +@a INT, -- after first parameter +-- before second parameter +@b INT -- after second parameter +AS SELECT 1;"; + var options = new SqlScriptGeneratorOptions + { + CommaPlacement = CommaPlacement.Trailing, + MultilineProcedureParametersList = true, + PreserveComments = true, + }; + const string expected = @" +CREATE PROCEDURE p + -- before first parameter + @a INT, -- after first parameter + -- before second parameter + @b INT -- after second parameter +AS +SELECT 1;"; + AssertGenerated(input, options, expected); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] diff --git a/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs b/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs index 61865b68..d7cbf1df 100644 --- a/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs +++ b/Test/SqlDom/ScriptGenerator/IdentifierFormattingTests.cs @@ -359,6 +359,38 @@ public void TestSuppressedFunctionNamePreservesOriginalBracketingAndCasing() AssertGenerated(input, options, expected); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingIncludeBracketsWindowOverReference() + { + // An unparenthesized "OVER window_name" reference is an ordinary identifier ("OVER [Win1]" + // is valid T-SQL), so it is bracketed like the WINDOW clause name it refers to. + const string input = "SELECT Sum(c1) OVER Win1 FROM t1 WINDOW Win1 AS (PARTITION BY c1)"; + var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); + const string expected = +@"SELECT Sum([c1]) OVER [Win1] FROM [t1] +WINDOW [Win1] AS (PARTITION BY [c1]);"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestIdentifierBracketingExcludeBracketsWindowOverReference() + { + // The "OVER window_name" reference and its WINDOW clause definition must stay in step: + // both lose their brackets and both are recased, so the reference still names the window. + const string input = "SELECT Sum(c1) OVER [Win1] FROM t1 WINDOW [Win1] AS (PARTITION BY c1)"; + var options = MakeOptions(IdentifierCasing.Uppercase, IdentifierBracketing.ExcludeBrackets); + const string expected = +@"SELECT Sum(C1) OVER WIN1 FROM T1 +WINDOW WIN1 AS (PARTITION BY C1);"; + + AssertGenerated(input, options, expected); + } + // ----------------------------------------------------------------------------------------- // Interaction: casing is applied after bracketing // ----------------------------------------------------------------------------------------- @@ -814,22 +846,6 @@ public void TestGapFederationNameNotBracketed() AssertGenerated(input, options, expected); } - // GAP-WINDOW: an unparenthesized "OVER window_name" reference must be a plain identifier - // ("OVER [Win1]" is invalid), while the WINDOW clause definition name may be bracketed. - [TestMethod] - [Priority(0)] - [SqlStudioTestCategory(Category.UnitTest)] - public void TestGapWindowOverReferenceNotBracketed() - { - const string input = "SELECT Sum(c1) OVER Win1 FROM t1 WINDOW Win1 AS (PARTITION BY c1)"; - var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.IncludeBrackets); - const string expected = -@"SELECT Sum([c1]) OVER Win1 FROM [t1] -WINDOW [Win1] AS (PARTITION BY [c1]);"; - - AssertGenerated(input, options, expected); - } - // GAP-TIMESTAMP: the INSERT BULK timestamp/rowversion shorthand column has no data type and its // name is the TIMESTAMP keyword ("([c2] CHAR, [TIMESTAMP])" is invalid); regular columns are // still bracketed. @@ -1000,6 +1016,7 @@ public void TestExcludeBracketsSpecialOperatorNameIsKnownLimitation() { const string input = "SELECT SOURCE FROM userTable CROSS APPLY dbo.[AI_GENERATE_CHUNKS](SOURCE);"; var options = MakeOptions(IdentifierCasing.Preserve, IdentifierBracketing.ExcludeBrackets); + options.NewLineBeforeJoinClause = false; const string expected = @"SELECT SOURCE FROM userTable CROSS APPLY dbo.AI_GENERATE_CHUNKS(SOURCE);"; AssertGeneratedWith(new TSql170Parser(true), new Sql170ScriptGenerator(options), input, expected); diff --git a/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs b/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs index 39ff4085..75c2b4e7 100644 --- a/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs +++ b/Test/SqlDom/ScriptGenerator/JoinClauseFormattingTests.cs @@ -195,10 +195,11 @@ INNER JOIN c [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] - public void TestCrossJoinUnaffectedByNewOptions() + public void TestCrossJoinUnaffectedByOnClauseOptions() { - // CROSS JOIN has no ON clause (it is an UnqualifiedJoin), so the new options do not - // change its formatting. + // CROSS JOIN has no ON clause (it is an UnqualifiedJoin), so the ON-related options + // (NewLineAfterJoinKeyword, NewLineBeforeOnClause) do not change its formatting. The + // leading newline comes from NewLineBeforeJoinClause, which defaults to true. const string input = "SELECT * FROM a CROSS JOIN b;"; var options = new SqlScriptGeneratorOptions { @@ -208,7 +209,8 @@ public void TestCrossJoinUnaffectedByNewOptions() const string expected = @" SELECT * -FROM a CROSS JOIN b;"; +FROM a + CROSS JOIN b;"; AssertGenerated(input, options, expected); } @@ -216,9 +218,10 @@ public void TestCrossJoinUnaffectedByNewOptions() [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] - public void TestCrossApplyUnaffectedByNewOptions() + public void TestCrossApplyUnaffectedByOnClauseOptions() { - // CROSS APPLY has no ON clause either, so the new options leave it unchanged. + // CROSS APPLY has no ON clause either, so the ON-related options leave it unchanged. The + // leading newline comes from NewLineBeforeJoinClause, which defaults to true. const string input = "SELECT * FROM a CROSS APPLY dbo.f(a.id) AS b;"; var options = new SqlScriptGeneratorOptions { @@ -228,11 +231,126 @@ public void TestCrossApplyUnaffectedByNewOptions() const string expected = @" SELECT * +FROM a + CROSS APPLY dbo.f(a.id) AS b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCrossApplyNewLineBeforeJoinClauseDefaultTrue() + { + // NewLineBeforeJoinClause (default true) applies to CROSS APPLY just like a qualified + // JOIN: the operator goes on its own line under the first table source. + const string input = "SELECT * FROM a CROSS APPLY dbo.f(a.id) AS b;"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +SELECT * +FROM a + CROSS APPLY dbo.f(a.id) AS b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCrossApplyInlineWhenNewLineBeforeJoinClauseFalse() + { + // When NewLineBeforeJoinClause is false, CROSS APPLY stays on the same line as the first + // table source. + const string input = "SELECT * FROM a CROSS APPLY dbo.f(a.id) AS b;"; + var options = new SqlScriptGeneratorOptions + { + NewLineBeforeJoinClause = false + }; + const string expected = +@" +SELECT * FROM a CROSS APPLY dbo.f(a.id) AS b;"; AssertGenerated(input, options, expected); } + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOuterApplyInlineWhenNewLineBeforeJoinClauseFalse() + { + // When NewLineBeforeJoinClause is false, OUTER APPLY stays on the same line as the first + // table source. + const string input = "SELECT * FROM a OUTER APPLY dbo.f(a.id) AS b;"; + var options = new SqlScriptGeneratorOptions + { + NewLineBeforeJoinClause = false + }; + const string expected = +@" +SELECT * +FROM a OUTER APPLY dbo.f(a.id) AS b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestOuterApplyNewLineBeforeJoinClauseDefaultTrue() + { + // NewLineBeforeJoinClause (default true) applies to OUTER APPLY just like a qualified + // JOIN: the operator goes on its own line under the first table source. + const string input = "SELECT * FROM a OUTER APPLY dbo.f(a.id) AS b;"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +SELECT * +FROM a + OUTER APPLY dbo.f(a.id) AS b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCrossJoinInlineWhenNewLineBeforeJoinClauseFalse() + { + // When NewLineBeforeJoinClause is false, CROSS JOIN stays on the same line as the first + // table source. + const string input = "SELECT * FROM a CROSS JOIN b;"; + var options = new SqlScriptGeneratorOptions + { + NewLineBeforeJoinClause = false + }; + const string expected = +@" +SELECT * +FROM a CROSS JOIN b;"; + + AssertGenerated(input, options, expected); + } + + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void TestCrossJoinNewLineBeforeJoinClauseDefaultTrue() + { + // NewLineBeforeJoinClause (default true) applies to CROSS JOIN just like a qualified + // JOIN: the operator goes on its own line under the first table source. + const string input = "SELECT * FROM a CROSS JOIN b;"; + var options = new SqlScriptGeneratorOptions(); + const string expected = +@" +SELECT * +FROM a + CROSS JOIN b;"; + + AssertGenerated(input, options, expected); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)] diff --git a/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql index 7c2656f9..2b577a6f 100644 --- a/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiAnalyzeSentimentTestsFabricDW.sql @@ -12,6 +12,12 @@ SELECT AI_ANALYZE_SENTIMENT(@s0 + 'a'); SELECT AI_ANALYZE_SENTIMENT('b' + 'a'); +SELECT AI_ANALYZE_SENTIMENT('text' ERROR ON ERROR); + +SELECT AI_ANALYZE_SENTIMENT('text' NULL ON ERROR); + +SELECT AI_ANALYZE_SENTIMENT('text' DEFAULT 'Sentiment unavailable' ON ERROR); + SELECT * FROM AI_ANALYZE_SENTIMENT((SELECT t.text_col FROM dbo.Texts AS t)); @@ -23,5 +29,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_ANALYZE_SENTIMENT(@s)); + RETURN (AI_ANALYZE_SENTIMENT(@s DEFAULT N'Sentiment unavailable' ON ERROR)); END diff --git a/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql index 2a623c02..8322a2db 100644 --- a/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiClassifyTestsFabricDW.sql @@ -11,6 +11,11 @@ SELECT AI_CLASSIFY(@s, 'topic', 'sentiment', 'intent'); SELECT AI_CLASSIFY('b' + 'a', 'topic', 'sentiment', 'intent'); SELECT AI_CLASSIFY(@s + 'a', 'topic', 'sentiment', 'intent'); SELECT * FROM AI_CLASSIFY((SELECT t.text_col FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); + +-- ON ERROR behaviors +SELECT AI_CLASSIFY('text', 'spam' ERROR ON ERROR); +SELECT AI_CLASSIFY('text', 'spam', 'ham' NULL ON ERROR); +SELECT AI_CLASSIFY(@s, 'topic', 'sentiment', 'intent' DEFAULT 'Classification unavailable' ON ERROR); GO -- RETURN context @@ -18,6 +23,6 @@ CREATE OR ALTER FUNCTION dbo.fx(@s NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN - RETURN (AI_CLASSIFY(@s, 'labelA', 'labelB')); + RETURN (AI_CLASSIFY(@s, 'labelA', 'labelB' DEFAULT N'Classification unavailable' ON ERROR)); END; GO diff --git a/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql index cf2c82e2..fa3c2472 100644 --- a/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiExtractTestsFabricDW.sql @@ -11,6 +11,11 @@ SELECT AI_EXTRACT(@s, 'topic', 'sentiment', 'intent'); SELECT AI_EXTRACT('b' + 'a', 'topic', 'sentiment', 'intent'); SELECT AI_EXTRACT(@s + 'a', 'topic', 'sentiment', 'intent'); SELECT * FROM AI_EXTRACT((SELECT t.text_col FROM dbo.Texts AS t), 'topic', 'sentiment', 'intent'); + +-- ON ERROR behaviors +SELECT AI_EXTRACT('text', 'spam' ERROR ON ERROR); +SELECT AI_EXTRACT('text', 'spam', 'ham' NULL ON ERROR); +SELECT AI_EXTRACT(@s, 'topic', 'sentiment', 'intent' DEFAULT 'Extraction unavailable' ON ERROR); GO -- RETURN context @@ -18,6 +23,6 @@ CREATE OR ALTER FUNCTION dbo.fx(@s NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN - RETURN (AI_EXTRACT(@s, 'labelA', 'labelB')); + RETURN (AI_EXTRACT(@s, 'labelA', 'labelB' DEFAULT N'Extraction unavailable' ON ERROR)); END; GO diff --git a/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql index 7e6225a6..8bfef169 100644 --- a/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiFixGrammarTestsFabricDW.sql @@ -12,6 +12,12 @@ SELECT AI_FIX_GRAMMAR(@s0 + 'a'); SELECT AI_FIX_GRAMMAR('b' + 'a'); +SELECT AI_FIX_GRAMMAR('text' ERROR ON ERROR); + +SELECT AI_FIX_GRAMMAR('text' NULL ON ERROR); + +SELECT AI_FIX_GRAMMAR('text' DEFAULT 'Correction unavailable' ON ERROR); + SELECT * FROM AI_FIX_GRAMMAR((SELECT t.text_col FROM dbo.Texts AS t)); @@ -23,5 +29,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_FIX_GRAMMAR(@s)); + RETURN (AI_FIX_GRAMMAR(@s DEFAULT N'Correction unavailable' ON ERROR)); END diff --git a/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql index 55cec5a1..d25347ff 100644 --- a/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiGenerateResponseTestsFabricDW.sql @@ -6,6 +6,9 @@ DECLARE @p1 NVARCHAR(MAX) = N'Prompt '; DECLARE @p2 NVARCHAR(MAX) = N'Continuation'; SELECT AI_GENERATE_RESPONSE(@p1 + 'part1', @p2); SELECT AI_GENERATE_RESPONSE('b' + 'a'); +SELECT AI_GENERATE_RESPONSE('Hello' ERROR ON ERROR); +SELECT AI_GENERATE_RESPONSE('Question:', ' What is the time?' NULL ON ERROR); +SELECT AI_GENERATE_RESPONSE(@p1, @p2 DEFAULT 'Response unavailable' ON ERROR); SELECT * FROM AI_GENERATE_RESPONSE((SELECT t.text_col FROM dbo.Texts AS t)); GO @@ -14,6 +17,6 @@ CREATE OR ALTER FUNCTION dbo.fx(@p NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN - RETURN (AI_GENERATE_RESPONSE(@p)); + RETURN (AI_GENERATE_RESPONSE(@p DEFAULT N'Response unavailable' ON ERROR)); END; GO diff --git a/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql index fbb972d0..89911348 100644 --- a/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiSummarizeTestsFabricDW.sql @@ -12,6 +12,12 @@ SELECT AI_SUMMARIZE(@s0 + 'a'); SELECT AI_SUMMARIZE('b' + 'a'); +SELECT AI_SUMMARIZE('text' ERROR ON ERROR); + +SELECT AI_SUMMARIZE('text' NULL ON ERROR); + +SELECT AI_SUMMARIZE('text' DEFAULT 'Summary unavailable' ON ERROR); + SELECT * FROM AI_SUMMARIZE((SELECT t.text_col FROM dbo.Texts AS t)); @@ -23,5 +29,5 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_SUMMARIZE(@s)); + RETURN (AI_SUMMARIZE(@s DEFAULT N'Summary unavailable' ON ERROR)); END diff --git a/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql b/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql index bcda9fb0..4a9893ca 100644 --- a/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/AiTranslateTestsFabricDW.sql @@ -8,6 +8,10 @@ DECLARE @s AS NVARCHAR (MAX) = N'Hello world'; DECLARE @lang AS NVARCHAR (5) = N'en'; SELECT AI_TRANSLATE (@s, @lang); SELECT AI_TRANSLATE (@s + 'a', @lang + 'a'); +SELECT AI_TRANSLATE ('Hello world', 'es' ERROR ON ERROR); +SELECT AI_TRANSLATE ('Hello world', 'es' NULL ON ERROR); +SELECT AI_TRANSLATE ('Hello world', 'es' DEFAULT 'Translation unavailable' ON ERROR); +SELECT AI_TRANSLATE (@s, @lang DEFAULT N'Translation unavailable' ON ERROR); SELECT * FROM AI_TRANSLATE((SELECT t.text_col FROM dbo.Texts AS t), 'e' + 's'); GO @@ -17,7 +21,7 @@ CREATE OR ALTER FUNCTION dbo.fx RETURNS NVARCHAR (MAX) AS BEGIN - RETURN (AI_TRANSLATE (@s, 'fr')); + RETURN (AI_TRANSLATE (@s, 'fr' DEFAULT N'Translation unavailable' ON ERROR)); END GO diff --git a/Test/SqlDom/TestScripts/AlterDatabaseScopedConfigTxnPriorityTests180.sql b/Test/SqlDom/TestScripts/AlterDatabaseScopedConfigTxnPriorityTests180.sql new file mode 100644 index 00000000..bba4e7c3 --- /dev/null +++ b/Test/SqlDom/TestScripts/AlterDatabaseScopedConfigTxnPriorityTests180.sql @@ -0,0 +1,20 @@ +-- TXN_PRIORITY_MODE = OFF +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MODE = OFF; + +-- TXN_PRIORITY_MODE = ROLLBACK +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MODE = ROLLBACK; + +-- TXN_PRIORITY_MODE = identifier (e.g., BLOCK) +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MODE = BLOCK; + +-- TXN_PRIORITY_MIN_WAIT_MILLISECONDS = integer +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 5000; + +-- TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 0 +ALTER DATABASE SCOPED CONFIGURATION SET TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 0; + +-- FOR SECONDARY with TXN_PRIORITY_MODE +ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET TXN_PRIORITY_MODE = PRIMARY; + +-- FOR SECONDARY with TXN_PRIORITY_MIN_WAIT_MILLISECONDS +ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET TXN_PRIORITY_MIN_WAIT_MILLISECONDS = 1000; diff --git a/Test/SqlDom/TestScripts/CreateAlterTableClusterByTestsFabricDW.sql b/Test/SqlDom/TestScripts/CreateAlterTableClusterByTestsFabricDW.sql index 05f8e022..b2102240 100644 --- a/Test/SqlDom/TestScripts/CreateAlterTableClusterByTestsFabricDW.sql +++ b/Test/SqlDom/TestScripts/CreateAlterTableClusterByTestsFabricDW.sql @@ -25,14 +25,21 @@ WITH (CLUSTER BY (ProductID)); GO ALTER TABLE Customers - ADD (CLUSTER BY (CustomerID)); + WITH (CLUSTER BY (CustomerID)); GO ALTER TABLE sales.Orders - ADD (CLUSTER BY (CustomerID, OrderDate)); + WITH (CLUSTER BY (CustomerID, OrderDate)); GO ALTER TABLE Inventory - ADD (CLUSTER BY (ProductID)); \ No newline at end of file + WITH (CLUSTER BY (ProductID)); + + +GO +CREATE TABLE CustomersClustered +WITH (CLUSTER BY (CustomerID)) AS +SELECT * +FROM Customers; \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/QueryHintsTestsFabricDW.sql b/Test/SqlDom/TestScripts/QueryHintsTestsFabricDW.sql new file mode 100644 index 00000000..4b2e7d80 --- /dev/null +++ b/Test/SqlDom/TestScripts/QueryHintsTestsFabricDW.sql @@ -0,0 +1,41 @@ +SELECT * +FROM t1 + INNER HASH JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT * +FROM t1 + INNER REPLICATE JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT * +FROM t1 + INNER REDISTRIBUTE JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT * +FROM t1 + INNER REDISTRIBUTE(2) JOIN + t2 + ON t1.c1 = t2.c1; +GO + +SELECT c1 +FROM t1 +OPTION (FORCE SINGLE NODE PLAN); +GO + +SELECT c1 +FROM t1 +OPTION (FORCE DISTRIBUTED PLAN); +GO + +SELECT c1 +FROM t1 +OPTION (FOR TIMESTAMP AS OF '2024-05-01T10:00:00'); \ No newline at end of file diff --git a/Test/SqlDom/TestScripts/WindowClauseQuotedNameTests160.sql b/Test/SqlDom/TestScripts/WindowClauseQuotedNameTests160.sql new file mode 100644 index 00000000..8a5ee8a2 --- /dev/null +++ b/Test/SqlDom/TestScripts/WindowClauseQuotedNameTests160.sql @@ -0,0 +1,46 @@ +CREATE PROCEDURE [dbo].[ExampleProc] +AS +BEGIN + SELECT ROW_NUMBER() OVER [win] AS [RowNum], + SUM([Amount]) OVER [win] AS [RunningTotal] + FROM [dbo].[Transactions] + WINDOW [win] AS (PARTITION BY [AccountID] ORDER BY [TransactionDate]); +END + + +GO +SELECT COUNT(*) OVER [win] +FROM t1 +WINDOW [win] AS (PARTITION BY c1); + + +GO +SELECT LAST_VALUE(c1) IGNORE NULLS OVER [win] +FROM t1 +WINDOW [win] AS (ORDER BY c2); + + +GO +SELECT LAG(c1) OVER [my win] +FROM t1 +WINDOW [my win] AS (ORDER BY c2); + + +GO +SELECT SUM(c1) OVER [select] +FROM t1 +WINDOW [select] AS (PARTITION BY c2); + + +GO +SELECT SUM(c1) OVER "win" +FROM t1 +WINDOW "win" AS (PARTITION BY c2); + + +GO +CREATE VIEW v1 +AS +SELECT AVG(c1) OVER [win] AS a +FROM t1 +WINDOW [win] AS ([base] ORDER BY c2), [base] AS (PARTITION BY c3); diff --git a/Test/SqlDom/UnicodeNonCharacterLexerTests.cs b/Test/SqlDom/UnicodeNonCharacterLexerTests.cs new file mode 100644 index 00000000..ad504b8c --- /dev/null +++ b/Test/SqlDom/UnicodeNonCharacterLexerTests.cs @@ -0,0 +1,319 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +//------------------------------------------------------------------------------ + +using System.Collections.Generic; +using System.IO; +using Microsoft.SqlServer.TransactSql.ScriptDom; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SqlStudio.Tests.AssemblyTools.TestCategory; + +namespace SqlStudio.Tests.UTSqlScriptDom +{ + /// + /// Regression tests for the lexer treating the Unicode non-character U+FFFF + /// (char.MaxValue) as an end-of-input sentinel. A literal U+FFFF appearing inside + /// a string literal, delimited identifier, or comment must be scanned as a normal + /// character; real end-of-input must be detected by stream position only. + /// + /// Downstream: DacFx GitHub issue #796 - stored procedures + /// whose bodies contain NCHAR(0xFFFE)/NCHAR(0xFFFF) caused continuous schema drift + /// because ScriptDom stopped scanning at the literal U+FFFF. + /// + public partial class SqlDomTests + { + // Unicode non-characters. U+FFFE is handled fine today; only U+FFFF + // (== char.MaxValue == CharScanner.EOF_CHAR) triggers the failure. + private const string UFFFE = "\uFFFE"; + private const string UFFFF = "\uFFFF"; + + private static TSqlScript ParseScript(TSqlParser parser, string source, out IList errors) + { + using (StringReader reader = new StringReader(source)) + { + return (TSqlScript)parser.Parse(reader, out errors); + } + } + + /// + /// Lexer-level guarantee across every parser version: an N'...' string literal + /// containing both U+FFFE and U+FFFF parses cleanly and the literal value + /// round-trips with the U+FFFF preserved (proving the scanner consumed past it). + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerTreatsUFFFFAsLiteralInStringLiteral() + { + string source = "SELECT N'hi" + UFFFE + UFFFF + "lo' AS c;"; + + ParserTestUtils.ExecuteTestForAllParsers(parser => + { + TSqlScript script = ParseScript(parser, source, out IList errors); + + ParserTestUtils.LogErrors(errors, source); + Assert.AreEqual(0, errors.Count, "U+FFFF inside a string literal must not terminate scanning."); + + SelectStatement select = (SelectStatement)script.Batches[0].Statements[0]; + QuerySpecification query = (QuerySpecification)select.QueryExpression; + SelectScalarExpression element = (SelectScalarExpression)query.SelectElements[0]; + StringLiteral literal = (StringLiteral)element.Expression; + + Assert.AreEqual("hi" + UFFFE + UFFFF + "lo", literal.Value, + "The U+FFFF must round-trip as a literal character inside the string literal."); + }, true); + } + + /// + /// The verbatim DacFx minimal repro: a CREATE PROCEDURE whose body contains a + /// string literal with U+FFFE + U+FFFF must parse to a single complete statement + /// that spans the entire input. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void ParseProcedureWithUnicodeNonCharactersIsComplete() + { + string body = + "CREATE PROCEDURE dbo.p AS BEGIN " + + "DECLARE @s NVARCHAR(50) = N'hi" + UFFFE + UFFFF + "lo'; " + + "SELECT @s; END"; + + ParserTestUtils.ExecuteTestForParsers(parser => + { + TSqlScript script = ParseScript(parser, body, out IList errors); + + ParserTestUtils.LogErrors(errors, body); + Assert.AreEqual(0, errors.Count, "U+FFFF in the procedure body must not terminate scanning."); + + IList statements = script.Batches[0].Statements; + Assert.AreEqual(1, statements.Count, "Exactly one statement should be produced."); + + CreateProcedureStatement statement = (CreateProcedureStatement)statements[0]; + Assert.AreEqual(body.Length, statement.StartOffset + statement.FragmentLength, + "The statement must cover the whole input, including everything after U+FFFF."); + }, new TSql160Parser(true), new TSql170Parser(true), new TSql180Parser(true)); + } + + /// + /// U+FFFF inside the bodies of CREATE VIEW / FUNCTION / TRIGGER must not stop + /// scanning; each produces a single statement covering the whole input. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerHandlesUFFFFInViewFunctionTriggerBodies() + { + string literal = "N'hi" + UFFFE + UFFFF + "lo'"; + string view = "CREATE VIEW dbo.v AS SELECT " + literal + " AS c"; + string function = + "CREATE FUNCTION dbo.f() RETURNS NVARCHAR(50) AS BEGIN RETURN " + literal + "; END"; + string trigger = + "CREATE TRIGGER dbo.tr ON dbo.t AFTER INSERT AS SELECT " + literal + " AS c"; + + ParserTestUtils.ExecuteTestForParsers(parser => + { + foreach (string body in new[] { view, function, trigger }) + { + TSqlScript script = ParseScript(parser, body, out IList errors); + + ParserTestUtils.LogErrors(errors, body); + Assert.AreEqual(0, errors.Count, "U+FFFF must not terminate scanning for: " + body); + + IList statements = script.Batches[0].Statements; + Assert.AreEqual(1, statements.Count, "Exactly one statement should be produced for: " + body); + Assert.AreEqual(body.Length, + statements[0].StartOffset + statements[0].FragmentLength, + "The statement must span the whole input for: " + body); + } + }, new TSql160Parser(true), new TSql170Parser(true), new TSql180Parser(true)); + } + + /// + /// A delimited identifier containing U+FFFF must parse and preserve the character. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerHandlesUFFFFInDelimitedIdentifier() + { + string source = "SELECT 1 AS [col" + UFFFF + "];"; + + ParserTestUtils.ExecuteTestForAllParsers(parser => + { + TSqlScript script = ParseScript(parser, source, out IList errors); + + ParserTestUtils.LogErrors(errors, source); + Assert.AreEqual(0, errors.Count, "U+FFFF inside a delimited identifier must not terminate scanning."); + + SelectStatement select = (SelectStatement)script.Batches[0].Statements[0]; + QuerySpecification query = (QuerySpecification)select.QueryExpression; + SelectScalarExpression element = (SelectScalarExpression)query.SelectElements[0]; + + Assert.AreEqual("col" + UFFFF, element.ColumnName.Identifier.Value, + "The U+FFFF must round-trip inside the delimited identifier."); + }, true); + } + + /// + /// U+FFFF inside a block comment and a line comment must not terminate scanning; + /// the following SELECT must still be parsed. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerHandlesUFFFFInComments() + { + string blockComment = "/* c" + UFFFF + " */ SELECT 1 AS c;"; + string lineComment = "-- c" + UFFFF + "\r\nSELECT 1 AS c;"; + + ParserTestUtils.ExecuteTestForAllParsers(parser => + { + foreach (string source in new[] { blockComment, lineComment }) + { + TSqlScript script = ParseScript(parser, source, out IList errors); + + ParserTestUtils.LogErrors(errors, source); + Assert.AreEqual(0, errors.Count, "U+FFFF inside a comment must not terminate scanning for: " + source); + + IList statements = script.Batches[0].Statements; + Assert.AreEqual(1, statements.Count, + "The SELECT after the comment must still be parsed for: " + source); + Assert.IsInstanceOfType(statements[0], typeof(SelectStatement)); + } + }, true); + } + + /// + /// Sanity guard: a string literal that genuinely runs to end-of-stream must still + /// report the unterminated-literal error. The fix must not mask real EOF errors. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerStillReportsUnterminatedLiteralAtEndOfStream() + { + string source = "SELECT N'abc"; + + ParserTestUtils.ExecuteTestForAllParsers(parser => + { + ParseScript(parser, source, out IList errors); + Assert.AreEqual(1, errors.Count, + "A genuinely unterminated literal at end-of-stream must still produce an error."); + }, true); + } + + /// + /// The integer lookahead contract must retain every char value while keeping + /// end-of-input outside that range, without changing ordinary case folding. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerIntegerLookaheadPreservesCharacterAndSentinelValues() + { + antlr.CharBuffer inputBuffer = new antlr.CharBuffer(new StringReader(UFFFF)); + + Assert.AreEqual((int)char.MaxValue, inputBuffer.LA(1)); + Assert.AreEqual(antlr.CharScanner.EOF_CHAR, inputBuffer.LA(2)); + + DiagnosticCharScanner scanner = new DiagnosticCharScanner(); + Assert.AreEqual((int)'a', scanner.toLower('A')); + Assert.AreEqual(antlr.CharScanner.EOF_CHAR, scanner.toLower(antlr.CharScanner.EOF_CHAR)); + Assert.AreEqual(-1, scanner.toLower(-1)); + } + + /// + /// Lexer exceptions must retain the out-of-range EOF sentinel so diagnostics do + /// not confuse end-of-input with a real U+0000 or U+FFFF character. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void LexerExceptionDiagnosticsPreserveEndOfInput() + { + antlr.NoViableAltForCharException eofAlternative = new antlr.NoViableAltForCharException( + antlr.CharScanner.EOF_CHAR, string.Empty, 1, 1); + antlr.NoViableAltForCharException nullAlternative = + new antlr.NoViableAltForCharException('\0', string.Empty, 1, 1); + antlr.NoViableAltForCharException uffffAlternative = + new antlr.NoViableAltForCharException(char.MaxValue, string.Empty, 1, 1); + + Assert.AreEqual(antlr.CharScanner.EOF_CHAR, eofAlternative.foundChar); + Assert.AreEqual("unexpected char: ", eofAlternative.Message); + Assert.AreEqual("unexpected char: 0x0", nullAlternative.Message); + Assert.AreEqual("unexpected char: 0xFFFF", uffffAlternative.Message); + + antlr.TokenStreamRecognitionException eofTokenStreamException = + new antlr.TokenStreamRecognitionException(eofAlternative); + ParseError eofParseError = TSql80ParserBaseInternal.ProcessTokenStreamRecognitionException( + eofTokenStreamException, 0); + antlr.NoViableAltForCharException printableAlternative = + new antlr.NoViableAltForCharException('@', string.Empty, 1, 1); + ParseError printableParseError = TSql80ParserBaseInternal.ProcessTokenStreamRecognitionException( + new antlr.TokenStreamRecognitionException(printableAlternative), 0); + + Assert.AreEqual("Incorrect syntax near ''.", eofParseError.Message); + Assert.AreEqual("Incorrect syntax near '@'.", printableParseError.Message); + + DiagnosticCharScanner scanner = new DiagnosticCharScanner(); + antlr.MismatchedCharException eofMismatch = new antlr.MismatchedCharException( + antlr.CharScanner.EOF_CHAR, 'x', false, scanner); + antlr.MismatchedCharException uffffMismatch = new antlr.MismatchedCharException( + char.MaxValue, 'x', false, scanner); + + Assert.AreEqual(antlr.CharScanner.EOF_CHAR, eofMismatch.foundChar); + StringAssert.Contains(eofMismatch.Message, "''"); + Assert.AreEqual(char.MaxValue, uffffMismatch.foundChar); + Assert.IsFalse(uffffMismatch.Message.Contains("")); + } + + /// + /// Generator round-trip: parse -> SqlScriptGenerator -> string must preserve U+FFFF, + /// and the generated script must re-parse with zero errors. + /// + [TestMethod] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void GeneratorRoundTripsUFFFFInStringLiteral() + { + string body = + "CREATE PROCEDURE dbo.p AS BEGIN " + + "DECLARE @s NVARCHAR(50) = N'hi" + UFFFE + UFFFF + "lo'; " + + "SELECT @s; END"; + + RoundTrip(new TSql160Parser(true), SqlVersion.Sql160, body); + RoundTrip(new TSql170Parser(true), SqlVersion.Sql170, body); + RoundTrip(new TSql180Parser(true), SqlVersion.Sql180, body); + } + + private static void RoundTrip(TSqlParser parser, SqlVersion version, string body) + { + TSqlScript script = ParseScript(parser, body, out IList errors); + ParserTestUtils.LogErrors(errors, body); + Assert.AreEqual(0, errors.Count, "Source must parse cleanly before generation."); + + SqlScriptGenerator generator = ParserTestUtils.CreateScriptGen(version); + StringWriter writer = new StringWriter(); + generator.GenerateScript(script, writer); + string generated = writer.ToString(); + + Assert.IsTrue(generated.Contains(UFFFF), "Generated script must preserve U+FFFF."); + Assert.IsTrue(generated.Contains(UFFFE), "Generated script must preserve U+FFFE."); + + ParseScript(parser, generated, out IList reparseErrors); + ParserTestUtils.LogErrors(reparseErrors, generated); + Assert.AreEqual(0, reparseErrors.Count, "Generated script must re-parse with zero errors."); + } + + private sealed class DiagnosticCharScanner : antlr.CharScanner + { + public DiagnosticCharScanner() + : base(new antlr.CharBuffer(new StringReader(string.Empty))) + { + } + } + } +} diff --git a/release-notes/180/180.140.0.md b/release-notes/180/180.140.0.md new file mode 100644 index 00000000..a0b8366f --- /dev/null +++ b/release-notes/180/180.140.0.md @@ -0,0 +1,33 @@ +# Release Notes + +## Microsoft.SqlServer.TransactSql.ScriptDom 180.140.0 +This update brings the following changes over the previous release: + +### Target Platform Support + +* .NET Framework 4.7.2 (Windows x86, Windows x64) +* .NET 8 (Windows x86, Windows x64, Linux, macOS) +* .NET Standard 2.0+ (Windows x86, Windows x64, Linux, macOS) + +### Dependencies +* None + +#### .NET Framework +#### .NET Core + +### New Features +* Adds `ON ERROR` clause support (`ERROR`, `NULL`, and `DEFAULT`) for Fabric DW AI functions: `AI_ANALYZE_SENTIMENT`, `AI_CLASSIFY`, `AI_EXTRACT`, `AI_FIX_GRAMMAR`, `AI_GENERATE_RESPONSE`, `AI_SUMMARIZE`, and `AI_TRANSLATE`. +* Adds Fabric DW join hints (`REPLICATE` and `REDISTRIBUTE`) and query hints, including `FORCE SINGLE NODE PLAN`, `FORCE DISTRIBUTED PLAN`, and `FOR TIMESTAMP AS OF`. + +### Fixed +* Fixes parsing of bracketed and double-quoted named `WINDOW` references in SQL Server 2022 and later. +* Fixes lexer handling of U+FFFF in string literals, delimited identifiers, and comments so it is not treated as end-of-input. +* Fixes source-token ranges for `GROUP BY ALL` in the Fabric DW parser. +* Fixes `ColumnAliasStyle.Preserve` so it retains whether a SELECT column alias used the `AS` keyword. +* Fixes preserved comment ordering and placement around comma-separated lists, before `FROM`, and in stored procedure parameters. + +### Changes +* None + +### Known Issues +* None From 72bb211088dc80e314c890edd89b850dd4aa6636 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:36:04 -0700 Subject: [PATCH 44/45] Bump actions/upload-artifact (#236) Bumps the github-actions group with 1 update: [actions/upload-artifact](https://github.com/actions/upload-artifact). Updates `actions/upload-artifact` from 7.0.1 to 7.0.2 - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/043fb46d1a93c77aae656e7c1c64a875d1fc6a0a...cf430e030ddbb5b0abf93d22962f4752f3646cd9) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: 7.0.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/pr-validation.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml index 7d16e3c5..9a136458 100644 --- a/.github/workflows/pr-validation.yml +++ b/.github/workflows/pr-validation.yml @@ -20,7 +20,7 @@ jobs: run: dotnet build dirs.proj - name: Archive antlr log for troubleshooting if: ${{ failure() && matrix.os == 'ubuntu-latest' }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: antlr-log path: SqlScriptDom/NUL From 3ea69b6fc1ed76b63eca6df868f3d1347b92e9fb Mon Sep 17 00:00:00 2001 From: Leila Lali Date: Wed, 21 Oct 2026 10:27:05 -0700 Subject: [PATCH 45/45] Fix COPY option formatting and round-trip handling (#235) Use standard fragment writers for COPY option strings and identifiers while retaining existing casing behavior. Add round-trip coverage across parser versions and formatting modes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../SqlScriptGeneratorVisitor.CopyOption.cs | 49 ++++--- .../ScriptGenerator/ScriptGeneratorTests.cs | 126 ++++++++++++++++++ 2 files changed, 158 insertions(+), 17 deletions(-) diff --git a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CopyOption.cs b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CopyOption.cs index 94a4b11c..7678371e 100644 --- a/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CopyOption.cs +++ b/SqlScriptDom/ScriptDom/SqlServer/ScriptGenerator/SqlScriptGeneratorVisitor.CopyOption.cs @@ -4,7 +4,6 @@ // //------------------------------------------------------------------------------ using System; -using System.Globalization; namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator { @@ -26,14 +25,13 @@ public override void ExplicitVisit(CopyOption node) break; } GenerateSymbol(TSqlTokenType.LeftParenthesis); - string identityValue = ExtractStringValue(((CopyCredentialOption)node.Value).Identity); - GenerateNameEqualsValue("Identity", string.Format(CultureInfo.InvariantCulture, "'{0}'", identityValue)); + CopyCredentialOption credential = (CopyCredentialOption)node.Value; + GenerateNameEqualsValue("Identity", GetCopyOptionStringLiteral(credential.Identity)); - if (((CopyCredentialOption)node.Value).Secret != null) + if (credential.Secret != null) { GenerateSymbol(TSqlTokenType.Comma); - string secretValue = ExtractStringValue(((CopyCredentialOption)node.Value).Secret); - GenerateNameEqualsValue("Secret", string.Format(CultureInfo.InvariantCulture, "'{0}'", secretValue)); + GenerateNameEqualsValue("Secret", GetCopyOptionStringLiteral(credential.Secret)); } GenerateSymbol(TSqlTokenType.RightParenthesis); NewLine(); @@ -48,29 +46,46 @@ public override void ExplicitVisit(CopyOption node) } else { - string optionValue = ExtractStringValue(node.Value); - - if (node.Kind == CopyOptionKind.FirstRow || node.Kind == CopyOptionKind.MaxErrors || node.Kind == CopyOptionKind.File_Format) - GenerateNameEqualsValue(node.Kind.ToString(), string.Format(CultureInfo.InvariantCulture, "{0}", optionValue)); + if (node.Kind == CopyOptionKind.FirstRow || node.Kind == CopyOptionKind.MaxErrors) + GenerateNameEqualsValue(node.Kind.ToString(), ExtractStringValue(node.Value)); + else if (node.Kind == CopyOptionKind.File_Format) + { + Identifier identifier = ((SingleValueTypeCopyOption)node.Value).SingleValue.Identifier; + GenerateNameEqualsValue(node.Kind.ToString(), new Identifier + { + Value = ScriptGeneratorSupporter.GetCasedString(identifier.Value, _options.KeywordCasing), + QuoteType = identifier.QuoteType + }); + } else - GenerateNameEqualsValue(node.Kind.ToString(), string.Format(CultureInfo.InvariantCulture, "'{0}'", optionValue)); + GenerateNameEqualsValue(node.Kind.ToString(), GetCopyOptionStringLiteral( + (StringLiteral)((SingleValueTypeCopyOption)node.Value).SingleValue.ValueExpression)); } NewLine(); } } /// - /// Extracts value from copy credential option. + /// Creates a string literal with the existing COPY option casing. /// - /// Copy option. - /// Extracted string. - private string ExtractStringValue(StringLiteral credOption) + /// Copy option literal. + /// A cased copy of the literal. + private StringLiteral GetCopyOptionStringLiteral(StringLiteral literal) { - if (credOption == null) + if (literal == null) { throw new ArgumentNullException("Invalid Credential values"); } - return credOption.Value; + + // Legacy PascalCase applied to the leading quote, leaving the value lowercase. + KeywordCasing casing = _options.KeywordCasing == KeywordCasing.PascalCase + ? KeywordCasing.Lowercase : _options.KeywordCasing; + return new StringLiteral + { + Value = ScriptGeneratorSupporter.GetCasedString(literal.Value, casing), + IsNational = literal.IsNational, + Collation = literal.Collation + }; } /// diff --git a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs index 72f0b680..d66656b6 100644 --- a/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs +++ b/Test/SqlDom/ScriptGenerator/ScriptGeneratorTests.cs @@ -17,6 +17,132 @@ namespace SqlStudio.Tests.UTSqlScriptDom [TestClass] public class SqlScriptGeneratorTests { + [DataTestMethod] + [DataRow("ERRORFILE = 'reader''s/files'", "ErrorFile = 'READER''S/FILES'")] + [DataRow("ERRORFILE = '''reader''''s'''", "ErrorFile = '''READER''''S'''")] + [DataRow("ERRORFILE = N'r\u00e9ader''s/files'", "ErrorFile = N'R\u00c9ADER''S/FILES'")] + [DataRow("FIELDTERMINATOR = 'a''b'", "FieldTerminator = 'A''B'")] + [DataRow("ROWTERMINATOR = 'a''''b'", "RowTerminator = 'A''''B'")] + [DataRow("FIELDQUOTE = ''''", "FieldQuote = ''''")] + [DataRow("FIELDQUOTE = ''", "FieldQuote = ''")] + [DataRow("FIELDTERMINATOR = '0x0a'", "FieldTerminator = '0X0A'")] + [DataRow("FILE_TYPE = 'csv'", "File_Type = 'CSV'")] + [DataRow("COMPRESSION = 'gzip'", "Compression = 'GZIP'")] + [DataRow("DATEFORMAT = 'ymd'", "DateFormat = 'YMD'")] + [DataRow("ENCODING = 'utf8'", "Encoding = 'UTF8'")] + [DataRow("IDENTITY_INSERT = 'on'", "Identity_Insert = 'ON'")] + [DataRow("FIRSTROW = 2", "FirstRow = 2")] + [DataRow("MAXERRORS = 0", "MaxErrors = 0")] + [DataRow("FILE_FORMAT = fileformat", "File_Format = FILEFORMAT")] + [DataRow("FILE_FORMAT = [reader's format]", "File_Format = [READER'S FORMAT]")] + [DataRow("FILE_FORMAT = [reader]]s]", "File_Format = [READER]]S]")] + [DataRow("FILE_FORMAT = \"reader\"\"s format\"", "File_Format = \"READER\"\"S FORMAT\"")] + [DataRow("FILE_FORMAT = [select]", "File_Format = [SELECT]")] + [DataRow("FILE_FORMAT = [format;(1)]", "File_Format = [FORMAT;(1)]")] + [DataRow("CREDENTIAL = (IDENTITY = 'Shared Access Signature', SECRET = 'reader''s''''key')", + "Credential = (Identity = 'SHARED ACCESS SIGNATURE',Secret = 'READER''S''''KEY')")] + [DataRow("ERRORFILE_CREDENTIAL = (IDENTITY = 'Shared Access Signature', SECRET = '''key''')", + "ERRORFILE_CREDENTIAL = (Identity = 'SHARED ACCESS SIGNATURE',Secret = '''KEY''')")] + [DataRow("CREDENTIAL = (IDENTITY = N'Shared Access Signature', SECRET = N'key''value')", + "Credential = (Identity = N'SHARED ACCESS SIGNATURE',Secret = N'KEY''VALUE')")] + [DataRow("CREDENTIAL = (IDENTITY = 'Managed Identity')", + "Credential = (Identity = 'MANAGED IDENTITY')")] + [DataRow("ERRORFILE_CREDENTIAL = (IDENTITY = 'Managed Identity')", + "ERRORFILE_CREDENTIAL = (Identity = 'MANAGED IDENTITY')")] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CopyOptionRoundTrip(string option, string expectedOption) + { + SqlVersion[] versions = + { + SqlVersion.Sql130, SqlVersion.Sql140, SqlVersion.Sql150, SqlVersion.Sql160, + SqlVersion.Sql170, SqlVersion.Sql180, SqlVersion.SqlFabricDW + }; + + foreach (SqlVersion version in versions) + { + VerifyCopyOptionRoundTrip(TSqlParser.CreateParser(version, true), + ParserTestUtils.CreateScriptGen(version), option, expectedOption); + } + + VerifyCopyOptionRoundTrip(new TSql160Parser(true), new SqlServerlessScriptGenerator(), + option, expectedOption); + } + + [DataTestMethod] + [DataRow(KeywordCasing.Uppercase, "ErrorFile = 'READER''S/FILES'", "File_Format = [MY FORMAT]")] + [DataRow(KeywordCasing.Lowercase, "ErrorFile = 'reader''s/files'", "File_Format = [my format]")] + [DataRow(KeywordCasing.PascalCase, "ErrorFile = 'reader''s/files'", "File_Format = [My format]")] + [Priority(0)] + [SqlStudioTestCategory(Category.UnitTest)] + public void CopyOptionCasing(KeywordCasing casing, string expectedLiteral, string expectedIdentifier) + { + var generator = new Sql160ScriptGenerator(new SqlScriptGeneratorOptions { KeywordCasing = casing }); + VerifyCopyOptionRoundTrip(new TSql160Parser(true), generator, + "ERRORFILE = 'Reader''s/Files'", expectedLiteral); + VerifyCopyOptionRoundTrip(new TSql160Parser(true), generator, + "FILE_FORMAT = [My Format]", expectedIdentifier); + } + + private static void VerifyCopyOptionRoundTrip(TSqlParser parser, SqlScriptGenerator generator, + string option, string expectedOption) + { + string sql = "COPY INTO dbo.t FROM 'https://example.invalid/data.csv' WITH (" + option + ");"; + var script = (TSqlScript)parser.Parse(new StringReader(sql), out var errors); + Assert.AreEqual(0, errors.Count, sql); + var original = (CopyStatement)script.Batches[0].Statements[0]; + var originalCredential = original.Options[0].Value as CopyCredentialOption; + var originalSingleValue = (original.Options[0].Value as SingleValueTypeCopyOption)?.SingleValue; + string originalIdentity = originalCredential?.Identity.Value; + string originalSecret = originalCredential?.Secret?.Value; + string originalValue = originalSingleValue?.Value; + QuoteType? originalQuoteType = originalSingleValue?.Identifier?.QuoteType; + + generator.GenerateScript(script, out string generated); + StringAssert.Contains(generated, expectedOption, parser.GetType().Name); + Assert.AreEqual(originalIdentity, originalCredential?.Identity.Value); + Assert.AreEqual(originalSecret, originalCredential?.Secret?.Value); + Assert.AreEqual(originalValue, originalSingleValue?.Value); + Assert.AreEqual(originalQuoteType, originalSingleValue?.Identifier?.QuoteType); + + var reparsed = (TSqlScript)parser.Parse(new StringReader(generated), out var reparseErrors); + Assert.AreEqual(0, reparseErrors.Count, generated); + Assert.AreEqual(1, reparsed.Batches.Count, generated); + Assert.AreEqual(1, reparsed.Batches[0].Statements.Count, generated); + Assert.IsInstanceOfType(reparsed.Batches[0].Statements[0], typeof(CopyStatement)); + var copy = (CopyStatement)reparsed.Batches[0].Statements[0]; + Assert.AreEqual(1, copy.Options.Count); + Assert.AreEqual(original.Options[0].Kind, copy.Options[0].Kind); + + var expected = (TSqlScript)parser.Parse(new StringReader( + "COPY INTO dbo.t FROM 'https://example.invalid/data.csv' WITH (" + expectedOption + ");"), + out var expectedErrors); + Assert.AreEqual(0, expectedErrors.Count); + var expectedCopy = (CopyStatement)expected.Batches[0].Statements[0]; + if (copy.Options[0].Value is CopyCredentialOption credential) + { + var expectedCredential = (CopyCredentialOption)expectedCopy.Options[0].Value; + Assert.AreEqual(expectedCredential.Identity.Value, credential.Identity.Value); + Assert.AreEqual(expectedCredential.Identity.IsNational, credential.Identity.IsNational); + Assert.AreEqual(expectedCredential.Secret?.Value, credential.Secret?.Value); + Assert.AreEqual(expectedCredential.Secret?.IsNational, credential.Secret?.IsNational); + } + else + { + var actualValue = ((SingleValueTypeCopyOption)copy.Options[0].Value).SingleValue; + var expectedValue = ((SingleValueTypeCopyOption)expectedCopy.Options[0].Value).SingleValue; + Assert.AreEqual(expectedValue.Value, actualValue.Value); + Assert.AreEqual(expectedValue.Identifier?.QuoteType, actualValue.Identifier?.QuoteType); + Assert.AreEqual((expectedValue.ValueExpression as StringLiteral)?.IsNational, + (actualValue.ValueExpression as StringLiteral)?.IsNational); + } + + generator.GenerateScript(reparsed, out string regenerated); + Assert.AreEqual(generated, regenerated); + generator.GenerateScript(script, out string generatedAgain); + Assert.AreEqual(generated, generatedAgain); + } + [TestMethod] [Priority(0)] [SqlStudioTestCategory(Category.UnitTest)]