14

"SQL Statement indentation good practice" appears to be the accepted format for writing SQL blocks.

Is there a Vim indent/syntax file that would adhere to this standard, or at least be close?

Currently my Vim left alights pretty much everything and only indents certain keywords.

Community
  • 1
  • 1
Mike
  • 3,818
  • 10
  • 28
  • 44

4 Answers4

18

By installing python module sqlparse

pip install sqlparse

from vim you can use

:%!sqlformat --reindent --keywords upper --identifiers lower -

in order to not attach a shortcut ,pt I added following configuration to my .vimrc config file:

autocmd FileType sql call SqlFormatter()
augroup end
function SqlFormatter()
    set noai
    " set mappings...
    map ,pt  :%!sqlformat --reindent --keywords upper --identifiers lower -<CR>
endfunction

You can customize sqlformat a bit. See

sqlformat --help

Valerio Crini
  • 1,476
  • 2
  • 10
  • 12
11

"SQLUtilities : SQL utilities - Formatting, generate - columns lists, procedures for databases" has the SQL Utilities plugin, which is capable. And "How to auto-format and auto-capitalize SQL in Vim" is a related discussion.

the Tin Man
  • 150,910
  • 39
  • 198
  • 279
Zsolt Botykai
  • 46,263
  • 14
  • 81
  • 102
5

You can use the vim-autoformat plugin:

  • Install vim-autoformat with your favourite plugin-manager (I prefer lightweight vim-plug)
  • Install sqlparse with pip
  • Add the following lines to your vim/nvim config
noremap <F3> :Autoformat<CR>
let g:formatdef_sql = '"sqlformat --reindent --keywords upper - identifiers lower -"'
let g:formatters_sql = ['sql']

If you see this message: vim has no support for python, you should rebuild your vim with python support or install python-client for neovim

lucidyan
  • 2,100
  • 2
  • 17
  • 20
5

If you use coc.nvim then you can add the coc-sql extension.

Dzamo Norton
  • 874
  • 8
  • 16