Managing databases with Neovim and Docker

If you work on software projects that use a database, you need a convenient way to connect, inspect, and query them.

Some IDEs like PhpStorm have an integrated database client, which I've recently added to my Neovim setup and working with Docker and Docker Compose.

Configuring Docker Compose

A local port needs to be exposed from the database container that Neovim can connect to.

I usually do this with a docker-compose.override.yaml file:

services:
database:
ports:
- 3307:3306

Docker Compose recognises this by default, extends the normal docker-compose.yaml file and adds a port forwarding to the database service.

Configuring Neovim

The two plugins I'm using are tpope/vim-dadbod and kristijanhusak/vim-dadbod-ui, and should work with Vim and Neovim. Thanks to both of these project maintainers.

Once installed, run :DBUIAddconnection to add a database connection.

Here is an example connection string:

mysql://drupal:drupal@localhost:3307/drupal?protocol=tcp

Using the local port mapping, this connects to a MySQL database within the database service.

Then run :DBUI to toggle the UI and see a list of databases in the left-hand sidebar.

You can enter <leader>R to refresh databases or r to rename or update connection details for a specific database.

Once connected, you can enter and save queries, using table and column name completion, which are executed every time the query is saved.

I like not needing to switch contexts and leave my editor in order to query a database, and feel a lot more productive being able to write, execute and save queries within this UI.

If you're a Vim or Neovim user, I'd suggest trying this setup and seeing if it works for you.