diff --git a/lua/psql.lua b/lua/psql.lua index f980cf6..c0b86fe 100644 --- a/lua/psql.lua +++ b/lua/psql.lua @@ -142,6 +142,41 @@ local function psql_run_visual() psql_run_file(tmp_sql_file) end +local function select_sql_statement() + local current_pos = vim.fn.getpos('.') + local start_pos = vim.fn.searchpos([[\v(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|WITH)\_s+]], 'cnbW') + + -- If no matching positions found, reset cursor and return + if start_pos[1] == 0 then + vim.fn.setpos('.', current_pos) + return false + end + + -- if cursor starts between two queries avoids selecting both + vim.fn.setpos('.', {0, start_pos[1], start_pos[2], 0}) + vim.cmd('normal! v') + + local end_pos = vim.fn.searchpos(';\\s*$', 'cW') + + -- If no matching positions found, reset cursor and return + if end_pos[1] == 0 then + vim.fn.setpos('.', current_pos) + return false + end + + vim.fn.setpos('.', {0, end_pos[1], end_pos[2], 0}) + return true +end + +local function psql_run_close_to_cursor() + select_sql_statement() + if select_sql_statement() then + psql_run_visual() + end + vim.cmd('normal! v\\') +end + + local function psql_run_curr_buf() local current_buf_name = vim.api.nvim_buf_get_name(0) if not is_sql_file(current_buf_name) then @@ -152,13 +187,29 @@ local function psql_run_curr_buf() end local function psql_format() - local current_buf_name = vim.api.nvim_buf_get_name(0) - if not is_sql_file(current_buf_name) then - vim.notify("Not a SQL file!", vim.log.levels.ERROR) - return - end - os.execute(string.format("pg_format -i %s", current_buf_name)) - vim.api.nvim_command("edit") + local current_buf = vim.api.nvim_get_current_buf() + local current_buf_name = vim.api.nvim_buf_get_name(0) + + if not is_sql_file(current_buf_name) then + vim.notify("Not a SQL file!", vim.log.levels.ERROR) + return + end + + -- Detach LSP clients before making changes + for _, client in pairs(vim.lsp.get_clients()) do + vim.lsp.buf_detach_client(current_buf, client.id) + end + + -- Execute pg_format command on the file + os.execute(string.format("pg_format -i %s", current_buf_name)) + + -- Reload the buffer + vim.api.nvim_command("edit") + + -- Reattach LSP clients after reloading the buffer + for _, client in pairs(vim.lsp.get_clients()) do + vim.lsp.buf_attach_client(current_buf, client.id) + end end local function psql_temp() @@ -171,6 +222,7 @@ end return { psql_run_curr_buf = psql_run_curr_buf, psql_run_visual = psql_run_visual, + psql_run_close_to_cursor = psql_run_close_to_cursor, psql_cancel = psql_cancel, psql_run_file = psql_run_file, psql_temp = psql_temp, diff --git a/plugin/psql.lua b/plugin/psql.lua index 3efbbd5..fbf395a 100644 --- a/plugin/psql.lua +++ b/plugin/psql.lua @@ -5,6 +5,13 @@ vim.api.nvim_create_user_command( psql.psql_run_curr_buf, {} ) + +vim.api.nvim_create_user_command( + "PgRunCursor", + psql.psql_run_close_to_cursor, + {} +) + vim.api.nvim_create_user_command( "PgCancel", psql.psql_cancel,