OracleSqlParser 1.0.0-rc.2

This is a prerelease version of OracleSqlParser.
There is a newer version of this package available.
See the version list below for details.
dotnet add package OracleSqlParser --version 1.0.0-rc.2
                    
NuGet\Install-Package OracleSqlParser -Version 1.0.0-rc.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OracleSqlParser" Version="1.0.0-rc.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OracleSqlParser" Version="1.0.0-rc.2" />
                    
Directory.Packages.props
<PackageReference Include="OracleSqlParser" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OracleSqlParser --version 1.0.0-rc.2
                    
#r "nuget: OracleSqlParser, 1.0.0-rc.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OracleSqlParser@1.0.0-rc.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OracleSqlParser&version=1.0.0-rc.2&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=OracleSqlParser&version=1.0.0-rc.2&prerelease
                    
Install as a Cake Tool

OracleSqlParser

A lexer and recursive-descent parser for Oracle SQL that builds an abstract syntax tree (similar in spirit to Microsoft's TSqlParser/ScriptDom). Targets net8.0 and net10.0 and has no NuGet package dependencies (SourceLink is build-time only).

Installing

dotnet add package OracleSqlParser --prerelease

The NuGet package, the C# namespace and the assembly are all named OracleSqlParser.

Migrating from PlsqlParser

The packages were renamed to match the namespace: PlsqlParser is now OracleSqlParser, and PlsqlParser.Guard is now OracleSqlParser.Guard. To migrate, replace the package reference (dotnet remove package PlsqlParser, then dotnet add package OracleSqlParser --prerelease). Namespaces are unchanged, so no using directives change.

Versions are published as pre-releases (0.1.0-preview.N) until the API stabilises.

Public API changes

The public API of OracleSqlParser and OracleSqlParser.Guard is checked by Microsoft.CodeAnalysis.PublicApiAnalyzers. Every public member must be listed in the PublicAPI.Shipped.txt or PublicAPI.Unshipped.txt file of its project (one line per member, the analyzer's own signature format). A change that adds, removes or changes a public member fails the build with RS0016 (a public member that is not declared in the file), so the build with -warnaserror is the gate.

  • PublicAPI.Unshipped.txt lists the API of the next release. Changing the API means updating this file in the same commit. Populate it from the analyzer's own output: the RS0016 messages of a build (or the code fix in an IDE). Do not rely on dotnet format analyzers alone, which skips generated override members. Then check the diff for accidental members (helpers, implicit constructors, record-generated members) before committing.
  • PublicAPI.Shipped.txt lists the API of released versions. It is empty until 1.0.0 (the preview versions are not frozen).
  • At the 1.0.0 release, move every line of PublicAPI.Unshipped.txt into PublicAPI.Shipped.txt and leave the unshipped file with only its #nullable enable header. From then on the public API is frozen until 2.0: a breaking change needs a new major version, and additions are added to the unshipped file.
  • Internal types and members are not checked. Tests see them through InternalsVisibleTo.

Releasing

Publishing uses nuget.org Trusted Publishing (GitHub OIDC) bound to .github/workflows/build.yml; no API key secret is required.

  1. Bump <Version> (e.g. 0.1.0-preview.2) in all three csproj files: src/OracleSqlParser/OracleSqlParser.csproj, src/OracleSqlParser.Guard/OracleSqlParser.Guard.csproj and src/OracleSqlParser.Cli/OracleSqlParser.Cli.csproj. Commit.
  2. Tag the commit with the matching v-prefixed version: git tag vX.Y.Z-preview.N (e.g. v0.1.0-preview.2).
  3. Push the tag: git push origin vX.Y.Z-preview.N.

The Build workflow runs on every push and pull request. It packs OracleSqlParser, OracleSqlParser.Guard and OracleSqlParser.Cli (the dotnet tool). Its publish job runs only on v* tags. It checks that the tag matches the <Version> of all three csproj files, then exchanges the GitHub OIDC token for a short-lived key and pushes the packages built by the build job to nuget.org.

Library

var result = SqlParser.Parse("SELECT e.name FROM emp e WHERE e.sal > :min");
if (!result.Success) foreach (var err in result.Errors) Console.WriteLine(err); // (line:col) message
foreach (var table in result.Script.Descendants().OfType<NamedTable>()) Console.WriteLine(table.Name[^1].Value); // EMP
string json = AstJson.Serialize(result.Script, includePositions: true);
  • SqlParser.Parse handles multi-statement scripts (; or /), collects errors and resyncs at the next ;.
  • SqlParser.ParseStatement, ParseExpression and ParseSelect throw ParseException instead; the others in the table below never throw.
  • Every SqlNode has Start/End/Line/Column, GetChildren() and Descendants(); subclass SqlNodeVisitor to walk (see below). Spans are set by the parser; nodes you build in code have zero spans.
  • Unquoted identifiers are upper-cased in Identifier.Value; quoted ones keep case (Quoted = true).

SQL*Plus scripts: &name and &&name are substitution variables by default. A SET DEFINE OFF line (or SET DEF OFF) turns substitution off for the rest of the input, so & is then ordinary text, as it already is inside string literals; SET DEFINE ON turns it back on, and SET DEFINE <char> (for example SET DEFINE ^) makes that character the prefix instead. Only a SET that starts a line and is followed by nothing but the value counts, so UPDATE t SET define = 1 is unaffected. For plain SQL that is not a script, new ParseOptions { SubstitutionEnabled = false } turns substitution off from the start.

new ParseOptions { SqlPlusScript = true } reads the input with two more SQLPlus client rules. A - that ends a line continues the command onto the next line (the hyphen and the line break are removed). A blank line ends an unterminated SQL statement, as it does by default in SQLPlus (SET SQLBLANKLINES ON turns this off). Blank lines inside a PL/SQL unit, and a lone / or . line, behave as in SQL*Plus. Both rules change how plain SQL reads (a - at a line end, a blank line inside a query), so they are off by default.

Entry points and errors

Method Throws ParseException? Returns
Parse(sql[, options]) never ParseResult: Script, Errors, Tokens, Success
TryParse(sql, out script, out errors[, options]) never bool, true when there are no errors
TryParseSelect(sql, out select, out errors[, options]) never bool; select is the single SelectStatement
ParseSelect(sql[, options]) yes, when the input is not exactly one SELECT or has any error the SelectStatement
ParseStatement(sql[, options]) yes, on the first error the Statement
ParseExpression(sql[, options]) yes, on the first error the Expression

ParseSelect and TryParseSelect accept one SELECT with an optional trailing ; or /. Anything else (no statement, two statements, or an INSERT, UPDATE, DELETE or MERGE) is reported with code PSP0008. ParseException.Errors holds every diagnostic, and ParseException.Error the first.

if (SqlParser.TryParseSelect(sql, out var select, out var errors))
    Console.WriteLine(select.Descendants().OfType<NamedTable>().Count());
else
    foreach (var e in errors) Console.WriteLine(e.FormatWithCaret(sql));

Each ParseError has a stable Code, a Message whose wording may change, the Offset, Line and Column of the problem, its Length (the offending token's span, zero at end of input), and Expected, the keywords or tokens the parser was looking for (for example [")"] or ["DML", "DDL", "QUERY"]). Match on Code, not on Message. ToString() gives (line:col) message.

Code Meaning
PSP0001 Unexpected token
PSP0002 Expected a particular token or keyword; see Expected
PSP0003 Unterminated string literal, quoted identifier, q-quote literal or comment
PSP0004 Nesting is deeper than ParseOptions.MaxNestingDepth
PSP0005 Valid Oracle that needs a newer release than ParseOptions.OracleVersion
PSP0006 Construct breaks a rule of its context, for example ** in SQL or PUBLIC on CREATE ROLE
PSP0007 Form that Oracle accepts but the parser does not implement yet
PSP0008 Input is not exactly one SELECT statement (ParseSelect, TryParseSelect)
PSP0099 Internal parser defect, contained so that parsing continues; please report it

FormatWithCaret(source) returns the source line and a caret under the span. Tabs are copied into the caret line, so it lines up in any tab width:

var r = SqlParser.Parse("SELECT (1 FROM dual");
Console.WriteLine(r.Errors[0]);                        // (1:11) Expected ')' but found 'FROM'
Console.WriteLine(r.Errors[0].FormatWithCaret(r.Source));
SELECT (1 FROM dual
          ^~~~

Targeting older Oracle versions

ParseOptions.OracleVersion names the release a script must run on: Oracle19, Oracle21 or Oracle23. The default is Oracle23, so nothing changes unless you set it. For an older target, constructs introduced later are still parsed and kept in the tree, but each one adds a ParseError, for example 'IS TRUE/FALSE' requires Oracle 23 or later (targeting Oracle 19). Check Errors as usual; the tree is still usable for tooling. ParseStatement and ParseExpression throw on the first such diagnostic, like any other error.

var r = SqlParser.Parse("SELECT 1 FROM dual WHERE (1 = 1) IS TRUE", new ParseOptions { OracleVersion = OracleVersion.Oracle19 });
// r.Errors: one error, "'IS TRUE/FALSE' requires Oracle 23 or later (targeting Oracle 19)"

SQL_MACRO is gated at 21, although table macros were backported to 19.7 and later release updates. Users on a patched 19c should target Oracle21 or ignore that diagnostic.

The gated constructs and their versions are listed in COVERAGE.md.

CLI

The command-line tool is packaged as the .NET tool OracleSqlParser.Cli (command oraclesqlparser):

dotnet tool install -g OracleSqlParser.Cli --prerelease
oraclesqlparser [--shape] [--positions] [--compact] [-f file | -e "sql"]   # or stdin

Prints the AST as JSON (or the compact tree with --shape); syntax errors go to stderr with exit code 1. See the tool README for every flag.

Coverage

See COVERAGE.md: every statement in Oracle's statement index, the node that represents it, whether it is fully typed or a typed header with a token-tree body, and the known gaps. oraclesqlparser --shape -e "..." prints the compact tree used by the shape tests.

Tests

tests/OracleSqlParser.Tests (and tests/OracleSqlParser.Guard.Tests for the guard): explicit expected trees (*ShapeTests.cs, compared via AstPrinter) plus a smoke corpus (SmokeCorpusTests.cs) that only checks inputs parse.

Query guard (experimental, separate package)

An experimental package, OracleSqlParser.Guard, validates and rewrites user-supplied SELECT queries. It is not a security boundary; read its README before using it.

Generating SQL

SqlScriptGenerator (the equivalent of ScriptDom's SqlScriptGenerator) prints any node the parser produces back to Oracle SQL / PL/SQL: scripts, queries, DML, DDL (including the token-tree bodies), transaction/session statements, PL/SQL blocks and program units, SQL*Plus commands. The output parses back to an identical tree (verified over the whole test corpus). Parentheses are added from operator precedence, so trees you build or edit print correctly; a node type the generator does not know throws NotSupportedException naming it.

var script = SqlParser.Parse("select e.name, d.name dname from emp e left join dept d on e.d = d.id where e.sal > 100 order by e.name").Script;
var generator = new SqlScriptGenerator(new SqlScriptGeneratorOptions
{
    NewLineBeforeFromClause = true, NewLineBeforeJoinClause = true, NewLineBeforeWhereClause = true,
    NewLineBeforeOrderByClause = true, MultilineSelectElementsList = true,
});
Console.WriteLine(generator.Generate(script));
SELECT
    e.name,
    d.name AS dname
FROM emp e
LEFT OUTER JOIN dept d ON e.d = d.id
WHERE e.sal > 100
ORDER BY e.name;

Generate(node) returns a string; Generate(node, textWriter) writes to a writer. Any node can be generated, not only scripts. Instances are immutable (options are copied) and thread-safe.

Option Default Effect
KeywordCasing Uppercase Uppercase / Lowercase keywords
IdentifierCasing Preserve Preserve prints unquoted names as typed (Identifier.Text), Uppercase / Lowercase normalise; quoted names are always verbatim
IndentSize 4 Spaces per indentation level
NewLineBeforeFromClause, ...WhereClause, ...HierarchicalClause, ...GroupByClause, ...HavingClause, ...OrderByClause, ...JoinClause, ...SetOperator false Start that clause on a new line (SELECT; FROM/WHERE also apply to UPDATE/DELETE/MERGE; ORDER BY also covers OFFSET/FETCH/FOR UPDATE)
NewLineBeforeSetClause, ...ValuesClause, ...ReturningClause false UPDATE ... SET / MERGE WHEN, INSERT VALUES/SELECT/INTO branches, RETURNING and LOG ERRORS on a new line
MultilineSelectElementsList false One select-list element per line below SELECT
MultilineColumnDefinitions false One column/constraint per line in CREATE TABLE
MultilinePlsql false PL/SQL declarations, statements, handlers and member lists each on an indented line
AlignClauseBodies false Clause body on its own indented line below SELECT / FROM / WHERE / GROUP BY / HAVING / ORDER BY
IncludeSemicolons true Script generation: ; after each statement
SqlPlusSlashAfterPlsql false Script generation: a / line after PL/SQL units (blocks, CREATE PROCEDURE/FUNCTION/PACKAGE/TRIGGER/TYPE); Java sources always get their required /

The parser keeps the source spelling that is not part of the meaning: q'[it's]' / nq'...' literals, N'x', :"Bind", number literals and optimizer hint text print back as written.

Limitations:

  • Comments are not part of the AST, so the generator does not print them. They are kept in the token stream (ParseResult.Tokens, Token.LeadingTrivia); to change a script and keep its comments and layout, use SourceEditor.
  • Token-tree bodies (long-tail syntax without a typed node: the generic CreateObjectStatement, AlterObjectStatement and AdminStatement, SQL*Plus command arguments, ...) are printed as their tokens, separated by single spaces (no space around ., @, % and before (), so their original line layout is lost. Words in them follow IdentifierCasing, not KeywordCasing.
  • Built-in data type names (VARCHAR2, TIMESTAMP WITH TIME ZONE, ...) are stored normalised and print with the keyword casing; user-defined type names keep their quoting (DataType.NameParts).
  • Without IncludeSemicolons a multi-statement script no longer parses (statements are only separated by newlines).
  • Some purely optional spellings are not stored and are normalised: ASC, VIRTUAL, 1..3 vs 1 .. 3, RETURN/RETURNING, JSON DUALITY VIEW as JSON RELATIONAL DUALITY VIEW, PIPELINED ROW POLYMORPHIC.

For a compact, normalised single line (upper-case keywords and unquoted identifiers), use new SqlScriptGenerator(new SqlScriptGeneratorOptions { IdentifierCasing = IdentifierCasing.Uppercase }).Generate(node).

Examining and editing trees

Modelled on ScriptDom: typed visitor callbacks, an in-place rewriter, no reflection.

// Examine: override Visit(T) for the node types you care about, then root.Accept(visitor).
sealed class TableCollector : SqlNodeVisitor
{
    public List<string> Names { get; } = [];
    public override void Visit(NamedTable node) => Names.Add(string.Join(".", node.Name.Select(i => i.Value)));
}
var tables = new TableCollector();
SqlParser.Parse("SELECT * FROM a JOIN s.b ON a.x = b.x").Script.Accept(tables);   // A, S.B

// Edit: Rewrite(T) returns the node (edited), a replacement, or null to remove it (from a list, or an optional property).
sealed class TenantFilter(string predicate) : SqlNodeRewriter
{
    public override SqlNode? Rewrite(QuerySpecification node)
    {
        base.Rewrite(node);                                   // rewrite nested subqueries first
        var p = SqlParser.ParseExpression(predicate);
        node.Where = node.Where is null
            ? new WhereClause { Condition = p }
            : new WhereClause { Condition = new BinaryExpression { Left = node.Where.Condition, Operator = BinaryOperator.And, Right = p } };
        return node;
    }
}
var script = SqlParser.Parse("SELECT a FROM t WHERE x = 1 OR y = 2").Script;
new TenantFilter("tenant = 7").RewriteTree(script);                     
new SqlScriptGenerator().Generate(script);                                       // SELECT a FROM t WHERE (x = 1 OR y = 2) AND tenant = 7;

Clause nodes

A clause is a node, as in ScriptDom: QuerySpecification.Where is a WhereClause, not the condition, and From, GroupBy, Having, StartWith, ConnectBy and SelectStatement.OrderBy follow the same pattern. The clause node spans its keyword, which the body alone does not, so the clause can be taken from the source or replaced without searching the token stream for the keyword.

const string sql = "SELECT a FROM t WHERE /* keep */ x = 1 GROUP BY a, b";
var q = (QuerySpecification)((SelectStatement)SqlParser.Parse(sql).Script.Statements[0]).Body;

var where = sql[q.Where!.Start..q.Where.End];       // WHERE /* keep */ x = 1
var group = sql[q.GroupBy!.Start..q.GroupBy.End];   // GROUP BY a, b
var first = q.From!.Tables[0];                      // the clause holds the table references
Console.WriteLine($"{where} | {group} | {first.Start}");
  • An absent clause is null, so SELECT 1 (Oracle 23c) has a null From rather than an empty list.

  • UpdateStatement and DeleteStatement carry the same WhereClause and FromClause, as ScriptDom puts both on UpdateDeleteSpecificationBase.

  • OrderByClause is used wherever a sort list is written: on a select statement, inside OVER (...), WITHIN GROUP (...) and KEEP (...), and in MATCH_RECOGNIZE and MODEL rules.

  • A modifier belongs to its clause: ConnectByClause.NoCycle and OrderByClause.Siblings (for ORDER SIBLINGS BY).

  • The condition inside a clause is required, so a rewriter removes a whole clause by returning null for the clause node, not by nulling its condition.

  • The graph pattern WHERE (GraphTable, GraphVertexPattern, GraphEdgePattern) stays a bare Expression; ScriptDom has no nested WhereClause either.

  • ExplicitVisit(T) (default: Visit(node), then node.AcceptChildren(this)) is where to change how the walk descends, as in ScriptDom's TSqlFragmentVisitor.

  • A rewriter changes the tree in place. Keep the original with node.DeepClone<T>() first. A wrong replacement type, or removing a required child, throws InvalidOperationException naming the property.

  • SqlNodeComparer.StructurallyEqual(a, b) compares two trees ignoring source positions and spelling-only properties (Identifier.Text, q'[...]' delimiters).

  • Visitors and rewriters recurse once per tree level, so a very deep left-leaning chain (more than about 5,000 a AND b AND ... terms) can exhaust the stack. For such trees use the iterative node.Descendants() (which also handles 20,000-term chains in well under a second); StructurallyEqual is iterative too.

  • GetChildren(), Accept, AcceptChildren, the typed Visit/ExplicitVisit/Rewrite overloads, cloning and comparison are generated into src/OracleSqlParser/Generated/*.g.cs by tools/AstGen. After adding or changing an AST node class or property, regenerate and commit the result:

    dotnet run --project tools/AstGen
    

    The tool builds the library without Generated/ in a temporary copy and reflects over it, so it works even when the generated files are stale. The unit test GeneratedCode_IsUpToDate fails CI if you forget.

Format-preserving edits

SourceEditor edits the original text instead of reprinting the tree, so comments, whitespace, line breaks and casing outside the edited ranges survive. SqlScriptGenerator prints only the replacement and inserted text.

var parsed = SqlParser.Parse("SELECT /* keep */ a  ,  b\nFROM   orders o -- trailing\nWHERE x = 1");
var query = parsed.Script.Descendants().OfType<QuerySpecification>().First();
var editor = new SourceEditor(parsed);
editor.Replace(((NamedTable)query.From!.Tables[0]).Name[0], "employees");   // table name only; the alias o stays
editor.Remove(query.SelectList[1]);                                  // removes "  ,  b"
editor.AndWhere(query, SqlParser.ParseExpression("o.active = 1"));   // SourceEdits.AndWhere
Console.WriteLine(editor.Apply());
SELECT /* keep */ a
FROM   employees o -- trailing
WHERE (x = 1) AND (o.active = 1)
  • Replace(node, replacement) prints a node with the editor's SqlScriptGeneratorOptions; Replace(node, text) inserts text as written. InsertBefore, InsertAfter and Remove work the same way. Apply() returns the edited text.
  • A node's range runs from its first to its last character. Comments before a node and after its last token stay in place.
  • Remove on an item of a comma-separated list also removes its comma (see the Remove remarks), so the list stays valid. Removing several items of one list works in any order and combination: a, b, c minus b and c gives a, and minus a and c gives b. Removals may overlap; they are merged when Apply() runs. Removing every item of a list is not valid SQL and is left to the caller.
  • A statement's range excludes its ;, so InsertAfter(statement, text) puts text before the terminator. Include the terminator in the text to add a statement after another.
  • Nodes built in code, or produced by ParseStatement/ParseExpression, have no source position and throw InvalidOperationException, as do replacements and inserts whose ranges overlap. Two inserts at one offset are kept in the order they were added.
  • SourceEdits.AndWhere(query, predicate) adds a condition with AND. An existing WHERE is wrapped in parentheses, so an OR stays grouped: WHERE x = 1 OR z = 3 becomes WHERE (x = 1 OR z = 3) AND (predicate). Without a WHERE, the condition is inserted after the FROM clause.

Analysing a tree

SqlAnalysis answers the usual discovery questions about a parsed tree: the tables and views a statement touches (and whether it reads or writes them), which column references belong to which FROM item, the bind variables and the function calls. Each result carries its node and its source span, and results are in source order.

var script = SqlParser.Parse(
    "WITH recent AS (SELECT e.id, e.dept_id FROM hr.employees e WHERE e.hired > :since) " +
    "SELECT r.id, d.name FROM recent r JOIN departments@hrlink d ON d.id = r.dept_id").Script;

foreach (var t in SqlAnalysis.GetTables(script))
    Console.WriteLine($"{t.Access} {(t.IsCteReference ? "[CTE] " : "")}{string.Join(".", t.NameParts.Select(p => p.Value))}{(t.DbLink is null ? "" : "@" + t.DbLink)}");
// Read HR.EMPLOYEES
// Read [CTE] RECENT
// Read DEPARTMENTS@HRLINK

foreach (var b in SqlAnalysis.GetBinds(script))
    Console.WriteLine($"bind :{b.Name} at {b.Start}");
// bind :since at 75
  • GetColumns binds each column reference to the FROM item it belongs to (Source) only when the tree decides it. A qualifier must match an alias, or the table name when there is no alias. An unqualified name binds when its query has exactly one FROM item and no enclosing query has one too. Otherwise the result is Ambiguous or Unresolved, never a guess.
  • GetFunctions reports calls with their qualified name parts and OVER usage. The parser has no catalogue of built-in functions, so built-in and user-defined calls are not told apart.
  • Not analysed: SQL inside string literals (EXECUTE IMMEDIATE, OPEN ... FOR), INTO targets as columns, and column references in DDL outside a query. The SqlAnalysis remarks list the details.

Tokens and comments

Modelled on ScriptDom's ScriptTokenStream: the parse result keeps every token, and every node knows which tokens it covers.

var r = SqlParser.Parse("SELECT /* c1 */ a -- c2\nFROM t");
foreach (var tok in r.Tokens)                                     // every token, hints and EOF included, in source order
    Console.WriteLine($"{tok.Text} preceded by {tok.LeadingTrivia.Count} trivia");

var stmt = r.Script.Statements[0];
Console.WriteLine(r.Tokens[stmt.FirstTokenIndex].Text);           // SELECT
Console.WriteLine(r.Tokens[stmt.LastTokenIndex].Text);            // t
  • ParseResult.Tokens is the complete lexer output. Optimizer hints the parser does not use are still listed there, though they are absent from the parser's own view of the stream.
  • Token.LeadingTrivia lists the whitespace and comments (TriviaKind.Whitespace, LineComment, BlockComment) between the previous token and this one. Each Trivia has its Text and source Start/End.
  • SqlNode.FirstTokenIndex and LastTokenIndex are indexes into ParseResult.Tokens. Tokens[node.FirstTokenIndex].Start == node.Start and Tokens[node.LastTokenIndex].End == node.End for every parsed node. -1 means the node has no position in ParseResult.Tokens: this covers nodes built in code, nodes from ParseStatement/ParseExpression, and the argument nodes inside a /*+ ... */ hint (the hint's own HintClause/HintItem do get indexes).
  • Reconstruction invariant: for every token in order, append its leading trivia text, then source[token.Start..token.End]. The result is the original input exactly, so no text between tokens is lost.

Roadmap

See ROADMAP.md for planned work.

Integration tests

tests/OracleSqlParser.IntegrationTests runs against a real Oracle database (the free gvenzl/oracle-free:23-slim-faststart image, started with Testcontainers; Docker is required):

dotnet test tests/OracleSqlParser.IntegrationTests

One container is started per test run (first run pulls the image; allow a few minutes). They check that (a) the SQL printed by SqlScriptGenerator is accepted by Oracle and returns the same columns and rows as the original query, (b) the experimental QueryGuard.RestrictToIds output executes and returns only permitted ids in the tested scenarios for both AccessJoinStyle values, and (c) every statement of the smoke corpus passes Oracle's own syntax check inside a scratch schema (PL/SQL-only forms such as SELECT ... INTO are asserted to be rejected), and (d) generator verification: every corpus statement that Oracle accepts is regenerated with SqlScriptGenerator using the default, the fully formatted and the lower-case option sets, and each generated text must be classified by Oracle like the original (never rejected); the 62 result-comparing queries are also printed with all three option sets and must return identical rows (GeneratorAcceptanceTests, WriterRoundTripTests; known gaps, if any, are listed with a reason in KnownGeneratorGaps). Container startup is capped at 8 minutes (override with ORACLE_TEST_STARTUP_TIMEOUT_SECONDS); on timeout the tests are skipped with a clear message. If Docker is not available the tests are skipped, not failed. The default unit tests (dotnet test tests/OracleSqlParser.Tests) do not need Docker.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on OracleSqlParser:

Package Downloads
OracleSqlParser.Guard

EXPERIMENTAL: policy validation and access-restriction rewriting for user-supplied Oracle SELECT queries, built on OracleSqlParser. Not a security boundary; see README.

OracleSqlParser.Fluent

Fluent builders that create and edit OracleSqlParser syntax trees (SELECT, INSERT, UPDATE, DELETE, MERGE and expressions), so that every built tree is the tree the parser produces for the printed SQL.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 94 11/21/2026
1.0.0-rc.4 61 11/20/2026
1.0.0-rc.3 83 11/19/2026
1.0.0-rc.2 65 11/18/2026
1.0.0-rc.1 69 11/16/2026
0.7.0-preview.1 59 11/14/2026
0.6.0-preview.1 64 11/14/2026
0.5.0-preview.1 69 11/14/2026