18

There are some general well-known coding standards and styles for SQL (e.g. capitalizing reserved words, placing main keywords in different lines, etc.).

Does Emacs come with any modes for this, or are there any packages for formatting SQL to make it adhere to common standards?

1

4 Answers 4

7

Emacs does not come anything useful for sql indenting.

The best thing out there is sql-indent.el

Which doesn't do auto-indenting only on command indentation.

I have found it pretty useful at times

6

If you don't mind calling out to a python process, then this works (pip install sqlparse):

(defun sqlparse-region (beg end)
  (interactive "r")
  (shell-command-on-region
   beg end
   "python -c 'import sys, sqlparse; print(sqlparse.format(sys.stdin.read(), reindent=True))'"
   t t))
1
  • Since python2 is no longer supported you should changes "python -c ..." to "python3 -c ...". Also, sqlparse is available under apt compatible linux distros and to install it system wide, type sudo apt install python3-sqlparse. Commented Nov 14, 2020 at 13:27
1

Not a complete answer to your query, but for capitalizing reserved words, I have some abbrev definitions. Here is a short example just to show you (not including all reserved sql words)

(define-abbrev-table 'sql-mode abbrev-table 
(mapcar #'(lambda (v) (list v (upcase v) nil 1))
'("absolute" "action" "add" "after" "all" "allocate" "alter" "and" "any" "are" "array" "as" "asc" "asensitive" )
))
1

From version 21.4a, Emacs comes with sql-mode (sql.el) that does automatic indentation and font lock. No built-in linting, but it allows you to define an external linter with the customizable variable sql-linter-program (M-x customize-group SQL)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.