sqlglot-rust 0.9.22

A SQL parser, optimizer, and transpiler library inspired by Python's sqlglot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# sqlglot-rust

A SQL parser, optimizer, and transpiler library written in Rust, inspired by Python's [sqlglot](https://github.com/tobymao/sqlglot).

## Features

- **Parse** SQL strings into a structured AST
- **Generate** SQL from AST nodes
- **Transpile** between 30 SQL dialects
- **CLI** — command-line interface for transpiling, parsing, and formatting SQL
- **Expression Builder API** — fluent builders for programmatic SQL construction
- **Typed function expressions** — 72+ functions across 8 categories with dialect-specific generation
- **LIMIT / TOP / FETCH FIRST** transpilation across dialects
- **Quoted identifier** preservation and cross-dialect conversion (`"id"``` `id` ```[id]`)
- **Optimize** SQL queries (constant folding, boolean simplification, subquery unnesting, predicate pushdown, column qualification)
- **Scope analysis** — track query scopes, sources, columns, and correlations across nested queries
- **Schema management** — dialect-aware table/column registration and type lookup
- **AST traversal** — walk, find, transform expressions
- **AST Diff** — semantic comparison of SQL statements with structural change detection
- **SQL Execution Engine** — in-memory query execution against Rust data structures for testing and validation
- CTEs, subqueries, set operations (UNION / INTERSECT / EXCEPT)
- Window functions with frames and filters
- CAST, TRY_CAST, EXTRACT, INTERVAL, EXISTS, ANY/ALL/SOME
- Full DDL support (CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE VIEW, etc.)
- Serde serialization for AST nodes

## Supported Dialects

All 30 dialects from Python's sqlglot are supported, with function name mapping,
data type mapping, and ILIKE rewriting between dialects.

### Official Dialects

| Dialect | Description |
| --- | --- |
| ANSI SQL | Base SQL standard |
| Athena | AWS Athena (Presto-based) |
| BigQuery | Google BigQuery |
| ClickHouse | ClickHouse |
| Databricks | Databricks (Spark-based) |
| DuckDB | DuckDB |
| Hive | Apache Hive |
| MySQL | MySQL |
| Oracle | Oracle Database |
| PostgreSQL | PostgreSQL |
| Presto | Presto |
| Redshift | Amazon Redshift (Postgres-based) |
| Snowflake | Snowflake |
| Spark | Apache Spark SQL |
| SQLite | SQLite |
| StarRocks | StarRocks (MySQL-compatible) |
| Trino | Trino (Presto successor) |
| T-SQL | Microsoft SQL Server |

### Community Dialects

| Dialect | Description |
| --- | --- |
| Doris | Apache Doris (MySQL-compatible) |
| Dremio | Dremio |
| Drill | Apache Drill |
| Druid | Apache Druid |
| Exasol | Exasol |
| Fabric | Microsoft Fabric (T-SQL variant) |
| Materialize | Materialize (Postgres-compatible) |
| PRQL | Pipelined Relational Query Language |
| RisingWave | RisingWave (Postgres-compatible) |
| SingleStore | SingleStore (MySQL-compatible) |
| Tableau | Tableau |
| Teradata | Teradata |

### Dialect Transform Rules

The transpiler applies dialect-specific rewrite rules when converting between dialects:

| Rule | Example |
| --- | --- |
| Function name mapping | `NOW()``CURRENT_TIMESTAMP()`, `GETDATE()` |
| `SUBSTR``SUBSTRING` | Postgres uses `SUBSTRING`, MySQL uses `SUBSTR` |
| `CEIL``CEILING` | T-SQL uses `CEILING` |
| `POW``POWER` | T-SQL/Oracle use `POWER` |
| `DATE_TRUNC``DATETRUNC`/`TRUNC` | T-SQL uses `DATETRUNC`, Oracle uses `TRUNC` |
| `ARRAY_AGG``LIST`/`COLLECT_LIST` | DuckDB uses `LIST`, Hive/Spark use `COLLECT_LIST` |
| `HEX`/`UNHEX``TO_HEX`/`FROM_HEX` | Presto/Trino naming convention |
| `IFNULL``COALESCE` | MySQL `IFNULL` → ANSI `COALESCE` |
| `IFNULL``ISNULL` | MySQL `IFNULL` → T-SQL `ISNULL` |
| `NVL``COALESCE` | Oracle `NVL` → standard `COALESCE` |
| `LEN``LENGTH` | T-SQL `LEN` ↔ standard `LENGTH` |
| `RAND``RANDOM` | MySQL `RAND` ↔ Postgres `RANDOM` |
| `ILIKE``LOWER`/`LIKE` | Rewritten for dialects without native ILIKE |
| `LIMIT``TOP` | `LIMIT 10``TOP 10` for T-SQL |
| `LIMIT``FETCH FIRST` | `LIMIT 10``FETCH FIRST 10 ROWS ONLY` (Oracle) |
| Quoted identifiers | `"id"``` `id` ```[id]` per dialect |
| Data type mapping | `TEXT``STRING`, `INT``BIGINT` (BigQuery) |
| `BYTEA``BLOB` | Postgres `BYTEA` ↔ MySQL `BLOB` |

