sqlparse Documentation
repository·master·Indexed 26 days ago
https://github.com/andialbrecht/sqlparseA non-validating SQL parser for Python 3.10+ used to split scripts into statements, format SQL text, and walk token trees for analysis. It provides the sqlformat CLI tool and can be integrated as a pre-commit hook. Key functions include sqlparse.split(), sqlparse.format(), and sqlparse.parse(), with support for custom lexer configuration via the Lexer singleton to handle specific SQL dialects or custom keywords.
What's inside sqlparse
- sqlparse is a non-validating SQL parser for Python. It tokenizes SQL text and organizes it into a tree structure consisting of statements, clauses, identifiers, and expressions. Because it does not validate the SQL or assume a specific dialect, it is highly compatible with vendor extensions and templated SQL. It is commonly used as a building block for SQL formatters, linters, editors, and query analysis tools.
Use the sqlformat.org web interface
masterIf you prefer a web-based interface, you can use sqlformat.org, which provides a web front-end that exposes the formatting features ofsqlparseonline.Understand the structure of parsed SQL statements
masterWhen callingsqlparse.parse(), the returned value is a tree-like representation of the analyzed SQL statements. You can traverse this tree to retrieve metadata and structural information about the SQL code.Configure the Lexer singleton
masterThe
sqlparse.lexer.Lexeris a singleton class responsible for breaking character streams into tokens using regular expressions and keyword dictionaries. To customize the parsing logic for specific SQL dialects or custom keywords, you must interact with the singleton instance.To configure the lexer:
- Retrieve the singleton instance using
Lexer.get_default_instance(). - Call
.clear()to remove all existing keyword dictionaries and regular expressions. Warning:.clear()removes all keyword dictionaries; you must re-add any dictionaries you wish to keep. - Use
.set_SQL_REGEX(SQL_REGEX)to apply a new list of regular expressions. - Use
.add_keywords(KEYWORDS)to add keyword dictionaries (e.g.,keywords.KEYWORDS_COMMON,keywords.KEYWORDS_MYSQL).
- Retrieve the singleton instance using
Configure sqlparse as a pre-commit hook
masterYou can use
sqlformatto automatically format SQL files during a git commit usingpre-commit.Important: When overriding
args, you MUST include the--in-placeflag, otherwise the hook will write tostdoutand leave your files unchanged.repos: - repo: https://github.com/andialbrecht/sqlparse rev: 0.5.5 # use the latest release hooks: - id: sqlformat args: [--in-place, --reindent, --keywords, upper]Integrate sqlparse with pre-commit
masterYou can integrate
sqlparsewithpre-committo automatically format SQL files before they are committed to version control.Add the following to your
.pre-commit-config.yamlfile:repos: - repo: https://github.com/andialbrecht/sqlparse rev: 0.5.5 # Replace with the version you want to use hooks: - id: sqlformatAfter adding the configuration, install the hooks by running:
pre-commit installTo run the hook manually on all files, use:
pre-commit run sqlformat --all-filesrepos: - repo: https://github.com/andialbrecht/sqlparse rev: 0.5.5 hooks: - id: sqlformatRequirements for sqlparse
masterTo usesqlparse, you must have Python 3.10+ installed.Configure sqlformat pre-commit hook arguments
masterYou can customize the formatting behavior of the
sqlformatpre-commit hook by overriding theargsparameter in your.pre-commit-config.yaml.Important: When overriding
args, you must include--in-place. If you omit this flag,sqlformatwill write to stdout instead of modifying the file, and the pre-commit hook will leave your files unchanged.Common arguments include:
--in-place(Required for pre-commit to modify files)--reindentor-r: Reindent statements--keywords <case>or-k <case>: Convert keywords toupperorlower--identifiers <case>or-i <case>: Convert identifiers toupperorlower--indent_width <int>: Set indentation width--strip-comments: Remove comments from SQL
repos: - repo: https://github.com/andialbrecht/sqlparse rev: 0.5.5 hooks: - id: sqlformat args: [--in-place, --reindent, --keywords, upper, --identifiers, lower]Install sqlparse via pip
masterInstall
sqlparsefrom the Python Package Index (PyPI) usingpip.Requirements:
- Python 3.10 or later
- No dependencies
$ pip install sqlparseAdd custom keywords and regex to the Lexer
masterYou can extend
sqlparseto support custom SQL syntax (likeZORDER BY) or specific keywords (likeBAR) by modifying the Lexer's regex list and keyword dictionaries.When using
.clear(), you can reconstruct the regex list by slicing the existingsqlparse.keywords.SQL_REGEXand injecting your custom tuple, which should follow the format(regex_string, token_type). You can then re-populate the lexer with standard keyword sets fromsqlparse.keywordsand add your own custom dictionary.import re import sqlparse from sqlparse import keywords from sqlparse.lexer import Lexer # get the lexer singleton object to configure it lex = Lexer.get_default_instance() # Clear the default configurations. lex.clear() # Define a custom regex for 'ZORDER BY' my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) # slice the default SQL_REGEX to inject the custom object lex.set_SQL_REGEX( keywords.SQL_REGEX[:38] + [my_regex] + keywords.SQL_REGEX[38:] ) # add the default keyword dictionaries lex.add_keywords(keywords.KEYWORDS_COMMON) lex.add_keywords(keywords.KEYWORDS_ORACLE) lex.add_keywords(keywords.KEYWORDS_MYSQL) lex.add_keywords(keywords.KEYWORDS_PLPGSQL) lex.add_keywords(keywords.KEYWORDS_HQL) lex.add_keywords(keywords.KEYWORDS_MSACCESS) lex.add_keywords(keywords.KEYWORDS_SNOWFLAKE) lex.add_keywords(keywords.KEYWORDS_BIGQUERY) lex.add_keywords(keywords.KEYWORDS) # add a custom keyword dictionary lex.add_keywords({'BAR': sqlparse.tokens.Keyword}) # The lexer is now configured to handle the custom syntax sqlparse.parse("select * from foo zorder by bar;")Use the sqlparse module functions
masterThe
sqlparsemodule provides three primary module-level functions for handling SQL:sqlparse.split(): Splits a script into individual SQL statements.sqlparse.format(): Formats a SQL statement according to specific rules.sqlparse.parse(): Parses a SQL statement into a list of tokens.
If the
encodingparameter is not provided,sqlparseassumes the SQL statement is encoded in eitherutf-8orlatin-1.Format and beautify SQL statements using sqlparse.format
masterUsesqlparse.format()to beautify SQL statements. You can pass keyword arguments to control formatting, such asreindentfor indentation andkeyword_caseto change the casing of SQL keywords.