Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 0 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
test:
Expand Down
20 changes: 14 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ The `TsqlAstParser/` directory contains a C# tool that generates `ast.json` file
2. Download the NuGet package (if `packages/` directory is empty):
```bash
mkdir -p packages
curl -L -o packages/microsoft.sqlserver.transactsql.scriptdom.170.128.0.nupkg \
"https://api.nuget.org/v3-flatcontainer/microsoft.sqlserver.transactsql.scriptdom/170.128.0/microsoft.sqlserver.transactsql.scriptdom.170.128.0.nupkg"
curl -L -o packages/microsoft.sqlserver.transactsql.scriptdom.180.154.0.nupkg \
"https://api.nuget.org/v3-flatcontainer/microsoft.sqlserver.transactsql.scriptdom/180.154.0/microsoft.sqlserver.transactsql.scriptdom.180.154.0.nupkg"
```

3. Build the tool:
Expand All @@ -83,10 +83,18 @@ done

### Limitations

TsqlAstParser uses TSql160Parser (SQL Server 2022) and cannot parse:
- SQL Server 170+ features (VECTOR indexes, AI functions, JSON enhancements)
- Fabric DW-specific syntax (CLONE TABLE, CLUSTER BY)
- Deprecated syntax removed in newer versions
TsqlAstParser uses TSql180Parser (the newest SQL Server parser in ScriptDom 180.x), or TSqlFabricDWParser when the test name contains `FabricDW`. It cannot parse:
- Deprecated syntax removed in newer versions (e.g. `*=` joins, `DUMP`/`LOAD`)
- Intentionally invalid SQL (error test cases)
- PhaseOne partial statements (their `ast.json` files are hand-written and have no positions)

Tests for unsupported syntax will not have `ast.json` files generated.

## Syncing tests with upstream ScriptDom

Test cases come from [microsoft/SqlScriptDOM](https://github.com/microsoft/SqlScriptDOM) `Test/SqlDom`:
- `TestScripts/<Name>.sql` → `parser/testdata/<Name>/query.sql`
- `Baselines<Ver>/<Name>.sql` → `parser/testdata/Baselines<Ver>_<Name>/query.sql`
- `PhaseOneTestScripts/<Name>.sql` → `parser/testdata/PhaseOne_<Name>/query.sql` (the first, intentionally invalid line is dropped)

When bumping the ScriptDom version, update `TsqlAstParser.csproj` (and the parser class in `Program.cs` if a newer one exists), copy new or changed scripts from upstream, regenerate every `ast.json` that the tool can parse, and mark new tests `{"todo": true}`. Tests the tool cannot parse keep `{"invalid_syntax": true}`.
7 changes: 6 additions & 1 deletion TsqlAstParser/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ static int Main(string[] args)

string sql = File.ReadAllText(sqlFile);

var parser = new TSql160Parser(initialQuotedIdentifiers: true);
// Use the newest SQL Server parser by default. Fabric DW-only syntax
// needs the Fabric DW parser, so pick it for tests named *FabricDW
// (matching the upstream SqlScriptDOM test layout).
TSqlParser parser = Path.GetFullPath(sqlFile).Contains("FabricDW")
? new TSqlFabricDWParser(initialQuotedIdentifiers: true)
: new TSql180Parser(initialQuotedIdentifiers: true);

using var reader = new StringReader(sql);
var fragment = parser.Parse(reader, out var errors);
Expand Down
2 changes: 1 addition & 1 deletion TsqlAstParser/TsqlAstParser.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SqlServer.TransactSql.ScriptDom" Version="170.128.0" />
<PackageReference Include="Microsoft.SqlServer.TransactSql.ScriptDom" Version="180.154.0" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion ast/declare_variable_statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func (d *DeclareVariableStatement) statement() {}
type DeclareVariableElement struct {
Fragment
VariableName *Identifier `json:"VariableName,omitempty"`
DataType *SqlDataTypeReference `json:"DataType,omitempty"`
DataType DataTypeReference `json:"DataType,omitempty"`
Value ScalarExpression `json:"Value,omitempty"`
Nullable *NullableConstraintDefinition `json:"Nullable,omitempty"`
}
Expand Down
4 changes: 4 additions & 0 deletions ast/order_by_clause.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ package ast
type OrderByClause struct {
Fragment
OrderByElements []*ExpressionWithSortOrder `json:"OrderByElements,omitempty"`
// All is true for the ORDER BY ALL shorthand; AllSortOrder is its
// ASC/DESC direction ("" means NotSpecified).
All bool `json:"All"`
AllSortOrder string `json:"AllSortOrder,omitempty"`
}

func (*OrderByClause) node() {}
2 changes: 2 additions & 0 deletions ast/query_specification.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ type OffsetClause struct {
Fragment
OffsetExpression ScalarExpression `json:"OffsetExpression,omitempty"`
FetchExpression ScalarExpression `json:"FetchExpression,omitempty"`
// WithApproximate is true for FETCH APPROXIMATE / FETCH APPROX.
WithApproximate bool `json:"WithApproximate"`
}

func (*OffsetClause) node() {}
3 changes: 3 additions & 0 deletions ast/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ package ast
type Script struct {
Fragment
Batches []*Batch `json:"Batches,omitempty"`
// TrailingGoCount is the number of GO batch separators that follow the
// last non-empty batch.
TrailingGoCount int `json:"TrailingGoCount"`
}

func (*Script) node() {}
2 changes: 2 additions & 0 deletions ast/top_row_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ type TopRowFilter struct {
Expression ScalarExpression `json:"Expression,omitempty"`
Percent bool `json:"Percent"`
WithTies bool `json:"WithTies"`
// WithApproximate is true for TOP (n) WITH APPROXIMATE / WITH APPROX.
WithApproximate bool `json:"WithApproximate"`
}

func (*TopRowFilter) node() {}
12 changes: 12 additions & 0 deletions ast/vector_data_type_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ast

// VectorDataTypeReference represents the VECTOR(dimension [, base_type]) data type.
type VectorDataTypeReference struct {
Fragment
Dimension *IntegerLiteral `json:"Dimension,omitempty"`
BaseType *Identifier `json:"BaseType,omitempty"`
Name *SchemaObjectName `json:"Name,omitempty"`
}

func (*VectorDataTypeReference) node() {}
func (*VectorDataTypeReference) dataTypeReference() {}
29 changes: 28 additions & 1 deletion parser/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func scriptToJSON(s *ast.Script) jsonNode {
}
node["Batches"] = batches
}
node["TrailingGoCount"] = s.TrailingGoCount
return addSpan(node, frag(s))
}

Expand Down Expand Up @@ -1913,6 +1914,7 @@ func offsetClauseToJSON(oc *ast.OffsetClause) jsonNode {
if oc.FetchExpression != nil {
node["FetchExpression"] = scalarExpressionToJSON(oc.FetchExpression)
}
node["WithApproximate"] = oc.WithApproximate
return addSpan(node, frag(oc))
}

Expand Down Expand Up @@ -1988,6 +1990,7 @@ func topRowFilterToJSON(t *ast.TopRowFilter) jsonNode {
}
node["Percent"] = t.Percent
node["WithTies"] = t.WithTies
node["WithApproximate"] = t.WithApproximate
return addSpan(node, frag(t))
}

Expand Down Expand Up @@ -4010,6 +4013,12 @@ func orderByClauseToJSON(obc *ast.OrderByClause) jsonNode {
}
node["OrderByElements"] = elems
}
node["All"] = obc.All
if obc.AllSortOrder != "" {
node["AllSortOrder"] = obc.AllSortOrder
} else {
node["AllSortOrder"] = "NotSpecified"
}
return addSpan(node, frag(obc))
}

Expand Down Expand Up @@ -4762,7 +4771,7 @@ func declareVariableElementToJSON(elem *ast.DeclareVariableElement) jsonNode {
node["VariableName"] = identifierToJSON(elem.VariableName)
}
if elem.DataType != nil {
node["DataType"] = sqlDataTypeReferenceToJSON(elem.DataType)
node["DataType"] = dataTypeReferenceToJSON(elem.DataType)
}
if elem.Nullable != nil {
node["Nullable"] = nullableConstraintToJSON(elem.Nullable)
Expand Down Expand Up @@ -10726,11 +10735,29 @@ func dataTypeReferenceToJSON(d ast.DataTypeReference) jsonNode {
return addSpan(xmlDataTypeReferenceToJSON(dt), frag(d))
case *ast.UserDataTypeReference:
return addSpan(userDataTypeReferenceToJSON(dt), frag(d))
case *ast.VectorDataTypeReference:
return addSpan(vectorDataTypeReferenceToJSON(dt), frag(d))
default:
return addSpan(jsonNode{"$type": "UnknownDataType"}, frag(d))
}
}

