Skip to main content

A fast SQL parser with Python wrapper and C++ core

Project description

fast-pysqlparse: High-Performance SQL Parsing Library

Build Status Language License

README.md (Chinese)

A high-performance, cross-platform SQL parsing library, designed to handle the most complex SQL queries with ease.

Overview

This library provides a robust set of tools for parsing and analyzing SQL statements. Built with a core engine in C++17 for maximum performance, it offers native Python bindings, making it the ideal choice for data-intensive applications where speed and accuracy are critical.

It excels at parsing extremely long SQL statements and queries with deeply nested subqueries, delivering performance far superior to pure-Python alternatives.

The parser is primarily tested against MySQL-style SQL. Supported dialects are exposed via the Dialects enum in fastsqlparse.conf (re-exported from fastsqlparse): ansi, mysql, postgresql, sqlite, doris. Pass the desired dialect to any parser constructor or tokenize/parse_dependence method via the dialect parameter (default ansi).

Features

  • Fast SQL Parsing: Leverages a high-performance C++17 core to parse SQL statements rapidly
  • Cross-Platform: Compiled into native extensions (.pyd for Windows, .so for Linux)
  • Comprehensive SQL Support: Supports a wide range of SQL statements, including:
    • SELECT (with complex JOIN, WHERE, GROUP BY, subqueries, etc.)
    • INSERT
    • Data Definition Language (CREATE)
    • VIEW
    • DELETE
    • UPDATE
    • Common Table Expressions (CTEs), including nested CTEs
  • Abstract Syntax Tree (AST): Generates a detailed JSON representation of the parsed SQL AST for easy traversal and analysis
  • SQL Formatting: Automatically reformats messy SQL into a clean, readable structure
  • Table Lineage Parsing: Automatically traces and reveals the source-to-target relationships between tables (data lineage)
  • Tokenization: Breaks down SQL statements into their fundamental tokens for lexical analysis
  • Python API: A clean and intuitive Python library built around the high-speed native extension

Performance

This library is engineered for speed. By moving the computationally intensive parsing work to a native C++ layer, it significantly outperforms pure-Python parsing libraries, especially when dealing with large, complex SQL scripts.

Benchmark Results

Test 1: 5000 Iterations

  • SQL Length: 639 characters
  • Total Time: 0.48s
  • PPS (Parses Per Second): ~10300
  • Average per parse: ~0.097ms

Test 2: 10 Million Character SQL

  • SQL Length: 10,500,998 characters
  • Total Time: 0.54s
  • CPS (Characters Per Second): ~19,500,000
  • Parse successful!

Test 3: Python-Only Comparison on ~10M PostgreSQL SQL (No C Benchmark)

Benchmark script: test/python_parsers_10m.py

Parser Avg Time CPS
fastsqlparse 0.7394s 13,524,892.44
pglast 4.8541s 2,060,217.57
sqlglot (postgres) 20.5364s 486,963.12
sqlparse 84.9591s 117,709.35

Notes:

  • SQL size: 10,000,484 chars
  • Runs per parser: 1
  • Results source: results of test/python_parsers_10m.py

Installation

pip install fast-pysqlparse

From Source:

git clone https://github.com/Nohaltsail/fast-pysqlparse.git
cd fast-pysqlparse
pip install build
python -m build
cd dist
pip install fast_pysqlparse-*.whl

Quick Start

from fastsqlparse import Parsed, ParsedQuery

