diff --git a/.gavel.yaml b/.gavel.yaml index 76f79691..06875ee0 100644 --- a/.gavel.yaml +++ b/.gavel.yaml @@ -1,3 +1,4 @@ commit: allow: - sqlglot/parser_gen.go + - harness/execute.py diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..52c7c76d --- /dev/null +++ b/.github/workflows/docs.yml @@ -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 diff --git a/cmd/sqlglot/migrate.go b/cmd/sqlglot/migrate.go index e9db16b4..b4c87252 100644 --- a/cmd/sqlglot/migrate.go +++ b/cmd/sqlglot/migrate.go @@ -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 diff --git a/docs/guide/go-api.md b/docs/guide/go-api.md index cfa71d92..625b7fff 100644 --- a/docs/guide/go-api.md +++ b/docs/guide/go-api.md @@ -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 diff --git a/migrate/sqlserver/storage_test.go b/migrate/sqlserver/storage_test.go index 89fe6ccb..7b748783 100644 --- a/migrate/sqlserver/storage_test.go +++ b/migrate/sqlserver/storage_test.go @@ -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}) } diff --git a/sqlglot/generate_nodes.go b/sqlglot/generate_nodes.go index 52e03903..1f668af3 100644 --- a/sqlglot/generate_nodes.go +++ b/sqlglot/generate_nodes.go @@ -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 @@ -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) diff --git a/sqlglot/parse_ddl.go b/sqlglot/parse_ddl.go index 75b984b1..c7a2c45a 100644 --- a/sqlglot/parse_ddl.go +++ b/sqlglot/parse_ddl.go @@ -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 } @@ -1172,7 +1172,8 @@ 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) @@ -1180,10 +1181,7 @@ func (p *parser) parseDrop() (*Expression, error) { return nil, err } tables = append(tables, table) - if kind != "TABLE" && kind != "VIEW" { - break - } - if !p.match(TokCOMMA) { + if !multipleNames || !p.match(TokCOMMA) { break } } @@ -1191,7 +1189,7 @@ func (p *parser) parseDrop() (*Expression, error) { // 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() diff --git a/sqlglot/parse_dml.go b/sqlglot/parse_dml.go index 73c128f4..dd53215c 100644 --- a/sqlglot/parse_dml.go +++ b/sqlglot/parse_dml.go @@ -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 @@ -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 { @@ -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] USING ON WHEN ...`. // INTO is optional, as T-SQL and the reference have it; it is always written. // diff --git a/sqlglot/parse_script.go b/sqlglot/parse_script.go index 02425533..706694cb 100644 --- a/sqlglot/parse_script.go +++ b/sqlglot/parse_script.go @@ -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 { diff --git a/sqlglot/parse_select.go b/sqlglot/parse_select.go index 14ec3bef..3843c821 100644 --- a/sqlglot/parse_select.go +++ b/sqlglot/parse_select.go @@ -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 @@ -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) { diff --git a/sqlglot/parse_tsql_deployment_test.go b/sqlglot/parse_tsql_deployment_test.go new file mode 100644 index 00000000..1b44cd11 --- /dev/null +++ b/sqlglot/parse_tsql_deployment_test.go @@ -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")))) + }) +}) diff --git a/sqlglot/parser.go b/sqlglot/parser.go index 4da76fe9..6304609b 100644 --- a/sqlglot/parser.go +++ b/sqlglot/parser.go @@ -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() }