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.

Slow vim startup

I had today a very weird situation.

From my laptop, I ssh to another system, and from there to yet another.

On this final system I noticed that vim starts relatively slow. i.e. this command:

time vim -u /dev/null -c “:q"

returned time in around 3.5 seconds, while on my laptop (which is much less powerful) it is:

=> time vim -u /dev/null -c ":q"
real    0m0.073s
user    0m0.056s
sys     0m0.016s

I tried to debug the situation, and it got weirder. If I did “su – another_user" (on the final system) – it became fast. What's more: if I did su – depesz (my account) back – vim was still fast!

After some debugging it occurred to me: I have automatic X11 forwarding turned on. I checked – and yes, in the shell that vim starts slowly, i had “DISPLAY" variable, set to localhost:10.0!

Quick unset DISPLAY, and suddenly vim starts 0.027s!

Lesson for future – do not use automatic X11 forwarding for long-distance ssh connections, or make sure you run vim with “-X" option.

Later I learned why it tries X11 connection – to get access to X copy/paste buffer (available as * register). Nice feature, but with quite problematic side effects.