I was making a lot of use of vim-dadbod in recent weeks. One thing that I was missing was the ability to run the query under the cursor. I ended up creating a query text object to help me do just that. It is implemented like this:
" sql query text objectvnoremap aq <esc>:callsearch(";", "cWz")<cr>:callsearch(";\\<bar>\\%^", "bsWz")<cr>:callsearch("\\v\\c^(select<bar>with<bar>insert<bar>update<bar>delete<bar>create)\>", "Wz")<cr>vg`'
omap aq :normal vaq<cr>
It searches backward for the last ; character or the beginning of the file and then from there forward for the next SQL keyword (I'm sure the list there might be refined, this worked for me though). It switches to visual mode and searches for the next ; character.
Then I mapped <C-Q> to execute the query using b:db as the database url:
" setup b:db and run queries with itnmap<expr><c-q>exists("b:db") ? 'vaq:DB b:db<cr>' : ':DB b:db = g:db_'vmap<expr><c-q>exists("b:db") ? ':DB b:db<cr>' : '<esc>:DB b:db = g:db_'
The conditional expression checks first whether b:db is set. It starts a command line expression to set it based on a g:db_* variable if it's not. We could throw an error instead here.
Would it make sense to add this to dadbod?
The text was updated successfully, but these errors were encountered:
Now you can use <C-Q>aq in normal mode or <C-Q> in visual mode to do what you intend. It's superior to mapping to :DB directly because it uses the exact selection rather than just line numbers.
I haven't mapped it by default because I'm not sure what a good map would be. <C-Q> is okay but for conflicting with terminal flow control. I kind of like Q, but lots of people inexplicably map that to gq. I might have to settle for making it an option (gross).
A few additional notes:
I don't want to take responsibility for something like aq because it's really hard to generalize to all use cases, and there's no reason it can't live in a separate plugin.
I really, really hate the "prompt me the first time" stuff. It's the reason I couldn't make peace with dbext. I provided several methods of defaulting and a map is definitely not the place to contradict that.