loading...

Format and run SQL on save in Vim

croaky profile image Dan Croak Updated on ・1 min read

Install and configure ALE in ~/.vimrc:

call plug#begin('~/.vim/plugged')
  Plug 'dense-analysis/ale' " :help ale
call plug#end()

In ~/.vim/ftplugin/sql.vim:

" Auto-fix
let b:ale_fixers = ['pgformatter']
let g:ale_fix_on_save = 1
let b:ale_sql_pgformatter_options = '--function-case 1 --keyword-case 2 --spaces 2'

" Run current file
nmap <buffer> <Leader>r :!clear && psql -d $(cat .db) -f %<CR>

In my laptop.sh, I have a variant of the following that is idempotent; it will install or update Homebrew and pgFormatter:

# pgformatter
brew install pgformatter

# Vim plugins
curl -fLo "$HOME/.vim/autoload/plug.vim" --create-dirs \
  https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
vim -u "$HOME/.vimrc" +PlugUpdate +PlugClean! +qa

In each of my projects, I have a .db file that contains only my database name:

example_development

When I save a .sql file in Vim, it auto-formats it with pgformatter using the flags from my ftplugin/sql.vim.

When I run <Leader>r from a .sql file in Vim, it runs the file against my .db Postgres database through psql.

Posted on by:

Discussion

pic
Editor guide