## Quick Start

Add to your `Cargo.toml`:

```toml
[dependencies]
sqlglot-rust = "0.9.21"
```

### Parse and generate SQL

```rust
use sqlglot_rust::{parse, generate, Dialect};

fn main() {
    // Parse a SQL query
    let ast = parse("SELECT a, b FROM t WHERE a > 1", Dialect::Ansi).unwrap();

    // Generate SQL (roundtrip)
    let sql = generate(&ast, Dialect::Ansi);
    assert_eq!(sql, "SELECT a, b FROM t WHERE a > 1");
}
```

### Transpile between dialects

```rust
use sqlglot_rust::{transpile, Dialect};

fn main() {
    // Postgres → BigQuery: NOW() becomes CURRENT_TIMESTAMP()
    let sql = transpile(
        "SELECT NOW(), SUBSTRING(name, 1, 3) FROM users",
        Dialect::Postgres,
        Dialect::BigQuery,
    ).unwrap();
    // → "SELECT CURRENT_TIMESTAMP(), SUBSTRING(name, 1, 3) FROM users"

    // Oracle → T-SQL: NVL becomes ISNULL
    let sql = transpile(
        "SELECT NVL(a, b) FROM t",
        Dialect::Oracle,
        Dialect::Tsql,
    ).unwrap();
    // → "SELECT ISNULL(a, b) FROM t"
}
```

### Parse a dialect name from a string

```rust
use sqlglot_rust::Dialect;

let d = Dialect::from_str("postgres").unwrap();
assert_eq!(d, Dialect::Postgres);

// Multiple aliases are supported
assert_eq!(Dialect::from_str("tsql"), Some(Dialect::Tsql));
assert_eq!(Dialect::from_str("mssql"), Some(Dialect::Tsql));
assert_eq!(Dialect::from_str("sqlserver"), Some(Dialect::Tsql));
```

### Build SQL with the Expression Builder API

```rust
use sqlglot_rust::builder::{select, condition, column, literal};
use sqlglot_rust::{generate, Dialect};

fn main() {
    // Fluent SELECT builder
    let query = select(&["u.id", "u.name", "COUNT(o.id) AS order_count"])
        .from("users")
        .left_join("orders", "u.id = o.user_id")
        .where_clause("u.active = true")
        .and_where("o.created_at > '2024-01-01'")
        .group_by(&["u.id", "u.name"])
        .having("COUNT(o.id) > 0")
        .order_by(&["order_count DESC"])
        .limit(10)
        .build();

    let sql = generate(&query, Dialect::Postgres);
    // => "SELECT u.id, u.name, COUNT(o.id) AS order_count FROM users LEFT JOIN orders ON u.id = o.user_id WHERE u.active = true AND o.created_at > '2024-01-01' GROUP BY u.id, u.name HAVING COUNT(o.id) > 0 ORDER BY order_count DESC LIMIT 10"

    // Condition builder
    let cond = condition("x = 1")
        .and("y = 2")
        .or("z = 3")
        .build();

    // Expression factory functions
    let col = column("name", Some("users"));  // users.name
    let num = literal(42);                     // 42
}
```

### Supported Statements

- `SELECT` (with JOINs, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, TOP, FETCH FIRST, QUALIFY)
- `INSERT INTO ... VALUES` / `INSERT INTO ... SELECT`
- `UPDATE ... SET ... WHERE` (with RETURNING)
- `DELETE FROM ... WHERE` (with USING)
- `MERGE INTO ... USING ... WHEN MATCHED / WHEN NOT MATCHED` (with dialect extensions)
- `CREATE TABLE` (with constraints, IF NOT EXISTS, TEMPORARY, AS SELECT)
- `DROP TABLE` (with IF EXISTS)
- `ALTER TABLE` (ADD COLUMN, DROP COLUMN, RENAME COLUMN, RENAME TO, ALTER TYPE)
- `CREATE VIEW` / `DROP VIEW`
- `TRUNCATE TABLE`
- `BEGIN` / `COMMIT` / `ROLLBACK`
- `EXPLAIN`
- `USE`

### Expression Support

- Column references (qualified and unqualified) with quote-style metadata
- Numeric, string, boolean, and NULL literals
- Binary operators (`+`, `-`, `*`, `/`, `%`, `=`, `<>`, `<`, `>`, `<=`, `>=`, `AND`, `OR`, `||`)
- Unary operators (`NOT`, `-`, `+`)
- Bitwise operators (`&`, `|`, `^`, `<<`, `>>`)
- Function calls (with DISTINCT, FILTER, OVER support)
- Typed function expressions (72+ functions: date/time, string, aggregate, array, JSON, window, math, conversion)
- `BETWEEN`, `IN`, `IS NULL`, `LIKE`, `ILIKE`
- `CASE ... WHEN ... THEN ... ELSE ... END`
- `CAST`, `TRY_CAST`, PostgreSQL `::` cast
- `EXTRACT(field FROM expr)` for all date/time fields
- `INTERVAL` expressions
- `EXISTS`, `IN (subquery)`
- Array literals (`ARRAY[1, 2, 3]`)
- Window functions with frames (`ROWS`, `RANGE`, `GROUPS`)
- Common Table Expressions (WITH / WITH RECURSIVE)
- Set operations (UNION, INTERSECT, EXCEPT with ALL)
- Parenthesized sub-expressions and subqueries

