joereynolds / SQHell.vim

An SQL wrapper for vim
MIT License
131 stars 9 forks source link

Queries should be async #17

Open joereynolds opened 6 years ago

joereynolds commented 6 years ago

Currently, long queries block the editor If we're on neovim or vim 8, use async, otherwise block as normal.

joereynolds commented 6 years ago

An attempt

function! mysql#GetResultsFromQuery(command)
    let user = g:sqh_connections[g:sqh_connection]['user']
    let password = g:sqh_connections[g:sqh_connection]['password']
    let host = g:sqh_connections[g:sqh_connection]['host']

    let connection_details = 'mysql --unbuffered -u' . user . ' -p' . password . ' -h' . host
    let system_command = connection_details . " --table -e '" . a:command . "'"

    let async_is_ok = has('job') && has ('channel') || has('nvim')
    if async_is_ok

        let query_results = jobstart(system_command, extend({'shell': 'shell 1'}, {'on_stdout': function('mysql#AsyncReturnQueryResultsCallback'), 'stdout_buffered' :v:true}))
    else
        let query_results = system(system_command)
        return query_results
    endif

endfunction

function! mysql#AsyncReturnQueryResultsCallback(id, data, event) dict
    call sqhell#InsertResultsToNewBufferAsync('SQHUnspecified', a:data)
endfunction
function! sqhell#InsertResultsToNewBufferAsync(local_filetype, query_results)

    call nvim_buf_set_lines(sqhell#GetResultsBuffer(), -2, -1, v:true, a:query_results)

    "Remove mysql junk"
    "this should probably go into the ftplugin on BufReadPre
    " normal gg2dd
    " setlocal buftype=nofile
    " setlocal bufhidden=hide
    " setlocal noswapfile
    setlocal nowrap
    " execute 'setlocal filetype=' . a:local_filetype
endfunction

function! sqhell#GetResultsBuffer()
    let buffers = filter(range(1, bufnr("$")), 'bufexists(v:val)')

    for buffer in buffers
        if bufname(buffer) ==? '_sq_'
            return buffer
        endif
    endfor

endfunction
joereynolds commented 6 years ago

Before this we should probably do the one buffer for all results idea.