October 5th, 2012 by depesz | Tags: , , , | 7 comments »
Did it help? If yes - maybe you can help me? Donate BTC to 19zPa5diT2LZqGtTi8f8bfApLn8rw9zBHx

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.

  1. 7 comments

  2. # Collin
    Oct 5, 2012

    I use the Vim plugin dbext, works great!

    http://vim.sourceforge.net/scripts/script.php?script_id=356

  3. # Ketema Harris
    Oct 5, 2012

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

  4. Oct 5, 2012

    @Collin: thanks

    @Katema: no plugin. Just configuration. You can see it here:

    http://svn.depesz.com/svn/environment/.vim/ftplugin/sql.vim

  5. # Jesper
    Oct 7, 2012

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

  6. Oct 7, 2012

    @Jesper – like column/table/function names?

  7. # Jesper
    Oct 7, 2012

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

  8. Oct 7, 2012

    @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.

Leave a comment