if __name__ == '__main__':
    sql = """

-- main query
SELECT 
    'Monthly Sales Report' AS report_type,
    ms.year,
    ms.month,
    ms.region,
    ms.customer_segment,
    ms.unique_customers,
    ms.total_orders,
    ms.gross_sales,
    ms.avg_order_value,
    ms.cancelled_orders,
    (SELECT SUM(gross_sales) FROM sub_monthly_sales WHERE year = ms.year AND month = ms.month) AS total_monthly_sales,
    ms.gross_sales / NULLIF((SELECT SUM(gross_sales) FROM monthly_sales WHERE year = ms.year AND month = ms.month), 0) * 100 AS sales_percentage,
    (SELECT AVG(avg_order_value) FROM monthly_sales WHERE year = ms.year AND month = ms.month) AS overall_avg_order_value
FROM monthly_sales ms

UNION ALL

SELECT 
    'Category Performance' AS report_type,
    cs.year,
    cs.month,
    NULL AS region,
    cs.category_name AS customer_segment,
    cs.unique_buyers AS unique_customers,
    cs.order_count AS total_orders,
    cs.total_sales AS gross_sales,
    cs.total_sales / NULLIF(cs.order_count, 0) AS avg_order_value,
    NULL AS cancelled_orders,
    (SELECT SUM(total_sales) FROM sub_category_sales WHERE year = cs.year AND month = cs.month) AS total_monthly_sales,
    cs.total_sales / NULLIF((SELECT SUM(total_sales) FROM category_sales WHERE year = cs.year AND month = cs.month), 0) * 100 AS sales_percentage,
    NULL AS overall_avg_order_value
FROM category_sales cs
LIMIT 50, 100"""

    sql_len = len(sql)
    print("sql length: ", sql_len)

    # parse sql statements to SQL object
    sql_stmt = Parsed(sql)
    # Format and print the SQL statement with proper indentation
    print(sql_stmt.format())  # Output formatted SQL statement

    # Tokenization - returns list of tuples containing (token_value, token_type, position)
    tokens = ParsedQuery.tokenize(sql)  # Get tuple list of token information (token_value, token_type, position)

    # Alternative tokenization - returns list of token objects with attributes
    token_obj_list = sql_stmt.tokens()  # Get object list of token information

    # Generate and print Abstract Syntax Tree (AST) in JSON format
    print(sql_stmt.AST())  # Get JSON structure of the SQL statement

    # Extract table lineage/dependencies from the query
    src_tables = ParsedQuery.parse_dependence(sql)  # Get source tables (dependencies) of the query

Comment Handling (pure)

pure controls SQL comment handling in parser constructors such as Parsed, ParsedQuery, ParsedInsert, ParsedCTE, ParsedUpdate, ParsedDelete, ParsedView, and ParsedCreate.

  • pure=False (default): keep comments in parsing/formatting output.
  • pure=True: strip -- and /* ... */ comments before parsing; formatted output and token results exclude comments, and parsing may be faster.
from fastsqlparse import Parsed

parsed_keep = Parsed(sql, pure=False)  # preserve comments
parsed_clean = Parsed(sql, pure=True)  # strip comments before parse

Dialects (dialect)

dialect selects the SQL dialect for parsing and lexical analysis (default "ansi"). Every parser constructor accepts dialect as a string; tokenize classmethods and ParsedQuery.parse_dependence accept a DialectType (default DialectType.ANSI).

Supported dialects: ansi, mysql, postgresql, sqlite, doris (see the Dialects enum and the DIALECT_* constants in fastsqlparse.conf).

from fastsqlparse import Parsed, ParsedQuery, Dialects, DialectType

parsed = Parsed(sql, dialect=Dialects.MYSQL.value)          # "mysql"
query = ParsedQuery(sql, "q", dialect="postgresql")
ParsedQuery.tokenize(sql, dialect=DialectType.MYSQL)        # typed DialectType
ParsedQuery.parse_dependence(sql, dialect="mysql")

When to Use Which Parser

Scenario Parser to Use
SQL statement type is unknown or you don't want to specify the type Parsed/ParsedOne
Multiple SQL statements separated by ; (script execution) Parsed
SELECT / query statement ParsedQuery
INSERT statement ParsedInsert
DELETE statement ParsedDelete
UPDATE statement ParsedUpdate
CREATE TABLE statement ParsedCreate
CREATE VIEW statement ParsedView
CTE (WITH clause) statement ParsedCTE

Note: If your SQL contains multiple statements separated by semicolons (e.g., a script with CREATE, INSERT, SELECT), you must use Parsed. The type-specific parsers are designed for single, known-type statements only.

Documentation

For complete API documentation, see: API_DOC.md

Contributing

Contributions are welcome! Please feel free to submit pull requests, report bugs, or suggest new features.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Note on Dynamic Libraries

This project currently distributes precompiled dynamic libraries (.pyd and .so). The corresponding C++ source code for these dynamic libraries is temporarily not public and is planned to be opened in a future release.

For the full supplementary notice, see LICENSE.

You can also use the dynamic libraries from the source code directly to develop your own SQL parsing library.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

fast_pysqlparse-0.8.0-cp314-cp314-win_amd64.whl (1.6 MB view details)

Uploaded CPython 3.14Windows x86-64

fast_pysqlparse-0.8.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.4 MB view details)

Uploaded CPython 3.14manylinux: glibc 2.17+ x86-64

