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 01/12] 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 02/12] 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 03/12] 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 04/12] 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 05/12] 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 06/12] 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 07/12] 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 08/12] 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 09/12] 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 10/12] 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 11/12] 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 12/12] 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)]