func vectorDataTypeReferenceToJSON(dt *ast.VectorDataTypeReference) jsonNode {
node := jsonNode{
"$type": "VectorDataTypeReference",
}
if dt.Dimension != nil {
node["Dimension"] = scalarExpressionToJSON(dt.Dimension)
}
if dt.BaseType != nil {
node["BaseType"] = identifierToJSON(dt.BaseType)
}
if dt.Name != nil {
node["Name"] = schemaObjectNameToJSON(dt.Name)
}
return addSpan(node, frag(dt))
}

func userDataTypeReferenceToJSON(dt *ast.UserDataTypeReference) jsonNode {
node := jsonNode{
"$type": "UserDataTypeReference",
Expand Down
37 changes: 36 additions & 1 deletion parser/parse_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -2537,6 +2537,10 @@ func (p *Parser) parseFunctionCallFromIdentifiers(identifiers []*ast.Identifier)
}
p.nextToken()

if fc.CallTarget == nil {
normalizeDatePartFunctionFirstParameter(fc)
}

// Span the call from its first identifier through the closing paren so
// wrappers built by parsePostExpressionAccess see the full extent.
if len(identifiers) > 0 {
Expand Down Expand Up @@ -3198,7 +3202,7 @@ func (p *Parser) parseSingleTableReference() (ast.TableReference, error) {
// Use GlobalFunctionTableReference for specific built-in global functions
if son.Count == 1 && son.BaseIdentifier != nil {
upper := strings.ToUpper(son.BaseIdentifier.Value)
if upper == "STRING_SPLIT" || upper == "GENERATE_SERIES" {
if upper == "STRING_SPLIT" || upper == "GENERATE_SERIES" || upper == "REGEXP_MATCHES" || upper == "REGEXP_SPLIT_TO_TABLE" {
return spanned(p, &ast.GlobalFunctionTableReference{
Name: son.BaseIdentifier,
Parameters: params,
Expand Down Expand Up @@ -9668,3 +9672,34 @@ func (p *Parser) parseOpenQueryTableReference() (*ast.OpenQueryTableReference, e

return spanned(p, result, astStart), nil
}

// normalizeDatePartFunctionFirstParameter mirrors ScriptDom's
// NormalizeDatePartFunctionFirstParameter: for built-in date functions whose
// first argument is a datepart keyword (DATEADD(day, ...), DATEPART(hour,
// ...), ...), a single-part column reference in that position becomes an
// IdentifierLiteral.
func normalizeDatePartFunctionFirstParameter(fc *ast.FunctionCall) {
if fc.FunctionName == nil || len(fc.Parameters) == 0 {
return
}
switch strings.ToUpper(fc.FunctionName.Value) {
case "DATEADD", "DATE_BUCKET", "DATEDIFF", "DATEDIFF_BIG", "DATENAME", "DATEPART", "DATETRUNC":
default:
return
}
col, ok := fc.Parameters[0].(*ast.ColumnReferenceExpression)
if !ok || col.MultiPartIdentifier == nil || len(col.MultiPartIdentifier.Identifiers) != 1 {
return
}
id := col.MultiPartIdentifier.Identifiers[0]
if id == nil {
return
}
lit := &ast.IdentifierLiteral{
LiteralType: "Identifier",
QuoteType: id.QuoteType,
Value: id.Value,
}
lit.Fragment = col.Fragment
fc.Parameters[0] = lit
}
28 changes: 26 additions & 2 deletions parser/parse_statements.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func (p *Parser) parseDeclareVariableStatement() (ast.Statement, error) {
}

// Parse data type
dataType, err := p.parseDataType()
dataType, err := p.parseDataTypeReference()
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -908,7 +908,7 @@ func (p *Parser) parseDeclareVariableElement() (*ast.DeclareVariableElement, err
}

// Parse data type
dataType, err := p.parseDataType()
dataType, err := p.parseDataTypeReference()
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -1041,6 +1041,30 @@ func (p *Parser) parseDataTypeReference() (ast.DataTypeReference, error) {
return spanned(p, xmlRef, astStart), nil
}

// VECTOR(dimension [, base_type]) - returns VectorDataTypeReference
if strings.ToUpper(typeName) == "VECTOR" && !isNational && p.curTok.Type == TokenLParen {
vecRef := &ast.VectorDataTypeReference{Name: baseName}
p.nextToken() // consume (
dim, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
lit, ok := dim.(*ast.IntegerLiteral)
if !ok {
return nil, fmt.Errorf("expected integer dimension for VECTOR type")
}
vecRef.Dimension = lit
if p.curTok.Type == TokenComma {
p.nextToken() // consume ,
vecRef.BaseType = p.parseIdentifier()
}
if p.curTok.Type != TokenRParen {
return nil, fmt.Errorf("expected ) after VECTOR parameters, got %s", p.curTok.Literal)
}
p.nextToken() // consume )
return spanned(p, vecRef, astStart), nil
}

// Check if this is a known SQL data type
sqlOption, isKnownType := getSqlDataTypeOption(typeName)

Expand Down
17 changes: 12 additions & 5 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,12 +364,16 @@ func (p *Parser) parseScript() (*ast.Script, error) {

// Parse all batches (separated by GO)
for p.curTok.Type != TokenEOF {
batch, err := p.parseBatch()
batch, sawGo, err := p.parseBatch()
if err != nil {
return nil, err
}
if batch != nil && len(batch.Statements) > 0 {
script.Batches = append(script.Batches, batch)
script.TrailingGoCount = 0
}
if sawGo {
script.TrailingGoCount++
}
}

Expand All @@ -380,19 +384,22 @@ func (p *Parser) parseScript() (*ast.Script, error) {
return script, nil
}

func (p *Parser) parseBatch() (*ast.Batch, error) {
batch := &ast.Batch{}
// parseBatch parses statements up to the next GO separator or EOF. sawGo
// reports whether the batch was terminated by a GO separator.
func (p *Parser) parseBatch() (batch *ast.Batch, sawGo bool, err error) {
batch = &ast.Batch{}

for p.curTok.Type != TokenEOF {
// Stop at GO statements (batch separators)
if p.curTok.Type == TokenIdent && strings.ToUpper(p.curTok.Literal) == "GO" {
p.nextToken()
sawGo = true
break
}

stmt, err := p.parseStatement()
if err != nil {
return nil, err
return nil, false, err
}
if stmt != nil {
batch.Statements = append(batch.Statements, stmt)
Expand All @@ -410,7 +417,7 @@ func (p *Parser) parseBatch() (*ast.Batch, error) {
}
}

return batch, nil
return batch, sawGo, nil
}

func (p *Parser) parseStatement() (ast.Statement, error) {
Expand Down
9 changes: 8 additions & 1 deletion parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,18 @@ func TestParse(t *testing.T) {
// Some golden files predate positional information and cannot be
// regenerated with TsqlAstParser (their SQL is rejected by the
// official parser). When the expected root node carries no
// StartOffset, compare without position fields.
// StartOffset, compare without position fields. These goldens
// also predate TSqlScript.TrailingGoCount (added in ScriptDom
// 180), so drop it from the root when the golden lacks it.
if root, ok := expectedObj.(map[string]any); ok {
if _, hasPos := root["StartOffset"]; !hasPos {
stripPositions(gotObj)
}
if _, hasGo := root["TrailingGoCount"]; !hasGo {
if got, ok := gotObj.(map[string]any); ok {
delete(got, "TrailingGoCount")
}
}
}

// Re-marshal for consistent formatting
Expand Down
3 changes: 2 additions & 1 deletion parser/testdata/AcceleratedDatabaseRecoveryTests150/ast.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,6 @@
}
]
}
]
],
"TrailingGoCount": 0
}
3 changes: 2 additions & 1 deletion parser/testdata/AddDropSignatureStatementTests/ast.json
Original file line number Diff line number Diff line change
Expand Up @@ -367,5 +367,6 @@
}
]
}
]
],
"TrailingGoCount": 0
}
Loading
Loading