fast_pysqlparse-0.8.0-cp313-cp313-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.13Windows x86-64

fast_pysqlparse-0.8.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.4 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.17+ x86-64

fast_pysqlparse-0.8.0-cp312-cp312-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.12Windows x86-64

fast_pysqlparse-0.8.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.4 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.17+ x86-64

fast_pysqlparse-0.8.0-cp311-cp311-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.11Windows x86-64

fast_pysqlparse-0.8.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.4 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64

fast_pysqlparse-0.8.0-cp310-cp310-win_amd64.whl (1.5 MB view details)

Uploaded CPython 3.10Windows x86-64

fast_pysqlparse-0.8.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (1.4 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.17+ x86-64

File details

Details for the file fast_pysqlparse-0.8.0-cp314-cp314-win_amd64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 1ee1128be367584883f7d4a5a602f7083b20de50915d8e2d53150723428cb0e2
MD5 e614dfecc8ea4b0848dc4fb1543aa343
BLAKE2b-256 d612410a3cd206f2679815338c0386333bfdbb117019221b6afc9188ec54fa72

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp314-cp314-win_amd64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 577f1dc743bed75ce3591b79270fd6a10e5e1a46217904ac9b599cc80b517102
MD5 eb918c629579d32fca282b19cd7c4653
BLAKE2b-256 7d7968c665d9e634fd29ac4b7d9bb5b6005c29c334a2f4d0a9863b89ce2b9144

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp313-cp313-win_amd64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 71dc7d7399e4bb1cd0ab989d6658e4a14873526df45ecbf30793d66987fe2268
MD5 9d4eed10b6522a9a5dfc7e8eba51acfc
BLAKE2b-256 f2b17d26fcd58ac5057e046956e8f834f0aedb7cb25e0e76c7c4a12e282c6d7d

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp313-cp313-win_amd64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 f72f75e65c3ea152b6b6ebce06d49902903d01bca3a8a92a3958fa110ac14147
MD5 df66aa21fab81bf821a990311e89ba2a
BLAKE2b-256 12b7c87cc46617b387a0faedc09d56a9893a38fdd0b088ec8e402968ff45c8c8

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 de72942792ec548dd3a4589340c1d6e63a9b6e27165b9d03ba993237e1458225
MD5 28e82ce85fd15ed41771761bfec28220
BLAKE2b-256 5051d6fff933833791c53349b907ff55773cbcb79e92ca8c3f74c660a049b96e

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp312-cp312-win_amd64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 fca6a63561fb07a8b8a4aa747e97c4e950429c9aab52377f56fb0e7c303d794e
MD5 22d3ff08ae79f6c336c688b6f4e7dffe
BLAKE2b-256 79ee6a669cff9cc65ec6c1c004b0b05a7c81c93dcffcbef9cb2184085fd95776

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 5a13548cfede0c9c6e002149fd943588395a505bd85b1d50fd522ce7edb5edfc
MD5 7bb6d2d5aa0dd428ff0d4b7a76fbff4b
BLAKE2b-256 92917f1825de9a0b8d6fce3241ce440e83ee29c2ee70b2d01af8a9b337405d26

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp311-cp311-win_amd64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 d1c253e1ecbc313ef9b32301d97a4421d203fdbfc4d46ab6032e49dd5f95f816
MD5 38fc0acbf9eb577d59f6eaff39410236
BLAKE2b-256 ca66861fc91116bc89733dfa7232aa8a1b36c147c3d0a097118d81820f2742a1

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 60988ee8f147e25b79d4a4990d921caaf87fbb576bac187b0315ebb337c8b1f4
MD5 54897b8c43a0d030026a2395a4acdcd1
BLAKE2b-256 7278e261a09f56f3b2397233a1e62a893cac0458bb5eba12fce98350660f6c8f

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp310-cp310-win_amd64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fast_pysqlparse-0.8.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for fast_pysqlparse-0.8.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 3012fb82f3ff357cf0596f2c12f89cae880b120d23fe65728abab10cdd8463d6
MD5 5909ad8cc36bb3a664eb6bb3474d4a3a
BLAKE2b-256 78b35e0052cf592b5a2f5e28f225c5bcc709f43fa78cda39b49f10fee09f0c6e

See more details on using hashes here.

Provenance

The following attestation bundles were made for fast_pysqlparse-0.8.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl:

Publisher: python-publish.yml on Nohaltsail/fast-pysqlparse

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page