I often work with SQL queries. Sometimes I write them myself, sometimes they are created by an ORM – in either case, they are sometimes pretty long. This means that it would often be nice to have them formatted in a nice way (I mean indentation and line breaks).
It turns out that there aren’t many programs which can do that. One that I found that works well enough is sqlformat
from the sqlparse Python module. However, I often had my query in an Emacs buffer. What I wanted was an Emacs command to invoke the sqlformat
binary and reformat the query I marked in the region.
This time, I decided to go for a quick-and-dirty solution – no error checking, no fancy stuff, just a plain command assuming that I have the SQL in the region (active or not). The emphasis here is on quick – it took me literally a couple of minutes to write this command. This is indeed one of the strengths of Emacs and Emacs Lisp: instead of learning fancy stuff like functional programming, even a beginner can just write a function mimicking a sequence of human actions in the editor, basically doing little more than writing a keyboard macro by hand. (I believe this is the gateway to more serious Elisp hacking for many people – it was for me.) So, here’s the code:
(defun sql-format-region () "Format SQL in region using `sqlformat'." (interactive) (shell-command-on-region (region-beginning) (region-end) "sqlformat -r -" nil t))
CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryPostgreSQL