DotGram.Sql
0.3.0
dotnet add package DotGram.Sql --version 0.3.0
NuGet\Install-Package DotGram.Sql -Version 0.3.0
<PackageReference Include="DotGram.Sql" Version="0.3.0" />
<PackageVersion Include="DotGram.Sql" Version="0.3.0" />
<PackageReference Include="DotGram.Sql" />
paket add DotGram.Sql --version 0.3.0
#r "nuget: DotGram.Sql, 0.3.0"
#:package DotGram.Sql@0.3.0
#addin nuget:?package=DotGram.Sql&version=0.3.0
#tool nuget:?package=DotGram.Sql&version=0.3.0
DotGram.Sql
SQL parsers written in .gram, and the trees of records they build. Where an
example shows one feature, a parser here is written against a whole specification.
They are ordinary C# libraries. .Gram generates the parsers into this assembly at compile time, so nothing here carries a parser runtime, and neither does anything that references it.
The dialects
Each dialect is a directory, a namespace and a grammar of its own, and all of them build one tree, the
standard's own, in DotGram.Sql.Ast: the records, and SqlWriter and TransactSqlWriter, which print them back;
SqlWalker, in DotGram.Sql, visits them. What each parser publishes is
under the table.
| Parser | Namespace | What it reads |
|---|---|---|
SqlStandardParser |
DotGram.Sql.Standard |
ISO SQL:2023, in part: its lexical elements, names, scalar expressions, aggregates and window functions, the JSON functions, query expressions with row pattern recognition, predicates, the data change statements, the whole schema — tables, views, domains, sequences, privileges, routines, triggers, user-defined types, casts, orderings, transforms, character sets and collations — and the transaction, session, connection, diagnostics, dynamic and direct statements |
Sql92Parser |
DotGram.Sql.Standard |
SQL-92 as the standard writes it |
TransactSqlParser |
DotGram.Sql.TransactSql |
SQL Server's T-SQL, as the engine reads it |
Each grammar stands alone: TransactSqlParser includes no other grammar, and the rules it has in the
shape of the standard's (a search condition, a row value constructor, a case expression) are written
out in TransactSql.gram beside T-SQL's own.
All three build one tree, the standard's, laid out in
SqlAst.cs in DotGram.Sql.Ast, with T-SQL's own
constructs in the standard's families and beside them, and printed back by
SqlWriter, or by TransactSqlWriter as T-SQL
reads it. Its records are named for the standard's constructs. The writers print key words and date
parts in capitals, whatever case they were read in: the tree holds what a key word means, not how it
was spelled. A text two parsers read is the same tree, in the shape
SqlStandardParser gives it. Sql92Parser's ParseSelect gives an Ast.Statement, ParseQuery an Ast.Query, and
ParseSearchCondition and ParseValueExpression an Ast.Expression.
SqlStandardParser reads at six levels: ParseValue (the standard's literal, a signed number among
them, or NULL), ParseDataType, ParseExpression, ParseSearchCondition, ParseStatement (one
statement of any kind, its ; optional; a query is the Statement.Select among them, holding an
Ast.Query) and ParseSql
(statements, each ended by a ; or by the end of the text, where an empty statement is refused).
A production below them is read through the level that holds it, and a statement's kind is the type
of its node. TransactSqlParser reads at four of them, with the same names and the same tree:
ParseExpression, ParseSearchCondition, ParseStatement and ParseSql, with the per-version
entries; and besides them ParseSelect, a query statement and nothing else, which refuses any
other statement where it begins, and ParseScript. ParseValue and ParseDataType can be added
to T-SQL later. Each has two kinds of TryParse…: one giving a Match<T> with the refusal's
message and position, and a bool TryParse…(string input, out T value) for where only the answer
is wanted; most entries have both from a position and over a window as well.
All three read through a lexical split (Lexical = true): a lexical half makes tokens, and the
syntactic half above it decides each choice by the token in front of it, which is what a parser
written by hand does. SqlStandardParser reads one thing less than the standard does because of
it: a comment holds others at any depth, but a /* inside a comment always opens one.
using DotGram.Sql.Ast;
using DotGram.Sql.TransactSql;
var match = TransactSqlParser.TryParseSelect("select name from Users where id > @id");
var select = (Statement.Select)match.Value;
var query = (Query.Select)select.Query;
var from = (TableSource.Named)query.From!.Sources[0]; // from.Name.Last.Text is "Users"
A database's compatibility level gates a small part of what SQL Server reads — the WINDOW
clause from 160, OPENJSON's schema from 130. TransactSqlParser.ParseStatement130 reads what
the engine reads at level 130, and so on from 100 to 170; ParseStatement names no level and
reads them all. The levels are one grammar and one machine, told apart by a number, and what each
gates is held against SQL Server.
TransactSqlParser.ParseStatement reads one statement. TransactSqlParser.ParseSql reads a text
of them — what a client sends the server in one call — and gives back a Statement[]: each ended
by a ; or by nothing, except before a WITH, which needs the statement before it ended, as the
server does. ParseSql100 to ParseSql170 are its levels.
Scripts
GO is not T-SQL: it is the line a client tool cuts a script at, and the server never sees it.
Nor are sqlcmd's :setvar, :r and $(name). So which method to call is a question of where the
text came from: text from a file or an editor is a script — read it with ParseScript or
SqlScript.Read; text a program sends the server in one command is not — read it with
ParseSql. Read in one call, SELECT 1 and then a line GO is a column called GO, because that
is what the server makes of it, and ParseSql does not guess otherwise.
TransactSqlParser.ParseScript cuts a script into batches as sqlcmd cuts it and reads each batch as
the one call it is, giving back a Batch[] (DotGram.Sql.Ast): each with its statements, the GO line that ended it
(GO 5, a batch sent five times, too) and its Source, the batch as it was cut. The variables the
script sets with :setvar are substituted, a :r is refused — there is no file to read — and every
other command is the tool's and is passed over. ParseScript100 to ParseScript170 are its levels.
The cutting is SqlScript.Read, in DotGram.Sql and no dialect's: the batches a tool would send, the
commands it would act on, and what it would have said. It is held byte for byte to what sqlcmd
sends, and it runs nothing and reads no file itself — an include is a callback.
using System;
using System.Collections.Generic;
using System.IO;
using DotGram.Sql;
using DotGram.Sql.TransactSql;
var text = "CREATE TABLE $(db).dbo.t (a int)\nGO\nSELECT FROM t\n";
var script = SqlScript.Read(text, new ScriptOptions
{
Profile = ScriptProfile.SqlCmd(), // or ScriptProfile.Ssms(): GO lines only
Variables = new Dictionary<string, string> { ["db"] = "Sales" }, // sqlcmd's -v
ResolveInclude = include => File.Exists(include.Path) ? new ScriptSource(include.Path, File.ReadAllText(include.Path)) : null,
SourceName = "deploy.sql",
});
foreach (var batch in script.Batches)
{
var match = TransactSqlParser.Located.TryParseSql150(batch);
if (!match.IsSuccess)
{
var where = batch.Locate((int)match.Position, 0);
Console.WriteLine($"{where.Source}({where.Span.At}): {match.Error}"); // deploy.sql(43): …
}
}
A batch written as one run of the script with nothing substituted is a window of the very string
given, so every position a reading reports is already a position in the script; in a batch where a
variable was substituted, batch.Locate takes it back to where it was written. script.Directives
lists the commands, none of them run, and script.Diagnostics what sqlcmd would have said — an
undefined variable, a file it could not include, a line it would stop at. And for text whose origin
is not known, script.HasClientSyntax says whether anything in it was the tool's: a script of one
batch ended by GO counts, which is why the question is not how many batches there are.
Where a statement was written is there for whoever asks for it. TransactSqlParser.Located is the
same parser called with locations on — TransactSqlParser.Located.TryParseStatement — and a
statement it builds carries in Span the range of text it was read from, a position in the input
handed in, and so do the queries, expressions and table sources in it. The two are one parser:
TransactSqlParser keeps no positions and offers none, and pays a test per value it reads for
sharing its reader. A span takes no part in a node's equality: the located tree of a text equals
the plain one.
A tree compares by what was written. The lists a node holds are SqlList<T>, which compare
element by element, so two readings of the same text are equal and hash alike, and a table of
nodes that should tell two equal subtrees apart is keyed by reference. A list is made with a
collection expression, [a, b] or [.. items], or with SqlList.From(items).
The tree they build is laid out in SqlAst.cs and the files
beside it, each record with the production of the standard or the page of Microsoft's reference it comes from.
What they read is held against SQL Server itself, against a corpus of somebody else's SQL and
against a round trip — parse, print, and compare the two readings — which catches a parser that
answers yes and builds the wrong thing.
All three of these parsers may be called from any number of threads at once; that is the
generated parser's own contract, not something this package adds
(DotGram's README).
Taking one
<PackageReference Include="DotGram.Sql" Version="0.3.0" />
There is no companion runtime package, and no generator to install alongside it: the parsers were generated when this assembly was compiled.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- System.Memory (>= 4.6.3)
-
net10.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Since 0.2.0. The three parsers build one tree: TransactSqlParser and Sql92Parser now build DotGram.Sql.Ast, the tree SqlStandardParser builds, and the T-SQL tree of 0.2.0 is gone. A script is cut into batches as sqlcmd cuts it, and every parser is carried immediately. docs/ast.md maps every node to the production or page it comes from.
BREAKING CHANGES, and what to write instead
- One tree. TransactSqlParser and Sql92Parser hand back DotGram.Sql.Ast nodes through every entry, plain and Located: a Statement, a Statement[], an Expression or a Query of DotGram.Sql.Ast. A text two parsers read is the same tree. The 0.2.0 T-SQL tree in the DotGram.Sql namespace is removed: Statement, SetExpression, Query, Expression, TableReference, Clause, their records and factories, SqlComparison and SqlTruth; SqlJoin, SqlOrder, SqlLiteralKind and SetCategory are no longer public. Migration: use the types of DotGram.Sql.Ast; walk with SqlWalker; write with SqlWriter or TransactSqlWriter. A T-SQL construct with no node of its own yet comes back as an Extension node (Dialect "T-SQL", and a Kind that names it), which the writers refuse.
- The DotGram.Sql.Ast tree of 0.2.0 changes shape. A SELECT holds a Query (Statement.Select.Query, beside its Hints), which a subquery, a derived table, a CTE, a view and an INSERT source hold as well (InSource.Query and InsertSource.Query are gone). SelectItem is SelectColumn, OFFSET and FETCH are one Limit (OffsetClause, FetchClause and FetchMode are gone), QueryOperand is gone, and set operations are a list on the query. DROP is a record per kind: Statement.DropObject and DropObjectKind are replaced by 46 records, and DropFulltextIndex is DropFullTextIndex. The session SET options are reshaped (eleven SetOption cases are gone), and Ast.SetCategory and JsonApiCommon.PathSpecification are removed. Migration: docs/ast.md says which node a construct now builds.
- Writers. Sql2023Writer is renamed SqlWriter, in DotGram.Sql.Ast; the old SqlWriter of the DotGram.Sql namespace, which wrote only the removed tree, is gone. Migration: DotGram.Sql.Ast.Sql2023Writer.Write -> DotGram.Sql.Ast.SqlWriter.Write. The writers print key words and date parts in capitals.
- Batch moves from DotGram.Sql to DotGram.Sql.Ast, with Statements, Go and Source. Migration: change the using.
- Entries. SqlStandardParser reads by level, six entries where it published forty-two productions: ParseValue (was ParseLiteral; also reads NULL), ParseDataType, ParseExpression (was ParseValueExpression), ParseSearchCondition, ParseStatement (replaces ParseDirectSQLStatement, ParseSQLProcedureStatement and ParseQueryExpression) and ParseSql; 258 public methods are removed besides the two renamed. TransactSqlParser reads ParseExpression (was ParseValueExpression), ParseSearchCondition, ParseStatement, ParseSql, ParseScript and ParseSelect, each with its Try forms; ParseStatement, ParseSql and ParseScript also have a form per compatibility level from 100 to 170 (ParseStatement130, TryParseSql130, ParseScript160, …), with Try forms of their own. ParseQuery is gone. Migration: read a production below a level through the level that holds it (a table reference as a query that names it, a predicate as a search condition); for a T-SQL query take the statement's Query, ((Statement.Select)TransactSqlParser.ParseSelect(text)).Query.
- Lists. Every list a node holds is a SqlList<T>, a read-only struct over one array that compares element by element: 183 IReadOnlyList<T> members of DotGram.Sql.Ast. Reading code mostly compiles unchanged (foreach, an indexer, Length, Count, LINQ, list patterns). Migration: where a list is handed in, write [.. array] or SqlList.From(array); use the list's own Exists and TrueForAll, or AsSpan, in place of Array.Exists and the other T[] methods; a SqlList<Derived> is not a SqlList<Base>.
- Equality by content. A node's Span takes no part in its equality: a located tree equals the plain tree of the same text, and two equal subtrees in different places compare equal. Migration: a table keyed by node is keyed by reference (ReferenceEqualityComparer on .NET 5 and later, or a comparer of your own). Hash values differ from 0.2.0.
- QualifiedName is a struct, its first Identifier and an array of the others: an optional name is a QualifiedName?, a Nullable, whose value is x.Value; the positional Parts and its Deconstruct are gone (Parts is kept and makes a list on each call; Count, the indexer, First, Last and foreach read without allocating). default(QualifiedName) is no name, and the writers and SqlWalker refuse it.
- LiteralValue is an Expression, and Expression.Literal is removed. Migration: Expression.Literal { Value: LiteralValue.Numeric n } -> LiteralValue.Numeric n; new Expression.Literal(v) -> v.
- Scripts. ParseScript, TryParseScript and their levels cut a script as ODBC sqlcmd 18.6 cuts it, so they answer differently wherever 0.2.0 disagreed with sqlcmd: GO; is text, a GO after a statement on its line is text, GO /* c */, GO 2; and GO x are refused at that line, :setvar is read and substituted, :r is refused. The four position and window forms of TryParseScript are removed at every level, 72 methods. Migration: cut the text with SqlScript.Read and read each batch with TryParseSql(ScriptBatch). ParseSql no longer refuses a GO line: in one command GO is a word, as the server reads it. Text from a file or an editor is a script, for ParseScript; text a program sends in one command is for ParseSql.
- Sql92Parser reserves every word SQL-92 reserves (section 5.2), so year, month, zone, with, names and the like are refused as names - write them delimited ("year"); SELECT b DAY FROM t reads b qualified by DAY. It refuses an interval qualifier SQL-92 does not have and a length, precision or scale above 2,147,483,647.
- Derivation. The concrete records of DotGram.Sql.Ast are sealed. The abstract records their families derive from (Statement, Expression, LiteralValue, Query, DataType and the rest) are not sealed: their parameterless constructor is private protected, so a type outside the package cannot derive through it, but the copy constructor C# requires of a record that is not sealed stays protected, and a record that calls it can still derive. No family is designed for that. Sql92Parser, SqlStandardParser and TransactSqlParser have no constructor outside the package. Migration: hold a node or call a parser rather than derive from it.
- Syntax, the helpers the T-SQL grammar's rules call, is no longer public, nor are the rule-value helper types nested in the parsers (the …_Dialect types of TransactSqlParser and TransactSqlParser.Located, CreateStatisticsWith, UpdateStatisticsWith, DottedType, Sql92Parser.Reserved, TransactSqlParser.ParserInput<T>).
- QualifiedName.Of is no longer public, and EndpointEncryptionLevel, EndpointAlgorithm and EndpointWindowsMode, which no node held, are removed. Migration: new QualifiedName(first, rest) or new QualifiedName([.. parts]).
- TransactSqlParser.SourceSpan is no longer public; nothing public took or returned it.
- Scan, the scanner of the lexer of Sql92Parser, SqlStandardParser and TransactSqlParser, is no longer public: the kind it gave was the grammar's own numbering of its tokens, which changed with the grammar. Migration: none in the package; a caller that cut text into tokens with it has no replacement.
- In a located T-SQL reading, an OVER spans the keyword and the window's name or brackets, as a located reading of SQL:2023 spans it.
NEW
- SqlScript.Read(text, options) cuts a script into the batches a client tool sends: ScriptProfile.SqlCmd() reads separator lines, GO n, :setvar and , :r through ScriptOptions.ResolveInclude (bounded by ScriptOptions.MaximumIncludes) and reports every other command as a ScriptDirective; ScriptProfile.Ssms() reads separator lines alone. Each ScriptBatch has Count, IsVerbatim and Locate. TransactSqlParser.TryParseSql(ScriptBatch) and its forms read one batch. Held byte for byte to what sqlcmd 18.6 sends the server.
- SqlList<T>, the list every node holds, made with a collection expression, SqlList.From or ToSqlList(). A list of one element of a reference type holds it without an array.
- TransactSqlParser.Located is the same parser called with locations on, rather than a second compilation, so the assembly carries one T-SQL parser instead of two.
CHANGED
- All three parsers are carried immediately (Carrier = GramCarrier.Immediate): a node is built as its rule is read. Accepted readings are mostly faster (FASTER, below); a text refused part-way allocates more. Trees, refusals and messages are as before.
- A node of DotGram.Sql.Ast keeps its location in eight bytes (start and length); its Span.GapStart is its At.
- A located node's span is the range of the rule that built it; a clause's keyword is no longer inside the value it introduces (a WHERE condition spans its own text).
- Equality and GetHashCode of a node throw InsufficientExecutionStackException on a tree deeper than the stack has room for, where they would have overflowed it.
FASTER
- Against 0.2.0 on the release benchmark. SqlStandardParser (SQL:2023) parses about 80% faster, with less than a third of the bytes.
- Sql92Parser parses about 29% faster and allocates about 1.6 times the bytes; a refused text costs more, up to 96% slower, with up to 108 times the 208 bytes it took.
- TransactSqlParser is 22% faster at the median, and a script of 400 statements 30% faster, but an UPDATE with a subquery is 6 to 9% slower. Accepted T-SQL allocates up to 2.2 times the bytes (1.6 times at the median), the cost of the one tree's records; a first call takes about 6% longer.
- DotGram.Sql.dll carries 63% less IL (9.2 MB to 3.4 MB).
FIXED
- Ten thousand nested T-SQL CASE … ELSE CASE … ended the process with a stack overflow; they are read. The writers carry a deep walk onto a thread of their own, and the T-SQL checks of a chain of UNION, brackets and PIVOT loop rather than recurse.
- SqlStandardParser refuses a length, precision, scale or cardinality beyond 2147483647 and a large object length beyond 9223372036854775807, where it read CHAR (4294967297) as 1 and threw OverflowException on a number beyond long.
- SqlStandardParser no longer reads a string literal through a simple comment: 'a' --c 'b' is the literal 'a' and a comment.
- TransactSqlParser refuses EXTRACT(f FROM x), POSITION(a IN b), SUBSTRING(x FROM a FOR b), CONVERT(x USING cs), TRANSLATE(x USING cs), CURRENT_TIME, CURRENT_TIME(n) and CURRENT_TIMESTAMP(n), which it read from SQL-92's rules and SQL Server 2025 refuses at every compatibility level. CURRENT_DATE and plain CURRENT_TIMESTAMP stay, and so do the ODBC escapes { fn EXTRACT (HOUR FROM d) } and { fn CURRENT_TIME }.
- A nest of T-SQL UPPER, LOWER, the four lengths, TRIM, CHOOSE or a set function (AVG, COUNT, MAX, MIN, SUM) took time doubling with every level, tripling for TRIM: 20 unclosed levels of UPPER ( took most of a second, and closed, accepted nests of TRIM ( and CHOOSE ( and of calls such as SUM (x, 1) did the same; so did SQL-92's TRIM (TRIM (a)). They are read in time proportional to the depth, and every tree, span and message is what it was.
- A chain of UNION, EXCEPT or INTERSECT, accepted or refused, allocates in proportion to its length in Sql92Parser and TransactSqlParser, where the operation list was copied at every operator (17 KB a branch at 2,048 branches, 2.1 GB at 16,384); Query.Combine appends without copying too. Trees, refusals and messages are as before.
- TransactSqlParser refuses TRIM (LEADING), TRIM (LEADING + 1) and every trim specification with no FROM after it, from level 160, as SQL Server does (Msg 102); it read them as a call over a column named LEADING.
KNOWN ISSUES
- Most DotGram.Sql.Ast records have no XML summary yet. The entry points have one (Batch; Statement with Select, Insert, Update, Delete, Merge and CreateTable; Query with Select; TableSource with Named, Subquery and Join; Expression with Reference, Unary and Binary), and most of the others that have one name the Microsoft reference page or the BNF production they follow. The tree's members carry no XML documentation beyond that yet; docs/ast.md is the reference, and the documentation comes in a later release.