Last active
June 13, 2021 15:19
-
-
Save mark-mishyn/b54fee17b33af43e92a8bbb24ca248cc to your computer and use it in GitHub Desktop.
Just a "SQL printer" for SQLAlchemy. It's a colored example for a SQLA ORM Query.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlparse | |
from pygments import highlight | |
from pygments.formatters.terminal import TerminalFormatter | |
from pygments.lexers import SqlLexer # to highlight SQL statements | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import Query | |
engine = create_engine("sqlite+pysqlite:///db.sqlite", echo=True, future=True) | |
def format_sql(query: Query): | |
compiled = query.statement.compile( | |
engine, compile_kwargs={"literal_binds": True}) | |
parsed = sqlparse.format(str(compiled), reindent=True, keyword_case='upper') | |
print(highlight(parsed, SqlLexer(), TerminalFormatter())) | |
# Or version without sqlparse (without sqlparse there are less new lines in output) | |
def format_sql(query: Query): | |
compiled = query.statement.compile( | |
engine, compile_kwargs={"literal_binds": True}) | |
print(highlight(str(compiled), SqlLexer(), TerminalFormatter())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment