diff plugins/dbtables/dbtables.vim @ 6:3017fd33ad8b

Better support for db tables. Adding some simple diffing support for hg.
author Luka Sitas <lsitas@avatarasoftware.com>
date Tue, 28 Oct 2025 15:26:12 -0400
parents 4a7bc1c8551b
children
line wrap: on
line diff
--- a/plugins/dbtables/dbtables.vim	Mon Oct 27 15:52:05 2025 -0400
+++ b/plugins/dbtables/dbtables.vim	Tue Oct 28 15:26:12 2025 -0400
@@ -1,43 +1,33 @@
-let g:db_user = ""      " Replace with your default database username
-let g:db_password = ""  " Replace with your default database password
-let g:db_name = ""      " Replace with your default database name
-let g:db_host = ""      " Replace with your default database name
+let g:db_user = ""
+let g:db_password = ""
+let g:db_name = ""
+let g:db_host = ""
 
-
-" Helper function to execute a command and handle errors
+" Execute shell commands
 function! s:ExecuteShellCommand(command)
     let result = system(a:command . ' 2>&1')
-    if v:shell_error != 0
-        return [v:false, result]
-    endif
-    return [v:true, result]
+    return [v:shell_error == 0, result]
 endfunction
 
+" Execute a SQL query
 function! s:ExecuteDBQuery(query)
-    let db_user = shellescape(g:db_user)
-    let db_password = shellescape(g:db_password)
-    let db_name = shellescape(g:db_name)
-    let db_host = shellescape(g:db_host)
-
-    let command = 'mariadb --user=' . db_user
-                \ . ' --password=' . db_password
-                \ . ' --database=' . db_name
-                \ . ' --host=' . db_host
-                \ . ' -e ' . shellescape(a:query)
-
+    let command = printf('mariadb --user=%s --password=%s --database=%s --host=%s -e %s',
+                \ shellescape(g:db_user), shellescape(g:db_password),
+                \ shellescape(g:db_name), shellescape(g:db_host),
+                \ shellescape(a:query))
+    
     let [success, result] = s:ExecuteShellCommand(command)
-
-    if !success
+    if success
+        return split(result, "\n")
+    else
         call s:HandleDBError(result, command)
         return []
     endif
-    return split(result, "\n")
 endfunction
 
+" Handle database command errors
 function! s:HandleDBError(result, command)
     echoerr 'Shell command failed: ' . a:command
-    echoerr a:result
-
     if a:result =~# 'Access denied'
         echoerr 'Authentication error: Check your username and password.'
     elseif a:result =~# 'Unknown database'
@@ -51,24 +41,28 @@
     endif
 endfunction
 
-
-" Show the structure/schema of the selected table
-function! s:ShowTableSchema(table)
-    " Open a new tab for schema
+" Display schema or data in a new buffer
+function! s:OpenInNewTab(title, data)
     tabnew
     enew
-    execute 'file ' . table . '_schema'
-    " Describe the table structure
-    let data = s:ExecuteDBQuery('DESCRIBE ' . table . ';')
-    if len(data) > 0
-        call append(0, data)
+    execute 'file ' . a:title
+    if !empty(a:data)
+        call append(0, a:data)
     else
-        call append(0, 'No schema found or an error occurred.')
+        call append(0, 'No data found or an error occurred.')
     endif
-    " Set buffer options and syntax
     setlocal filetype=sql buftype=nofile bufhidden=wipe nobuflisted noswapfile nomodifiable
 endfunction
 
+" Open the database schema
+function! s:OpenTableSchema(table)
+    call s:OpenInNewTab(a:table . '_schema', s:ExecuteDBQuery('DESCRIBE ' . a:table . ';'))
+endfunction
+
+" Open the table data
+function! s:OpenTableData(table)
+    call s:OpenInNewTab(a:table, s:ExecuteDBQuery('SELECT * FROM ' . a:table . ';'))
+endfunction
 
 let s:popup_table = ""
 " Popup selection for table actions
@@ -101,124 +95,26 @@
     unlet! s:popup_table
 endfunction
 
-
-" Internal: remove any existing dropdown option lines from the DBTables buffer
-function! s:ClearTableOptions()
-    let to_del = []
-    for lnum in range(1, line('$'))
-        let ln = getline(lnum)
-        if ln =~# '^\s\+\(Data\|Schema\)$'
-            call add(to_del, lnum)
-        endif
-    endfor
-    if !empty(to_del)
-        for lnum in reverse(to_del)
-            call deletebufline('%', lnum)
-        endfor
-    endif
-endfunction
-
-
-" Open table data for a given table name
-function! s:OpenTableData(table)
-    tabnew
+" Open the database tables list
+function! s:OpenDBTablesWindow()
+    execute '34 vsplit'
     enew
-    execute 'file ' . a:table
-    let data = s:ExecuteDBQuery('SELECT * FROM ' . a:table . ';')
-    if !empty(data)
-        call append(0, data)
-    else
-        call append(0, 'No data found.')
-    endif
-    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nomodifiable
-endfunction
-
-" Open table schema for a given table name
-function! s:OpenTableSchema(table)
-    tabnew
-    enew
-    execute 'file ' . a:table . '_schema'
-    let data = s:ExecuteDBQuery('DESCRIBE ' . a:table . ';')
-    if !empty(data)
-        call append(0, data)
-    else
-        call append(0, 'No schema found or an error occurred.')
-    endif
-    setlocal filetype=sql buftype=nofile bufhidden=wipe nobuflisted noswapfile nomodifiable
-endfunction
-
-function! s:OpenDBTablesWindow()
-    " Open a new vertical split window
-    execute '34 vsplit'
-    " Create a new buffer
-    enew
-    " Set buffer name to "DBTables"
     file DBTables
-
     let tables = s:ExecuteDBQuery("SHOW TABLES;")
     if empty(tables)
         echo "No tables found or an error occurred."
-        return
+    else
+        call append(0, ['Available Tables:'] + tables[1:])
+        setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nomodifiable nonumber norelativenumber winfixwidth
+        nnoremap <buffer> <CR> :call <SID>ShowTablePopup()<CR>
     endif
-
-    " Display the tables in the buffer
-    call append(0, 'Available Tables:')
-    call remove(tables, 0)
-    for table in tables
-        call append('$', table)
-    endfor
-
-    " Set buffer options
-    setlocal buftype=nofile
-    setlocal bufhidden=wipe
-    setlocal nobuflisted
-    setlocal noswapfile
-    setlocal nomodifiable
-    setlocal nonumber
-    setlocal norelativenumber
-    setlocal winfixwidth
-
-    " Map <Enter> to a modal menu (data or schema)
-    nnoremap <buffer> <CR> :call <SID>ShowTablePopup()<CR>
-endfunction
-
-
-function! s:ShowTableData()
-    " Get the current line (table name)
-    let lnum = line('.')
-    let table_name = getline(lnum)
-
-    " Open a new tab and create a new buffer
-    tabnew
-    enew
-    " Set buffer name to the table name
-    execute 'file ' . table_name
-
-    let data = s:ExecuteDBQuery("SELECT * FROM " . table_name . ";")
-
-    " Display the table data in the buffer
-    if len(data) > 0
-        call append(0, data)
-    else
-        call append(0, 'No data found.')
-    endif
-
-    " Set buffer options
-    setlocal buftype=nofile
-    setlocal bufhidden=wipe
-    setlocal nobuflisted
-    setlocal noswapfile
-    setlocal nomodifiable
 endfunction
 
 let s:query_history = []
 
 " Function to execute SQL from the current buffer with parameter prompt
 function! s:ExecuteSQLQuery()
-    " Get the content of the current buffer (SQL query)
     let query = join(getline(1, '$'), "\n")
-
-    " Execute query with prompt for parameters
     call s:PromptAndExecuteQuery(query)
 endfunction
 
@@ -232,8 +128,7 @@
     call s:PromptAndExecuteQuery(query)
 endfunction
 
-
-" Function to prompt user for parameter values and execute query
+" Handle parameter prompts and execute query
 function! s:PromptAndExecuteQuery(query)
     " Identify parameters in the form of :parameter_name
     let pattern = ':\(\k\+\)'
@@ -261,74 +156,45 @@
     " Replace parameters in the query with user-provided values
     let updated_query = a:query
     for [param, value] in items(param_values)
-        let updated_query = substitute(updated_query, param, shellescape(value), 'g')
+        let updated_query = substitute(updated_query, param, value, 'g')
     endfor
 
-    " Append the query to history
     call add(s:query_history, updated_query)
-
-    " Execute the updated query
-    let data = s:ExecuteDBQuery(updated_query)
-
-    " Open results in a new tab
-    tabnew
-    enew
-    execute 'file SQLQueryResult'
-    call append(0, data)
-
-    " Set buffer options and highlight
-    setlocal filetype=sql
-    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nomodifiable
+    call s:OpenInNewTab('SQLQueryResult', s:ExecuteDBQuery(updated_query))
 endfunction
 
-
+" View query history
 function! s:OpenQueryHistory()
     " Open the query history in a new split window
     execute 'vsplit'
     enew
     call setline(1, s:query_history)
-
-    " Allow selecting a query to be put into a new buffer to execute
     nnoremap <buffer> <CR> :call <SID>ExecuteHistoryQuery(line('.'))<CR>
-
-    " Set buffer options
-    setlocal buftype=nofile
-    setlocal bufhidden=wipe
-    setlocal nobuflisted
-    setlocal noswapfile
+    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile
 endfunction
 
 function! s:ExecuteHistoryQuery(lnum)
-    " Execute the selected query from history
     let query = getline(a:lnum)
     execute 'normal! i' . query
-    " Optionally call the execute function directly or process
+    " Optional execution or further processing
 endfunction
 
-
+" Open MariaDB console
 function! DBConsole()
-  " Save the current cursor position
-  let save_cursor = getpos(".")
-
-  "Format the files
-  let db_user = g:db_user
-  let db_password = g:db_password
-  let db_name = g:db_name
-  " let db_host = shellescape(g:db_host)
-  let db_host = g:db_host
-
-
-
-  let command = 'mariadb --user=' . db_user . ' --password=' . db_password . ' --database=' . db_name . ' --host=' . db_host . ' '
-  let command =  substitute(command, '\n', '', 'g')
-  execute ':term ' . command
-  call setpos(".", save_cursor)
+    " Save the current cursor position
+    let save_cursor = getpos(".")
+    let command = printf('mariadb --user=%s --password=%s --database=%s --host=%s',
+                  \ g:db_user, g:db_password,
+                  \ g:db_name, g:db_host)
+    
+    let command =  substitute(command, '\n', '', 'g')
+    execute ':term ' . command
+    call setpos(".", save_cursor)
 endfunction
 
 " Keybinding to open query history
 nnoremap <Leader>qh :call <SID>OpenQueryHistory()<CR>
-nnoremap <Leader>db :call DBConsole()<cr>
-
+nnoremap <Leader>db :call DBConsole()<CR>
 command! DBTables call s:OpenDBTablesWindow()
 command! ExecuteSQL call s:ExecuteSQLQuery()