## CLI

The CLI is built with the `cli` feature flag and provides three commands:

### Install

```bash
cargo install sqlglot-rust --features cli
```

### Transpile

Transpile SQL between dialects:

```bash
# From stdin
echo "SELECT CAST(x AS INT) FROM t" | sqlglot transpile --read mysql --write postgres

# With pretty-printing
echo "SELECT a, b FROM t WHERE x > 1" | sqlglot transpile --pretty

# With optimizer
echo "SELECT * FROM t WHERE 1 = 1 AND a > 5" | sqlglot transpile --optimize

# From file to file
sqlglot transpile --read mysql --write postgres --input query.sql --output result.sql
```

### Parse

Parse SQL and output the AST as JSON:

```bash
echo "SELECT a FROM t" | sqlglot parse --pretty
```

### Format

Pretty-print SQL:

```bash
echo "select a,b from t where x>1" | sqlglot format
```

### Options

| Option | Description |
| --- | --- |
| `--read <dialect>` | Source dialect (default: ansi) |
| `--write <dialect>` | Target dialect (default: ansi) |
| `--pretty` | Pretty-print output |
| `--input <file>` | Read from file instead of stdin |
| `--output <file>` | Write to file instead of stdout |
| `--optimize` | Run optimizer before generation (transpile only) |

## Documentation

- **[Installation]docs/installation.md** — Dependency setup and verification
- **[Developer Guide]docs/developer-guide.md** — Parsing, generating, transpiling, AST traversal, optimization, and serialization with full code examples
- **[API Reference]docs/reference.md** — Complete type catalog, function signatures, dialect tables, and error variants

## Architecture

```text
src/
├── ast/          # AST node definitions (~40 expression types, 15 statement types)
├── bin/          # CLI binary (sqlglot) — feature-gated behind "cli"
├── tokens/       # Token types (~200+ variants) and tokenizer
├── parser/       # Recursive-descent SQL parser
├── generator/    # SQL code generator
├── dialects/     # 30 dialect definitions with transform rules
├── optimizer/    # Query optimization and scope analysis
├── planner/      # Logical query planner (execution plan DAG)
├── executor/     # In-memory SQL execution engine
├── schema/       # Schema management (MappingSchema, dialect-aware lookups)
├── errors/       # Error types
└── lib.rs        # Public API (parse, generate, transpile)
```

## Development

```bash
# Build
cargo build

# Build with CLI
cargo build --features cli

# Run tests (500+ tests)
cargo test

# Run CLI tests
cargo test --features cli --test test_cli

# Run benchmarks
cargo bench

# Lint
cargo clippy

# Format
cargo fmt
```

A `Makefile` is provided for convenience:

```bash
make build          # cargo build
make test           # cargo test
make lint           # cargo clippy
make fmt            # cargo fmt
make sbom           # Generate SPDX SBOM (see below)
make bump-version   # Update version across all files (see below)
make all            # build + sbom
```

## SBOM (Software Bill of Materials)

The project supports generating an SBOM in [SPDX](https://spdx.dev/) 2.3 JSON format using [`cargo-sbom`](https://crates.io/crates/cargo-sbom).

### Prerequisites

Install `cargo-sbom`:

```bash
cargo install cargo-sbom
```

### Generate the SBOM

```bash
make sbom
```

This writes the SBOM to `target/sbom/sqlglot-rust.spdx.json`. You can also run the command directly:

```bash
cargo sbom --output-format spdx_json_2_3 > target/sbom/sqlglot-rust.spdx.json
```

The generated SBOM includes all dependency packages with license information, download locations, and [Package URLs (PURLs)](https://github.com/package-url/purl-spec).

## Updating the Version

Use the `bump-version` Makefile target to update the version consistently across
all configuration and documentation files:

```bash
make bump-version VERSION=1.0.0
```

This updates:

- `Cargo.toml` — package version
- `README.md` — dependency snippet
- `docs/installation.md` — dependency snippet
- `Cargo.lock` — regenerated automatically

The `VERSION` parameter is required and must be a full semantic version (e.g. `1.0.0`, `0.10.1`).

## Acknowledgements

This project is inspired by and derived from [sqlglot](https://github.com/tobymao/sqlglot) by Toby Mao, licensed under the MIT License. The original sqlglot license is included in this repository as required by the MIT License terms. A copy of the original license can also be found [in the polyglot repository](https://github.com/tobilg/polyglot/tree/main/licenses).

## License

This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.

This project includes code and concepts derived from [sqlglot](https://github.com/tobymao/sqlglot), which is also licensed under the MIT License. The original copyright notice and permission notice are reproduced below:

```text
MIT License

Copyright (c) 2023 Toby Mao

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```