DEV Community

Dan Croak
Dan Croak

Posted on • Edited on

2 1

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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay