Vim: "show create table $Some::DBIx::Class"

Ovid on 2008-05-14T13:43:49

Constantly I'll find myself working with DBIx::Class and I want to see the underlying table structure. So I exit my editor, fire up mysql, sob quietly, and type "show create table $some_table". Now I don't have to -- except for the sobbing part.

Make sure you have filetype plugin on in your .vimrc and in your .vim/ftplugin/perl.vim file add the following code (replacing the variables in the beginning of the function, of course):

noremap T :call ShowCreateTable(expand(""))

function! ShowCreateTable(class_segment)

    " replace these values with whatever your system needs
    let dbic_base = "My::Schema::"
    let host      = "localhost"
    let port      = 3306
    let user      = "someuser"
    let pass      = "somepass"
    let db        = "somedatabase"

    let class     = dbic_base . a:class_segment
    let table     = system("perl -M". class ." -e 'print ". class ."->table'")
    let create    =  system(
        \ "mysql -h".host.
        \ " -P"     .port.
        \ " -u"     .user.
        \ " -p"     .pass.
        \ " "       .db.
        \ " -e 'show create table ".table."'"
    \ )
    echo substitute(create, "\\\\n", "\n", "g")
endfunction

Then, when I see stuff like this:

$schema->resultset('MasterBrand')->find_or_create({ ...

I just position my cursor on the MasterBrand word, type 'T' and it automatically shows the "create table" statement.

Of course, if you don't want to create a .vim/ftplugin/perl.vim file (you should, but you don't have to :), then you could drop the function in your .vimrc and add the following:

filetype plugin on
au! FileType perl :noremap T :call ShowCreateTable(expand(""))