Tips N’ Tricks – Running your queries from within Vim

I use VIM. For more or less everything. Including writing blogposts.

Usually, when I was working on blogpost about PostgreSQL, I would write an sql file, switch to another console with psql running, run \i, get output, and then copy/paste the results to my blogpost in another vim.

It worked, but wasn't really nice.

Today, I realized that I can do something much smarter.

I can just type in Vim, and then pass the data to psql, using simple “visual mapping":

:vmap R :!psql -e<enter>

How does it work? When I'm in Vim, and I select (visual) some text, I press shift-R, and the selected blob is sent to psql.

Of course – psql has to know which database to connect to, as which user, and so on, but this is handled by setting PG* environment variables before running Vim.

Thanks to “-e" option, I get all the queries printed back to me, so I don't lose them from my text file.

It works just great.

While I didn't show it in the ascii cast, I can of course also run in this way multiple queries, use transactions, and everything else. The only problem might be that every such run is executed in new psql, which means that you don't have single session.

But, that doesn't seem to be big problem (at least for me).

It would be nice to have vim as full blown sql client, and I think it's perfectly possible, but I just don't care enough to spend time writing necessary scripts.

7 thoughts on “Tips N’ Tricks – Running your queries from within Vim”

  1. What is the vim plugin you are using to auto capitilize the SQL keywords ?

  2. Awesome, then if we just could tie in psql’s autocomplete while typing SQL..

  3. depesz, yes excactly, then my (already extremely loved) vim would be a full-blown replacement for my psql-sessions.

  4. @Jesper:
    actually, it’s pretty simple.

    Run in your vim:

    !psql -qAtX -c "select proname from pg_proc union select relname from pg_class union select nspname from pg_namespace union select usename from pg_user union select attname from pg_attribute order by 1" > ~/.sql-dict

    It’s long, but it can be added as macro.

    And then do:

    :set dict=~/.sql-dict

    Now your completion commands will use the data from dict.

    Of course this is not full context-based completion, but I think with some, not much, hacking, it could be added too.

Comments are closed.