DEV Community

Dan Croak
Dan Croak

Posted on • Edited on

Format and run SQL on save in Vim

Install and configure ALE in ~/.vimrc:

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

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

example_development
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)