Top Related Projects
The Database Toolkit for Python
Various utility functions and datatypes for SQLAlchemy.
Python CLI utility and library for manipulating SQLite databases
Postgres CLI with autocompletion and syntax highlighting
Rich MySQL Terminal Client with AutoCompletion, Syntax Highlighting, and Dataframes
Quick Overview
sqlparse is a non-validating SQL parser for Python. It provides a set of utilities for parsing, formatting, and manipulating SQL statements. It can be used as a standalone library or integrated into other applications that require SQL parsing functionality.
Pros
- Flexible Parsing: sqlparse can handle a wide range of SQL dialects, including MySQL, PostgreSQL, Oracle, and more.
- Formatting and Beautification: The library can format SQL statements, making them more readable and easier to work with.
- Modular Design: sqlparse is designed with a modular architecture, allowing developers to easily extend or customize its functionality.
- Cross-platform Compatibility: The library is written in pure Python and is compatible with a variety of Python versions and platforms.
Cons
- Limited Validation: sqlparse is a non-validating parser, meaning it does not perform comprehensive syntax checking or semantic analysis of SQL statements.
- Lack of Advanced Features: Compared to some other SQL parsing libraries, sqlparse may lack more advanced features, such as support for complex SQL constructs or optimization capabilities.
- Dependency on External Libraries: The library relies on the
ply(Python Lex-Yacc) library for its parsing implementation, which may introduce additional dependencies for users. - Potential Performance Limitations: For very large or complex SQL statements, the parsing performance of sqlparse may not be as efficient as some other SQL parsing solutions.
Code Examples
Here are a few examples of how to use sqlparse:
- Parsing a SQL Statement:
import sqlparse
sql = "SELECT * FROM users WHERE id = 1;"
parsed = sqlparse.parse(sql)
print(parsed)
- Formatting a SQL Statement:
import sqlparse
sql = "SELECT * FROM users WHERE id = 1;"
formatted = sqlparse.format(sql, reindent=True, keyword_case='upper')
print(formatted)
- Extracting Tokens from a SQL Statement:
import sqlparse
sql = "SELECT * FROM users WHERE id = 1;"
parsed = sqlparse.parse(sql)[0]
tokens = list(parsed.tokens)
for token in tokens:
print(token.value)
- Modifying a SQL Statement:
import sqlparse
from sqlparse.sql import IdentifierList, Identifier
from sqlparse.tokens import Keyword, DML, Whitespace
sql = "SELECT id, name FROM users WHERE active = 1 ORDER BY name DESC;"
parsed = sqlparse.parse(sql)[0]
# Add a new column to the SELECT clause
columns = parsed.get_sublists()[0].tokens
columns.insert(2, Identifier('email'))
# Change the WHERE clause
where_clause = parsed.get_sublists()[1]
where_clause.tokens[2].value = '0'
# Reformat the modified SQL statement
modified_sql = sqlparse.format(str(parsed), reindent=True, keyword_case='upper')
print(modified_sql)
Getting Started
To get started with sqlparse, you can install it using pip:
pip install sqlparse
Once installed, you can import the library and start using its functionality. The sqlparse documentation provides detailed information on the available features and usage examples.
Competitor Comparisons
The Database Toolkit for Python
Pros of SQLAlchemy
- Full-featured ORM with extensive database abstraction capabilities
- Supports a wide range of database systems and SQL dialects
- Provides powerful query construction and optimization tools
Cons of SQLAlchemy
- Steeper learning curve due to its comprehensive feature set
- Heavier overhead for simple database operations
- More complex setup and configuration process
Code Comparison
SQLAlchemy (ORM usage):
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
SQLParse (SQL parsing):
import sqlparse
sql = "SELECT * FROM users WHERE id = 1"
parsed = sqlparse.parse(sql)
print(parsed[0].tokens)
SQLAlchemy is a comprehensive SQL toolkit and Object-Relational Mapping (ORM) library, while SQLParse is a specialized SQL parsing library. SQLAlchemy offers more extensive database interaction capabilities, including ORM functionality, query construction, and database abstraction. SQLParse, on the other hand, focuses solely on parsing and formatting SQL statements, making it lighter and easier to use for specific SQL-related tasks.
Various utility functions and datatypes for SQLAlchemy.
Pros of SQLAlchemy-Utils
- Provides a wide range of utility functions and custom data types for SQLAlchemy
- Offers database-agnostic functionality, enhancing SQLAlchemy's ORM capabilities
- Includes tools for database schema management and data validation
Cons of SQLAlchemy-Utils
- Requires SQLAlchemy as a dependency, limiting its use to SQLAlchemy-based projects
- May have a steeper learning curve due to its integration with SQLAlchemy's ecosystem
- Less focused on SQL parsing and manipulation compared to SQLParse
Code Comparison
SQLAlchemy-Utils example (creating a custom data type):
from sqlalchemy_utils import URLType
class Website(Base):
__tablename__ = 'website'
id = Column(Integer, primary_key=True)
url = Column(URLType)
SQLParse example (parsing SQL):
import sqlparse
sql = "SELECT * FROM table WHERE id = 1"
parsed = sqlparse.parse(sql)
print(parsed[0].tokens)
SQLAlchemy-Utils focuses on extending SQLAlchemy's functionality with utility functions and custom data types, while SQLParse specializes in parsing and formatting SQL statements. SQLAlchemy-Utils is more suitable for projects already using SQLAlchemy, whereas SQLParse is a standalone tool for working with SQL strings directly.
Python CLI utility and library for manipulating SQLite databases
Pros of sqlite-utils
- Focused on SQLite database operations, providing high-level utilities for common tasks
- Includes CLI tools for easy database manipulation from the command line
- Offers features like automatic table creation and CSV import/export
Cons of sqlite-utils
- Limited to SQLite databases, not applicable for other SQL dialects
- Less suitable for complex SQL parsing or analysis tasks
- Smaller community and fewer contributors compared to sqlparse
Code comparison
sqlite-utils:
import sqlite_utils
db = sqlite_utils.Database("my_database.db")
db["table_name"].insert({"column1": "value1", "column2": "value2"})
sqlparse:
import sqlparse
sql = "SELECT * FROM table_name WHERE column1 = 'value1'"
parsed = sqlparse.parse(sql)
print(sqlparse.format(sql, reindent=True, keyword_case='upper'))
Summary
sqlite-utils is a specialized tool for working with SQLite databases, offering convenient utilities and CLI tools. It's ideal for quick database operations and prototyping. sqlparse, on the other hand, is a more general-purpose SQL parser and formatter, suitable for working with various SQL dialects and performing in-depth analysis of SQL statements. The choice between the two depends on the specific requirements of your project and the type of database you're working with.
Postgres CLI with autocompletion and syntax highlighting
Pros of pgcli
- Interactive command-line interface with auto-completion and syntax highlighting
- Specific to PostgreSQL, offering tailored features and optimizations
- Multi-line support and command history
Cons of pgcli
- Limited to PostgreSQL, while sqlparse is database-agnostic
- More complex setup and dependencies compared to sqlparse
- Larger codebase and potentially steeper learning curve
Code Comparison
pgcli example:
from prompt_toolkit.completion import Completion
class PGCompleter(Completer):
def get_completions(self, document, complete_event):
word_before_cursor = document.get_word_before_cursor(WORD=True)
return [Completion(text, start_position=-len(word_before_cursor))
for text in self.find_matches(word_before_cursor, self.all_completions)]
sqlparse example:
import sqlparse
sql = "SELECT * FROM table WHERE id = 1"
parsed = sqlparse.parse(sql)
formatted = sqlparse.format(sql, reindent=True, keyword_case='upper')
The code snippets demonstrate the different focus areas of the projects. pgcli emphasizes interactive features like auto-completion, while sqlparse concentrates on parsing and formatting SQL statements. pgcli is more specialized for PostgreSQL usage, whereas sqlparse offers a general-purpose SQL parsing solution applicable to various database systems.
Rich MySQL Terminal Client with AutoCompletion, Syntax Highlighting, and Dataframes
Pros of mycli
- Interactive command-line interface for MySQL with auto-completion and syntax highlighting
- Supports multi-line queries and smart completion for SQL keywords, tables, and columns
- Includes features like alias support, favorite queries, and configurable key bindings
Cons of mycli
- Limited to MySQL databases, while sqlparse is database-agnostic
- Requires additional dependencies and setup compared to sqlparse's simpler library approach
- May have a steeper learning curve for users unfamiliar with command-line interfaces
Code Comparison
mycli example:
from mycli.main import MyCli
from mycli.sqlexecute import SQLExecute
sql_execute = SQLExecute(database='mydb', user='myuser', password='mypassword')
mycli = MyCli(sqlexecute=sql_execute)
mycli.run_cli()
sqlparse example:
import sqlparse
sql = "SELECT * FROM users WHERE id = 1"
formatted = sqlparse.format(sql, reindent=True, keyword_case='upper')
print(formatted)
The code examples demonstrate the different approaches of the two projects. mycli provides an interactive CLI experience, while sqlparse focuses on SQL parsing and formatting functionality.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
sqlparse
A non-validating SQL parser for Python. Split scripts into statements, format them, and walk their token tree.
sqlparse tokenizes SQL text and groups the parts it recognizes into a tree of statements, clauses, identifiers and expressions. It accepts any input without validating it, and makes no assumptions about a particular SQL dialect, so vendor extensions and templated SQL parse too. It is a building block for formatters, linters, editors and query analysis tools.
Licensed under the New BSD license.
Install
pip install sqlparse
Usage
Three module-level functions cover most needs: split(), format() and
parse().
Split a script into statements
import sqlparse
sqlparse.split("select * from foo; select * from bar;")
# ['select * from foo;', 'select * from bar;']
Format a statement
print(sqlparse.format("select id,name from users where active=1",
reindent=True, keyword_case="upper"))
SELECT id,
name
FROM users
WHERE active=1
format() accepts the same options as the command line, among them
reindent, keyword_case, strip_comments and indent_width.
Parse and inspect a statement
statement = sqlparse.parse("select id, name from users where active = 1")[0]
print(statement.get_type())
for token in statement.tokens:
if not token.is_whitespace:
print(f"{token.ttype or type(token).__name__!s:20} {token!s}")
SELECT
Token.Keyword.DML select
IdentifierList id, name
Token.Keyword from
Identifier users
Where where active = 1
Tokens with a ttype are leaves. The others are groups you can descend into,
which is how nested constructs like subqueries and CASE expressions are
represented. See
Analyzing SQL statements
for the traversal API.
Command line
Installing sqlparse also provides the sqlformat command. It reads from stdin
when the filename is -, writes to stdout by default, and rewrites files in
place with --in-place:
sqlformat --reindent --keywords upper query.sql
Run sqlformat --help for all formatting options.
Pre-commit hook
Format SQL files on commit with pre-commit:
repos:
- repo: https://github.com/andialbrecht/sqlparse
rev: 0.5.5 # use the latest release
hooks:
- id: sqlformat
args: [--in-place, --reindent, --keywords, upper]
The hook defaults to --in-place --reindent. When overriding args, keep
--in-place, or the hook writes to stdout and leaves your files unchanged.
Links
| Documentation | https://sqlparse.readthedocs.io/ |
| Release notes | https://sqlparse.readthedocs.io/en/latest/changes.html |
| Issues | https://github.com/andialbrecht/sqlparse/issues |
| Discussions | https://github.com/andialbrecht/sqlparse/discussions |
| Online demo | https://sqlformat.org/ |
Contributing
Contributions are welcome. See CONTRIBUTING.md to get started.
sqlparse is maintained in spare time, so it can take a while before an issue or pull request gets a reply. Thanks for your patience. A pull request that comes with tests for the behavior it changes is usually the quickest to review.
For security issues, please follow SECURITY.md rather than opening a public issue.
License
sqlparse is licensed under the New BSD license; see LICENSE for the full text. Parts of the code are based on Pygments, written by Georg Brandl and others.
Top Related Projects
The Database Toolkit for Python
Various utility functions and datatypes for SQLAlchemy.
Python CLI utility and library for manipulating SQLite databases
Postgres CLI with autocompletion and syntax highlighting
Rich MySQL Terminal Client with AutoCompletion, Syntax Highlighting, and Dataframes
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot