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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gavel.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
commit:
allow:
- sqlglot/parser_gen.go
- harness/execute.py
47 changes: 47 additions & 0 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Documentation

on:
pull_request:
paths:
- 'docs/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'rspress.config.ts'
- 'tsconfig.json'
- '.github/workflows/docs.yml'
- 'Makefile'
push:
branches: [main]
paths:
- 'docs/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'rspress.config.ts'
- 'tsconfig.json'
- '.github/workflows/docs.yml'
- 'Makefile'

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
package_json_file: package.json
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: pnpm
cache-dependency-path: pnpm-lock.yaml
- run: pnpm install --frozen-lockfile
- run: make docs-check docs-build
- uses: actions/upload-artifact@v4
with:
name: documentation
path: doc_build
if-no-files-found: error
2 changes: 1 addition & 1 deletion cmd/sqlglot/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ func migrationInput(ctx context.Context, opts MigrationOptions, role pathRole) (
func migrateRun(ctx context.Context, opts MigrationOptions, mode string) (workflow.RunResult, error) {
return withHistory(func(store *history.Store) (workflow.RunResult, error) {
return operation.Run(ctx, operation.Options{Run: opts.Run, Parent: opts.Parent, Kind: history.KindMigration, Target: opts.DSN, Name: "Migration " + mode, Store: store}, func(ctx context.Context, record *history.Record, t *task.Task) (result workflow.RunResult, returnErr error) {
plan := workflow.Options{Source: opts.Source, Project: opts.project, Variables: opts.Variables, Routines: opts.Routines, AllowDrops: opts.AllowDrops}
plan := workflow.Options{Source: opts.Source, Project: opts.project, Labels: opts.Labels, Variables: opts.Variables, Routines: opts.Routines, AllowDrops: opts.AllowDrops}
filters, err := migrationLayerFilters(opts)
if err != nil {
return workflow.RunResult{}, err
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/go-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ The expression model exposes SQL constructs as nodes and named arguments. For th

`sqlglot.ParseScript(source, "tsql")` scans scripts and provides statement trees and diagnostics. Check the returned error, require `Complete`, and reject diagnostics or missing trees before relying on an analysis. `Complete` describes scan completion alone.

Native script analysis supports structured SQL Server routines and triggers. `ParseOne` retains the upstream reference's single-statement contract, which can represent some commands opaquely. Choose the entrypoint to match the analysis you need.
Native script analysis returns structured trees for SQL Server routines, triggers, and deployment syntax such as `CREATE TYPE ... AS TABLE` and `DELETE TOP`. Diagnostic offsets count Unicode code points in the source. `ParseOne` retains the upstream reference's single-statement contract, which can represent some commands opaquely.

## Formatting

Expand Down
2 changes: 1 addition & 1 deletion migrate/sqlserver/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ var _ = Describe("Fill factor, ROWGUIDCOL, QUOTED_IDENTIFIER and sequences", fun
})

Describe("a definition whose body is not understood", func() {
const header, body = "CREATE PROCEDURE dbo.acme_purge AS ", "DELETE TOP (500) a FROM dbo.acme a; RAISERROR(N'it''s %d', 0, 1, 2) WITH NOWAIT;"
const header, body = "CREATE PROCEDURE dbo.acme_purge AS ", "WAITFOR DELAY '00:00:01'; RAISERROR(N'it''s %d', 0, 1, 2) WITH NOWAIT;"
purge := func(sql string) migrate.Schema {
return definitions(migrate.Definition{Name: migrate.Name{Schema: "dbo", Name: "acme_purge"}, Kind: "PROCEDURE", SQL: sql})
}
Expand Down
13 changes: 11 additions & 2 deletions sqlglot/generate_nodes.go
Original file line number Diff line number Diff line change
Expand Up @@ -1227,8 +1227,9 @@ func (g *generator) writeLimitWord(e *Expression, word string) string {
// A NEGATIVE count is parenthesised here and is not by the reference,
// which writes `SELECT TOP -1 x` and then cannot read it back. That is the
// one place this writer does not follow it; see docs/upstream-issues.md.
deleteTop := e.Parent != nil && e.Parent.Class == "Delete"
if inner, _ := e.Args["expression"].(*Expression); inner != nil &&
word == "TOP " && !isPlainNumber(inner) {
word == "TOP " && (deleteTop || !isPlainNumber(inner)) {
count = "(" + count + ")"
}
out := word + count
Expand Down Expand Up @@ -5796,11 +5797,19 @@ func (g *generator) writeDelete(e *Expression) string {
}
}
order := g.child(e, "order")
limit := g.child(e, "limit")
verb := g.withPrefix(e, "DELETE")
if hint := g.child(e, "hint"); hint != "" {
verb += " " + hint
}
limit := ""
if top, _ := e.Args["limit"].(*Expression); e.Args["top"] == true && top != nil {
if g.dialect != "tsql" {
return g.fail("DELETE TOP outside T-SQL")
}
verb += " " + g.writeLimitWord(top, "TOP ")
} else {
limit = g.child(e, "limit")
}
verb += tablesWord
if g.tables.ReturningEnd {
return clauses(verb, body, cluster, where, returning, order, limit)
Expand Down
12 changes: 5 additions & 7 deletions sqlglot/parse_ddl.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (p *parser) parseCreate() (*Expression, error) {
// UNIQUE is a flag on the node rather than a property, and only an INDEX
// takes it.
unique := false
if p.atWords("UNIQUE") && p.next() != nil && strings.EqualFold(p.next().Text, "INDEX") {
if p.atWords("UNIQUE") && p.next() != nil && p.next().Type == TokINDEX {
p.advance()
unique = true
}
Expand Down Expand Up @@ -1172,26 +1172,24 @@ func (p *parser) parseDrop() (*Expression, error) {
exists = true
}

// A TABLE or a VIEW may name several at once; everything else names one.
routine := kind == "FUNCTION" || kind == "PROCEDURE" || kind == "PROC"
multipleNames := kind == "TABLE" || kind == "VIEW" || (p.dialect == "tsql" && p.nativeTSQLModules && routine)
var tables []*Expression
for {
table, err := p.parseDroppedName(written)
if err != nil {
return nil, err
}
tables = append(tables, table)
if kind != "TABLE" && kind != "VIEW" {
break
}
if !p.match(TokCOMMA) {
if !multipleNames || !p.match(TokCOMMA) {
break
}
}

// A FUNCTION or a PROCEDURE may be named with its SIGNATURE, because a
// name alone need not say which of them is meant.
var signature []*Expression
if p.at(TokL_PAREN) && (kind == "FUNCTION" || kind == "PROCEDURE") {
if p.at(TokL_PAREN) && len(tables) == 1 && (kind == "FUNCTION" || kind == "PROCEDURE") {
p.advance()
for !p.at(TokR_PAREN) {
dt, err := p.parseDataType()
Expand Down
32 changes: 32 additions & 0 deletions sqlglot/parse_dml.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,13 @@ func (p *parser) parseDelete() (*Expression, error) {
if err != nil {
return nil, err
}
var top *Expression
if p.dialect == "tsql" && p.nativeTSQLModules && p.match(TokTOP) {
top, err = p.parseDeleteTop()
if err != nil {
return nil, err
}
}

// MySQL's Multiple-Table DELETE names, before the FROM, which of the
// tables joined there actually lose rows: `DELETE x, y FROM x JOIN y
Expand Down Expand Up @@ -354,6 +361,9 @@ func (p *parser) parseDelete() (*Expression, error) {
node.Set("order", New("Order", Arg{"expressions", ordered}))
}
if p.at(TokLIMIT) {
if top != nil {
return nil, p.unsupported("DELETE with both TOP and LIMIT")
}
p.advance()
count, err := p.parseLimitCount()
if err != nil {
Expand All @@ -362,12 +372,34 @@ func (p *parser) parseDelete() (*Expression, error) {
node.Set("limit", New("Limit", Arg{"this", nil}, Arg{"expression", count},
Arg{"limit_options", p.parseLimitOptions()}, Arg{"expressions", nil}))
}
if top != nil {
node.Set("limit", top)
node.Set("top", true)
}
if !p.atStatementEnd() {
return nil, p.unsupported("DELETE with more than this port reads")
}
return node, nil
}

func (p *parser) parseDeleteTop() (*Expression, error) {
if !p.at(TokL_PAREN) {
return nil, p.unsupported("DELETE TOP without a parenthesized count")
}
count, err := p.parseTopCount()
if err != nil {
return nil, err
}
var options *Expression
if p.match(TokPERCENT) {
options = New("LimitOptions", Arg{"percent", true}, Arg{"rows", false}, Arg{"with_ties", false})
}
if p.atWords("WITH", "TIES") {
return nil, p.unsupported("DELETE TOP WITH TIES")
}
return newTopLimit(count, options), nil
}

// parseMerge reads `MERGE [INTO] <target> USING <source> ON <cond> WHEN ...`.
// INTO is optional, as T-SQL and the reference have it; it is always written.
//
Expand Down
13 changes: 7 additions & 6 deletions sqlglot/parse_script.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import (
)

type ParseDiagnostic struct {
Kind string `json:"kind"`
Label string `json:"label"`
StatementKind string `json:"statement_kind"`
Start int `json:"start"`
End int `json:"end"`
StatementStart int `json:"statement_start"`
Kind string `json:"kind"`
Label string `json:"label"`
StatementKind string `json:"statement_kind"`
// Start, End, and StatementStart are rune offsets in the source.
Start int `json:"start"`
End int `json:"end"`
StatementStart int `json:"statement_start"`
}

type ScriptResult struct {
Expand Down
26 changes: 16 additions & 10 deletions sqlglot/parse_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,14 @@ func (p *parser) parseTop() (*Expression, error) {
if !p.match(TokTOP) {
return nil, nil
}
var count *Expression
count, err := p.parseTopCount()
if err != nil {
return nil, err
}
return newTopLimit(count, p.parseLimitOptions()), nil
}

func (p *parser) parseTopCount() (*Expression, error) {
switch {
// `TOP (expr)` is how T-SQL spells a count that is not a plain number, and
// the reference stores the expression UNWRAPPED -- `SELECT TOP (A) 0` and
Expand All @@ -917,25 +924,24 @@ func (p *parser) parseTop() (*Expression, error) {
if !p.match(TokR_PAREN) {
return nil, p.unsupported("unclosed TOP count")
}
count = inner
return inner, nil
case p.curr() != nil && p.curr().Type == TokNUMBER:
count = New("Literal", Arg{"this", p.curr().Text}, Arg{"is_string", false})
count := New("Literal", Arg{"this", p.curr().Text}, Arg{"is_string", false})
p.advance()
return count, nil
default:
return nil, p.unsupported("TOP without a count")
}
limit := New("Limit",
}

func newTopLimit(count, options *Expression) *Expression {
return New("Limit",
Arg{"this", nil},
Arg{"expression", count},
Arg{"offset", nil},
Arg{"limit_options", nil},
Arg{"limit_options", options},
Arg{"expressions", nil},
)
// The same words a LIMIT takes after its count, in the same order.
if options := p.parseLimitOptions(); options != nil {
limit.Set("limit_options", options)
}
return limit, nil
}

func (p *parser) parseProjections() ([]*Expression, error) {
Expand Down
60 changes: 60 additions & 0 deletions sqlglot/parse_tsql_deployment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package sqlglot

import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("T-SQL deployment syntax", func() {
DescribeTable("parses and generates typed deployment statements",
func(sql, class, generatedFragment string) {
result, err := ParseScript(sql, "tsql")
Expect(err).NotTo(HaveOccurred())
Expect(result.Diagnostics).To(BeEmpty())
Expect(result.Complete).To(BeTrue())
Expect(result.Tree).To(HaveField("Class", class))

generated, err := Generate(result.Tree, "tsql")
Expect(err).NotTo(HaveOccurred())
Expect(generated).To(ContainSubstring(generatedFragment))
reparsed, err := ParseScript(generated, "tsql")
Expect(err).NotTo(HaveOccurred())
Expect(reparsed.Diagnostics).To(BeEmpty())
Expect(reparsed.Tree.Dump()).To(Equal(result.Tree.Dump()))
},
Entry("an index followed by another statement",
"CREATE NONCLUSTERED INDEX IX_Audit ON dbo.AuditRows (Id); SELECT 1;",
"Block", "CREATE NONCLUSTERED INDEX"),
Entry("a unique clustered index",
"CREATE UNIQUE CLUSTERED INDEX IX_Audit ON #audit (Id);",
"Create", "CREATE UNIQUE CLUSTERED INDEX"),
Entry("an ALTER ADD column under IF",
"IF 1 = 1 ALTER TABLE dbo.AuditRows ADD Ordinal VARCHAR(2) NULL; SELECT 1;",
"Block", "ADD Ordinal VARCHAR(2) NULL"),
Entry("a table type under IF",
"IF TYPE_ID(N'dbo.AuditRows') IS NULL CREATE TYPE dbo.AuditRows AS TABLE (Id INT NOT NULL PRIMARY KEY);",
"IfBlock", "AS TABLE (Id INTEGER NOT NULL PRIMARY KEY)"),
Entry("batch RAISERROR options",
"RAISERROR(N'audit', 0, 1) WITH NOWAIT, SETERROR; SELECT 1;",
"Block", "WITH NOWAIT, SETERROR"),
Entry("DELETE TOP on an aliased joined table",
"DELETE TOP (500) a FROM dbo.AuditKeys k INNER LOOP JOIN dbo.AuditRows a ON a.Id = k.Id;",
"Delete", "DELETE TOP (500) a FROM"),
Entry("DELETE TOP with PERCENT and no target alias",
"DELETE TOP (10) PERCENT FROM dbo.AuditRows;",
"Delete", "DELETE TOP (10) PERCENT FROM"),
Entry("comma-separated procedure names",
"DROP PROCEDURE IF EXISTS dbo.RunAudit, dbo.StageAudit;",
"Drop", "DROP PROCEDURE IF EXISTS dbo.RunAudit, dbo.StageAudit"),
Entry("comma-separated function names",
"DROP FUNCTION IF EXISTS dbo.ReadAudit, dbo.FindAudit;",
"Drop", "DROP FUNCTION IF EXISTS dbo.ReadAudit, dbo.FindAudit"),
)

It("rejects TOP WITH TIES in DELETE", func() {
result, err := ParseScript("DELETE TOP (10) WITH TIES FROM dbo.AuditRows;", "tsql")
Expect(err).NotTo(HaveOccurred())
Expect(result.Tree).To(BeNil())
Expect(result.Diagnostics).To(ContainElement(HaveField("Label", ContainSubstring("WITH TIES"))))
})
})
3 changes: 3 additions & 0 deletions sqlglot/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,9 @@ func (p *parser) parseStatementBody() (*Expression, error) {
if p.dialect == "tsql" && p.atWords("PRINT") {
return p.parseTSQLPrint()
}
if p.dialect == "tsql" && p.nativeTSQLModules && p.atWords("RAISERROR") {
return p.parseTSQLRaiserror()
}
if p.atEventSession() {
return p.parseEventSession()
}
Expand Down
Loading