Skip to content

Instantly share code, notes, and snippets.

@redraw
Last active September 24, 2019 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redraw/117a9e6eb0f5fa993adf2c00cadcda87 to your computer and use it in GitHub Desktop.
Save redraw/117a9e6eb0f5fa993adf2c00cadcda87 to your computer and use it in GitHub Desktop.
Custom IPython magic to format SQL
""" ~/.ipython/profile_default/startup/00-sqlf.py
Requires sqlparse (`pip install sqlparse`)
Example:
In [1]: %sqlf Site.objects.all().query
SELECT `django_site`.`id`,
`django_site`.`domain`,
`django_site`.`name`
FROM `django_site`
ORDER BY `django_site`.`domain` ASC
"""
from __future__ import print_function
import sys
from IPython.core.magic import register_line_magic
try:
import sqlparse
except ImportError:
sys.exit()
@register_line_magic
def sqlf(line):
output = eval("str(%s)" % line)
print(sqlparse.format(output, reindent=True))
@edvm
Copy link

edvm commented Jun 5, 2018

awsome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment