Vim – jump to db function under cursor

Our database functions files grouped in the code repository by their schemas. I.e. there is a folder for every schema, and there are sql files named by function name inside the folders. So files hierarchy looks like


If you have the similar code structure (what is quite common) and use vim as editor, then the following trick let you jump to the database function file under cursor with hotkey combination \gf (analogue with embedded gf – go file)
To go back use either command :b# or keys combination ctrl+shift+6 (all keys are for normal mode)

Place the following code into your .vimrc and redefine the value of the first variable with absolute path to your source directory.
Works only for schema prefixed functions with the corresponding folders in the repository.

" Go to db function in the local repo
fu! GoFunction()
    " Redefine the _absolute_ path to the db folder
    let l:sourcePath = '/Users/username/db_repo/'

    let l:schema = ''
    let l:ff = ''
    let l:word = expand("") 
    let l:word = matchstr(l:word, '[^\(]*')
    let l:farr = split(l:word, '\.')
    :if len(l:farr) != 2
        echo 'Word "' . expand("") . '" is not a function'
        let l:schema = l:farr[0]
        let l:ff = l:farr[1]

        let l:fpath = l:sourcePath . l:schema .'/'. l:ff . '.sql'
        :if filereadable(l:fpath)
            execute ':edit ' l:fpath
            echo 'Can not read file ' l:fpath

    unlet l:sourcePath l:schema l:ff l:farr l:fpath l:word

nmap \gf :call GoFunction()

Hope it will be useful for somebody.

This entry was posted in Vim. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s