Skip to content

Instantly share code, notes, and snippets.

@mark-mishyn
Last active June 13, 2021 15:19
Show Gist options
  • Save mark-mishyn/b54fee17b33af43e92a8bbb24ca248cc to your computer and use it in GitHub Desktop.
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.
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