提交 488c028e 编写于 作者: C Cosmin Popescu

first commit

上级
此差异已折叠。
"============================================================================"
"
" Vim SQL Workbench/J Implementation
"
" Copyright (c) Cosmin Popescu
"
" Author: Cosmin Popescu <cosminadrianpopescu at gmail dot com>
" Version: 1.00 (2015-01-08)
" Requires: Vim 7
" License: GPL
"
" Description:
"
" Provides SQL database access to any DBMS supported by SQL Workbench/J. The
" only dependency is SQL Workbench/J. Also includes powefull intellisense
" autocomplete based on the current selected database
"
"============================================================================"
if !exists('g:Sw_unique_id')
let g:Sw_unique_id = 0
endif
" Executes a shell command{{{1
function! sw#do_shell(command)
let prefix = ''
if (!g:sw_show_shell_output)
let prefix = 'silent'
endif
execute prefix . ' !clear && echo Executting && cat ' . g:sw_tmp . '/' . s:input_file() . ' && ' . a:command
endfunction
function! s:get_profile(profile)
if a:profile =~ '\v^__no__'
let profile = ' ' . b:connection
else
let profile = ' -profile=' . a:profile
endif
return profile
endfunction
function! s:input_file()
return 'sw-sql-' . g:sw_instance_id
endfunction
function! s:output_file()
return 'sw-result-' . g:sw_instance_id
endfunction
" Executes an sql command{{{1
function! sw#execute_sql(profile, command, ...)
execute "silent !echo '' >" . g:sw_tmp . '/' . s:output_file()
let delimiter = ''
if (exists('b:delimiter'))
if (b:delimiter != ';')
let delimiter = ' -delimiter=' . b:delimiter
endif
endif
let abort_on_errors = ''
if (exists('b:abort_on_errors'))
if (!b:abort_on_errors)
let abort_on_errors = ' -abortOnError=false'
endif
endif
let feedback = ' -feedback=false'
if (exists('b:feedback'))
if (b:feedback)
let feedback = ' -feedback=true'
endif
endif
let c = g:sw_exe . s:get_profile(a:profile) . ' -displayResult=true ' . delimiter . abort_on_errors . feedback . ' -script=' . g:sw_tmp . '/' . s:input_file() . ' >' . g:sw_tmp . '/' . s:output_file()
let g:sw_last_sql_query = a:command
if (exists('w:auto_added1') && exists('w:auto_added2'))
let s1 = substitute(w:auto_added1, "\n", '', 'g')
let s2 = substitute(w:auto_added2, "\n", '', 'g')
if a:command =~ '\v' . s1
let add = 1
let lines = split(a:command, "\n")
let g:sw_last_sql_query = ''
for line in lines
if line =~ '\v' . s1
let add = 0
endif
if add
let g:sw_last_sql_query = g:sw_last_sql_query . line . "\n"
endif
if line =~ '\v' . s2
let add = 1
endif
endfor
endif
endif
let g:sw_last_command = c
let lines = split(a:command, "\n")
call writefile(lines, g:sw_tmp . '/' . s:input_file())
call sw#do_shell(c)
redraw!
let result = readfile(g:sw_tmp . '/' . s:output_file())
let touch_result = 1
if a:0
let touch_result = a:1
endif
if (touch_result && len(result) > 0)
if result[len(result) - 1] =~ '\v\c^\([0-9]+ row[s]?\)$'
let result[0] = result[len(result) - 1]
unlet result[len(result) - 1]
else
unlet result[0]
endif
endif
""let i = 0
""for row in result
"" if row == a:command
"" unlet result[i]
"" break
"" endif
"" let i = i + 1
""endfor
if (g:sw_show_command)
call add(result, "")
call add(result, '-----------------------------------------------------------------------------')
call add(result, ' Command executed: ' . a:command)
endif
return result
endfunction
" Exports as ods{{{1
function! sw#export_ods(profile, command)
let g:sw_last_sql_query = a:command
let format = input('Please select a format (text | sqlinsert | sqlupdate | sqldeleteinsert | xml | ods | html | json): ', 'ods')
if (format != '')
let location = input('Please select a destination file: ', '', 'file')
if (location != '')
let queries = sw#sql_split(a:command)
echomsg string(queries)
call writefile(['WbExport -type=' . format . ' -file=' . location . ';', queries[len(queries) - 1]], g:sw_tmp . '/' . s:input_file())
let c = g:sw_exe . s:get_profile(a:profile) . ' -displayResult=true -script=' . g:sw_tmp . '/' . s:input_file()
call sw#do_shell(c)
redraw!
endif
endif
endfunction
" Hides columns from a resultset{{{1
function! sw#hide_columns(rows, columns)
let result = []
let a_columns = split(a:rows[1], "|")
let i = 0
let final = len(a:rows)
if (g:sw_show_command)
let final = len(a:rows) - 4
endif
while i < final
let s = ''
let j = 0
let w = 0
if a:rows[i] =~ '\v^\([0-9]+ Row[^\)]+\)$'
let i = i + 1
continue
endif
while j < len(a_columns)
let f = w + strlen(a_columns[j]) - 1
if (j == len(a_columns) - 1)
let f = strlen(a:rows[i])
endif
if (index(a:columns, j) == -1)
let cmd = 'let s = s . a:rows[i][' . w . ':' . f . ']'
execute cmd
endif
let w = w + strlen(a_columns[j])
let j = j + 1
endwhile
if !(s =~ '\v^[ \s]*$')
call add(result, s)
endif
let i = i + 1
endwhile
if (index(a:columns, 0) != -1)
let i = 0
while i < final && i < len(result)
let h = strlen(result[i])
let cmd = 'let result[i] = result[i][2:' . h . ']'
execute cmd
let i = i + 1
endwhile
endif
let i = final
while (i < len(a:rows))
call add(result, a:rows[i])
let i = i + 1
endwhile
return result
endfunction
function! sw#get_sql_canonical(sql)
let pattern = '\v"([^"]*)"'
let s = substitute(a:sql, '\v[\r\n]', '#NEWLINE#', 'g')
let s = substitute(s, "\\\\\"", '#ESCAPEDDOUBLEQUOTE#', 'g')
let s = substitute(s, "\\\\'", '#ESCAPEDSINGLEQUOTE#', 'g')
let m = matchstr(s, pattern, 'g')
let matches = []
let n = 0
while m != ''
execute "call add(matches, {'m" . n . "': m})"
let m = substitute(m, "\\", "\\\\\\", 'g')
let s = substitute(s, '\V' . m, '#m' . n . '#', 'g')
let n = n + 1
let m = matchstr(s, pattern, 'g')
endwhile
let pattern = "\\v'([^']*)'"
let m = matchstr(s, pattern, 'g')
while m != ''
execute "call add(matches, {'m" . n . "': m})"
let m = substitute(m, "\\", "\\\\\\", 'g')
let s = substitute(s, '\V' . m, '#m' . n . '#', 'g')
let n = n + 1
let m = matchstr(s, pattern, 'g')
endwhile
return [s, matches]
endfunction
function! sw#index_of(s, search)
let start = 0
while start < strlen(a:s) - strlen(a:search)
let n = start + strlen(a:search) - 1
let cmd = "let s = a:s[" . start . ":" . n . "]"
execute cmd
if s == a:search
return start
endif
let start = start + 1
endwhile
return -1
endfunction
" Splits an sql string in statements{{{1
function! sw#sql_split(sql, ...)
let delimiter = ';'
if a:0
let delimiter = substitute(a:1, '\/', "\\/", 'g')
endif
let canon = sw#get_sql_canonical(a:sql)
let s = canon[0]
let matches = canon[1]
let s = substitute(s, '\V' . delimiter, '#SEPARATOR#', 'g')
for _m in matches
let i = items(_m)
let m = '#' . i[0][0] . '#'
let x = substitute(i[0][1], "\\", "\\\\\\", 'g')
let s = substitute(s, m, x, 'g')
endfor
let s = substitute(s, '#NEWLINE#', "\n", 'g')
let s = substitute(s, '#ESCAPEDDOUBLEQUOTE#', "\\\\\"", 'g')
let s = substitute(s, '#ESCAPEDSINGLEQUOTE#', "\\\\'", 'g')
let _result = split(s, '#SEPARATOR#')
let result = []
for r in _result
if !(r =~ '\v^[ \s\t\n\r]*$') && r != ''
call add(result, r)
endif
endfor
return result
endfunction
" Test the split function{{{1
function! sw#test_split()
let s = "select * from t where a = \";\\\"''\"; \nselect * from t2 where b = \"...;\"; select n from t where x = 'u\\'';"
let s = "let result = sw#execute_sql(b:profile, a:sql)"
echo sw#sql_split(s)
endfunction
" Test function for executing an sql statement{{{1
function! sw#test()
let v = sw#execute_sql('pozeLocal', 'WbGrepSource -searchValues="references j_banner_clients" -types=TABLE -useRegex=false')
""let v = sw#hide_columns(v, [2])
call writefile(v, '/tmp/tmp')
endfunction
" Hides the header{{{1
function! sw#hide_header(rows)
let result = a:rows
let i = 0
for row in a:rows
if row =~ '\v^[\-\+]{4,}$'
break
endif
let i = i + 1
endfor
if i < len(a:rows)
unlet result[i]
if (i > 0)
unlet result[i - 1]
endif
endif
return result
endfunction
" Goes to a window identified by a buffer name{{{1
function! sw#goto_window(name)
if bufwinnr(a:name) != -1
while bufname('%') != a:name
wincmd w
endwhile
endif
endfunction
function! sw#generate_unique_id()
let g:Sw_unique_id = g:Sw_unique_id + 1
return g:Sw_unique_id
endfunction
" Sets a buffer to no modification{{{1
function! sw#set_special_buffer(profile)
setlocal buftype=nofile
setlocal bufhidden=wipe
setlocal noswapfile
setlocal nowrap
setlocal nobuflisted
setlocal nomodifiable
call sw#session#set_buffer_variable('profile', a:profile)
endfunction
" Parses the profile xml file to give autocompletion for profiles{{{1
function! sw#parse_profile_xml()
if !exists('g:sw_config_dir')
return []
endif
let lines = readfile(g:sw_config_dir . 'WbProfiles.xml')
let s = ''
for line in lines
let s = s . ' ' . line
endfor
let pattern = '\v\c\<object class\="[^"]{-}"\>.{-}\<void property\="name"\>.{-}\<string\>([^\<]{-})\<'
let result = []
let n = 1
let list = matchlist(s, pattern, 0, n)
while len(list) > 0
if index(result, list[1]) == -1
call add(result, list[1])
endif
let n = n + 1
let list = matchlist(s, pattern, 0, n)
endwhile
return result
endfunction
function! sw#autocomplete_profile(ArgLead, CmdLine, CursorPos)
let profiles = sw#parse_profile_xml()
let result = []
for profile in profiles
if profile =~ '^' . a:ArgLead
call add(result, profile)
endif
endfor
return result
endfunction
function! sw#autocomplete_profile_for_buffer(ArgLead, CmdLine, CursorPos)
let words = split(a:CmdLine, '\v\s+')
if len(words) == 1 || (len(words) == 2 && !(a:CmdLine =~ '\v\s+$'))
return sw#autocomplete_profile(a:ArgLead, a:CmdLine, a:CursorPos)
endif
if a:ArgLead =~ '\v^\s*$'
let path = '*'
else
let path = a:ArgLead . '*'
endif
return split(glob(path), '\n')
endfunction
此差异已折叠。
"============================================================================"
"
" Vim SQL Workbench/J Implementation
"
" Copyright (c) Cosmin Popescu
"
" Author: Cosmin Popescu <cosminadrianpopescu at gmail dot com>
" Version: 1.00 (2015-01-08)
" Requires: Vim 7
" License: GPL
"
" Description:
"
" Provides SQL database access to any DBMS supported by SQL Workbench/J. The
" only dependency is SQL Workbench/J. Also includes powefull intellisense
" autocomplete based on the current selected database
"
"============================================================================"
if !exists('g:SW_Tabs')
let g:SW_Tabs = {}
endif
" Local functions{{{1
" Iterates in the tabs array{{{2
function! s:iterate(f)
for _profile in items(g:SW_Tabs)
let profile = _profile[0]
let tabs = _profile[1]
if (profile == b:profile || profile == '*')
for tab in tabs
execute "let r = " . a:f . "(tab)"
if !r
break
endif
endfor
endif
endfor
endfunction
function! s:open_in_new_buffer()
normal ggVGy
tabnew
normal Vp
set filetype=sql
endfunction
" Finds a tab by shortcut (to be called via iterate){{{2
" We are returning 0 if found, because this will break the loop
" The result is saved in b:tab. The tab searched is in b:shortcut
function! s:find_tab_by_shortcut(tab)
if a:tab['shortcut'] == b:shortcut
call sw#session#set_buffer_variable('tab', a:tab)
return 0
endif
return 1
endfunction
" Get the first tab{{{2
function! s:get_first_tab(tab)
call sw#session#set_buffer_variable('first_tab', a:tab)
return 0
endfunction
" Set a special buffer{{{2
function! s:set_special_buffer(profile, connection)
call sw#session#init_section()
call sw#set_special_buffer(a:profile)
call sw#session#set_buffer_variable('t1_shortcuts', 'Main shortcuts:')
call sw#session#set_buffer_variable('t2_shortcuts', 'Available shortcuts in the left panel:')
call sw#session#set_buffer_variable('t3_shortcuts', 'Available shortcuts in the right panel:')
if (a:connection != '')
call sw#session#set_buffer_variable('connection', a:connection)
endif
call s:iterate('s:add_shortcut')
endfunction
" Change a tab{{{2
function! s:change_tab(command, shortcut, title)
let result = sw#execute_sql(b:profile, a:command)
wincmd t
call sw#session#set_buffer_variable('current_tab', a:shortcut)
wincmd b
call sw#session#set_buffer_variable('current_tab', a:shortcut)
if (exists('b:last_cmd'))
call sw#session#unset_buffer_variable('last_cmd')
endif
setlocal modifiable
normal! ggdG
setlocal nomodifiable
wincmd h
if (exists('b:mappings'))
for m in b:mappings
execute "silent! nunmap <buffer> " . m
endfor
endif
call sw#session#set_buffer_variable('current_tab', a:shortcut)
setlocal modifiable
normal! ggdG
for line in result
put =line
endfor
normal! ggdd
setlocal nomodifiable
call s:set_info_buffer()
wincmd b
wincmd h
call sw#session#set_buffer_variable('mappings', [])
call sw#session#set_buffer_variable('shortcut', a:shortcut)
call s:iterate('s:find_tab_by_shortcut')
if (exists('b:tab'))
for panel in b:tab['panels']
execute "nnoremap <buffer> <silent> " . panel['shortcut'] . " :call <SID>change_panel(\"" . substitute(panel['command'], '"', "\\\\\"", 'g') . "\", \"" . panel['shortcut'] . "\", \"" . panel['title'] . "\", \"" . b:tab['shortcut'] . "\")<cr>"
call add(b:mappings, panel['shortcut'])
endfor
endif
normal 5G
if (exists('b:selected_row'))
silent! call matchdelete(b:selected_row)
call sw#session#unset_buffer_variable('selected_row')
endif
endfunction
function! s:change_panel(command, shortcut, title, tab_shortcut)
"if line('.') < 5
" echoerr "You have to select an object in the left panel"
" return
"endif
if (exists('b:selected_row'))
call matchdelete(b:selected_row)
endif
let object = substitute(getline('.'), '\v^([^ ]+) .*$', '\1', 'g')
call sw#session#set_buffer_variable('selected_row', matchadd('SWSelectedObject', '^' . object . ' .*$'))
let cmd = substitute(a:command, '\v\%object\%', object, 'g')
let result = sw#execute_sql(b:profile, cmd)
call sw#session#set_buffer_variable('shortcut', a:tab_shortcut)
call s:iterate('s:find_tab_by_shortcut')
if (exists('b:tab'))
for panel in b:tab['panels']
if (panel['shortcut'] == a:shortcut)
if (has_key(panel, 'skip_columns'))
let result = sw#hide_columns(result, panel['skip_columns'])
endif
if (has_key(panel, 'hide_header'))
if (panel['hide_header'])
let result = sw#hide_header(result)
endif
endif
wincmd b
if (has_key(panel, 'filetype'))
execute 'set filetype=' . panel['filetype']
else
execute 'set filetype=' . g:sw_default_right_panel_type
endif
break
endif
endfor
endif
wincmd b
call sw#session#set_buffer_variable('last_cmd', cmd)
setlocal modifiable
normal! ggdG
for line in result
put =line
endfor
normal! ggdd
setlocal nomodifiable
let pattern = '\v^.*-- AFTER(.*)$'
if cmd =~ pattern
let after = substitute(cmd, pattern, '\1', 'g')
execute after
endif
endfunction
" Adds a shortcut from a tab to the current buffer{{{2
function! s:add_shortcut(tab)
execute "nnoremap <buffer> <silent> " . a:tab['shortcut'] . " :call <SID>change_tab(\"" . substitute(a:tab['command'], '"', "\\\\\"", 'g') . "\", \"" . a:tab['shortcut'] . "\", \"" . a:tab['title'] . "\")<cr>"
return 1
endfunction
" Displays the tabs in the help buffer{{{2
function! s:display_tabs(tab)
if b:current_tab == ''
call sw#session#set_buffer_variable('current_tab', a:tab['shortcut'])
endif
if b:txt != ''
call sw#session#set_buffer_variable('txt', b:txt . ' | ')
endif
call sw#session#set_buffer_variable('txt', b:txt . a:tab['title'] . ' (' . a:tab['shortcut'] . ')')
return 1
endfunction
" Set the help buffer{{{2
function! s:set_info_buffer()
wincmd t
setlocal modifiable
normal! ggdG
put ='The current profile is ' . b:profile
call sw#session#set_buffer_variable('txt', '')
call s:iterate('s:display_tabs')
put =b:t1_shortcuts
put =b:txt
if b:current_tab != ''
call sw#session#set_buffer_variable('shortcut', b:current_tab)
call s:iterate('s:find_tab_by_shortcut')
if (exists('b:tab'))
put =b:t2_shortcuts
let txt = ''
for panel in b:tab['panels']
if txt != ''
let txt = txt . ' | '
endif
let txt = txt . panel['title'] . ' (' . panel['shortcut'] . ')'
endfor
put =txt
endif
endif
put =b:t3_shortcuts . ': Export (E) \| Open in new buffer (B)'
normal! ggdd
setlocal nomodifiable
endfunction
" Sets the objects initial state{{{2
""function! s:set_objects_buffer()
"" wincmd b
"" wincmd h
"" let b:object_tabs = []
"" let b:txt = ''
"" call s:iterate('s:display_tabs')
"" setlocal modifiable
"" normal! ggdG
"" "put =b:txt
"" normal! ggdd
"" setlocal nomodifiable
""endfunction
" Global functions{{{1
" Adds a tab{{{2
function! sw#dbexplorer#add_tab(profile, title, shortcut, command, panels)
if (!exists('g:extra_sw_tabs'))
let g:extra_sw_tabs = {}
endif
let obj = {'title': a:title, 'shortcut': a:shortcut, 'command': a:command, 'panels': a:panels}
if !has_key(g:extra_sw_tabs, a:profile)
let g:extra_sw_tabs[a:profile] = [obj]
else
call add(g:extra_sw_tabs[a:profile], obj)
endif
endfunction
" Add a panel to a tab{{{2
function! sw#dbexplorer#add_panel(profile, tab_shortcut, title, shortcut, command)
if (!exists('g:extra_panels'))
let g:extra_sw_panels = {}
endif
let obj = {'title': a:title, 'shortcut': a:shortcut, 'command': a:command}
if (!has_key(a:profile, g:extra_panels))
let g:extra_sw_panels[a:profile] = {}
endif
endfunction
" Hide the db explorer panel{{{2
function! sw#dbexplorer#hide_panel(...)
if a:0
let profile = a:1
else
if !exists('b:profile') || !exists('b:t1_shortcuts')
throw "You can only execute this command from a DBExplorer panel"
endif
let profile = b:profile
endif
let name = "__SQL__-" . profile
if !bufexists(name)
echoerr "There is no dbexplorer opened for " . profile
return
endif
execute "silent! bwipeout __SQL__-" . profile
execute "silent! bwipeout __Info__-" . profile
execute "silent! bwipeout __DBExplorer__-" . profile
endfunction
" Export the result panel as ods{{{2
function! sw#dbexplorer#export()
if (exists('b:last_cmd'))
call sw#export_ods(b:profile, b:last_cmd)
else
echoerr "The panel is empty!"
endif
endfunction
function! sw#dbexplorer#show_panel_no_profile(...)
let connection = ''
let i = 1
while i <= a:0
let cmd = "let arg = a:" . i
execute cmd
let connection = connection . ' ' . arg
let i = i + 1
endwhile
let profile = '__no__' . sw#generate_unique_id()
call sw#dbexplorer#show_panel(profile, connection)
endfunction
function! sw#dbexplorer#restore_from_session(...)
let connection = ''
if exists('b:connection')
let connection = b:connection
endif
wincmd t
call sw#session#init_section()
call sw#session#check()
call s:set_special_buffer(b:profile, connection)
call s:set_highlights()
wincmd b
call sw#session#init_section()
call sw#session#check()
call s:set_special_buffer(b:profile, connection)
wincmd h
call sw#session#init_section()
call sw#session#check()
call s:set_special_buffer(b:profile, connection)
call s:change_tab(b:first_tab['command'], b:first_tab['shortcut'], b:first_tab['title'])
endfunction
function! s:set_highlights()
highlight SWHighlights term=NONE cterm=NONE ctermbg=25 ctermfg=yellow gui=NONE guibg=#808080 guifg=yellow
highlight SWSelectedObject term=NONE cterm=NONE ctermbg=DarkGrey ctermfg=fg gui=NONE guibg=#808080 guifg=yellow
let id = matchadd('SWHighlights', b:profile)
let id = matchadd('SWHighlights', b:t1_shortcuts)
let id = matchadd('SWHighlights', b:t2_shortcuts)
let id = matchadd('SWHighlights', b:t3_shortcuts)
endfunction
" Shows the dbexplorer panel{{{2
function! sw#dbexplorer#show_panel(profile, ...)
let s_below = &splitbelow
set nosplitbelow
let name = "__SQL__-" . a:profile
if bufexists(name)
echoerr "There is already a dbexplorer opened for " . a:profile
return
endif
""if (g:sw_bufexplorer_new_tab)
"" tabnew
""endif
tabnew
let connection = ''
if (a:0)
let connection = a:1
endif
execute "badd " . name
execute "buffer " . name
call s:set_special_buffer(a:profile, connection)
nnoremap <buffer> <silent> E :call sw#dbexplorer#export()<cr>
nnoremap <buffer> <silent> B :call <SID>open_in_new_buffer()<cr>
execute "silent! split __Info__-" . a:profile
resize 7
"let id = matchadd('SWHighlights', '\v^([^\(]+\([A-Za-z]+\)( \| )?)+$')
call s:set_special_buffer(a:profile, connection)
call s:set_highlights()
wincmd b
execute "silent! vsplit __DBExplorer__-" . a:profile
call s:set_special_buffer(a:profile, connection)
vertical resize 60
""call s:set_objects_buffer()
call s:iterate('s:get_first_tab')
call s:change_tab(b:first_tab['command'], b:first_tab['shortcut'], b:first_tab['title'])
if s_below
set splitbelow
endif
endfunction
" Returns true if the current tab is a db explorer tab{{{2
function! sw#dbexplorer#is_db_explorer_tab()
let name = bufname('%')
return name =~ '\v^__Info__' || name =~ '\v^__DBExplorer__' || name =~ '\v^__SQL__'
endfunction
" Eliminates the first column of the buffer for the source code{{{2
function! sw#dbexplorer#fix_source_code()
setlocal modifiable
normal gg0G0x
setlocal nomodifiable
endfunction
" vim:fdm=marker
"============================================================================"
"
" Vim SQL Workbench/J Implementation
"
" Copyright (c) Cosmin Popescu
"
" Author: Cosmin Popescu <cosminadrianpopescu at gmail dot com>
" Version: 1.00 (2015-01-08)
" Requires: Vim 7
" License: GPL
"
" Description:
"
" Provides SQL database access to any DBMS supported by SQL Workbench/J. The
" only dependency is SQL Workbench/J. Also includes powefull intellisense
" autocomplete based on the current selected database
"
"============================================================================"
"let s:obj_parameters = [
" {'name': 'searchValues', 'prompt': 'Search terms: ', 'type': 'string', 'escape': 1},
" {'name': 'useRegex', 'prompt': 'Use regular expressions? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_regex},
" {'name': 'matchAll', 'prompt': 'Match all values? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_match_all},
" {'name': 'ignoreCase', 'prompt': 'Ignore case? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_ignore_case},
" {'name': 'types', 'prompt': 'Object types: ', 'type': 'string', 'default': g:sw_search_default_types, 'escape': 1},
" {'name': 'objects', 'prompt': 'Objects list', 'type': 'string', 'default': g:sw_search_default_objects}
"]
let s:obj_parameters = [{'name': 'searchValues', 'prompt': 'Search terms: ', 'type': 'string', 'escape': 1}, {'name': 'useRegex', 'prompt': 'Use regular expressions? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_regex}, {'name': 'matchAll', 'prompt': 'Match all values? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_match_all}, {'name': 'ignoreCase', 'prompt': 'Ignore case? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_ignore_case}, {'name': 'types', 'prompt': 'Object types: ', 'type': 'string', 'default': g:sw_search_default_types, 'escape': 1}, {'name': 'objects', 'prompt': 'Objects list: ', 'type': 'string', 'default': g:sw_search_default_objects}]
"let s:data_parameters = [
" {'name': 'searchValue', 'prompt': 'Search terms: ', 'type': 'string', 'escape': 1, 'highlight': 1},
" {'name': 'ignoreCase', 'prompt': 'Ignore case? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_ignore_case, 'highlight_case': 1},
" {'name': 'compareType', 'prompt': 'Possible values: equals | matches | startsWith | isNull. Compare type: ', 'type': 'select', 'default': g:sw_search_default_compare_types, 'options': ['equals', 'matches', 'startsWith', 'isNull']},
" {'name': 'tables', 'prompt': 'Tables list: ', 'type': 'string', 'default': g:sw_search_default_tables},
" {'name': 'types', 'prompt': 'Object types: ', 'type': 'string', 'default': g:sw_search_default_data_types, 'escape': 1},
" {'name': 'excludeTables', 'prompt': 'Tables to exclude: ', 'type': 'string', 'continue_on_null': 1},
" {'name': 'excludeLobs', 'prompt': 'Do you want to exclude lobs? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_exclude_lobs}
"]
let s:data_parameters = [{'name': 'searchValue', 'prompt': 'Search terms: ', 'type': 'string', 'escape': 1, 'highlight': 1}, {'name': 'ignoreCase', 'prompt': 'Ignore case? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_ignore_case, 'highlight_case': 1}, {'name': 'compareType', 'prompt': 'Possible values: equals | matches | startsWith | isNull. Compare type: ', 'type': 'select', 'default': g:sw_search_default_compare_types, 'options': ['equals', 'matches', 'startsWith', 'isNull']}, {'name': 'tables', 'prompt': 'Tables list: ', 'type': 'string', 'default': g:sw_search_default_tables}, {'name': 'types', 'prompt': 'Object types: ', 'type': 'string', 'default': g:sw_search_default_data_types, 'escape': 1}, {'name': 'excludeTables', 'prompt': 'Tables to exclude: ', 'type': 'string', 'continue_on_null': 1}, {'name': 'excludeLobs', 'prompt': 'Do you want to exclude lobs? [Y/N] ', 'type': 'boolean', 'default': g:sw_search_default_exclude_lobs}]
function! s:input_boolean(message, default_value)
let result = input(a:message, a:default_value)
if result == ''
return ''
endif
while !(result =~ '\v\c^(y|n)$')
let result = input(a:message, a:default_value)
if result == ''
return ''
endif
endwhile
if result =~ '\v\c^y$'
let result = 'true'
else
let result = 'false'
endif
return result
endfunction
function! sw#search#input_select_complete(a1, a2, a3)
if !exists('b:complete_options')
return []
endif
let result = []
for option in b:complete_options
if option =~ '^' . a:a1
call add(result, option)
endif
endfor
return result
endfunction
function! s:input_select(message, default_value, options)
call sw#session#set_buffer_variable('complete_options', a:options)
let result = input(a:message, a:default_value,'customlist,sw#search#input_select_complete')
call sw#session#unset_buffer_variable('complete_options')
return result
endfunction
function! sw#search#do(command, columns)
call sw#session#init_section()
if exists('b:feedback')
let feedback = b:feedback
call sw#session#unset_buffer_variable('feedback')
endif
let result = sw#execute_sql(b:profile, a:command, 0)
if exists('feedback')
call sw#session#set_buffer_variable('feedback', feedback)
endif
if a:columns != ''
let _c = split(a:columns, ',')
let columns = []
for column in _c
if column == 'NAME'
call add(columns, 0)
endif
if column == 'TYPE'
call add(columns, 1)
endif
if column == 'SOURCE'
call add(columns, 2)
endif
endfor
let i = 0
let hide = []
while i < 3
if index(columns, i) == -1
call add(hide, i)
endif
let i = i + 1
endwhile
if exists('b:resultsets')
call sw#session#unset_buffer_variable('resultsets')
endif
if exists('b:messages')
call sw#session#unset_buffer_variable('messages')
endif
if len(hide) > 0
let result = sw#hide_columns(result, hide)
endif
else
let _r = []
for line in result
if !(line =~ ':')
call add(_r, line)
endif
endfor
let result = _r
endif
if exists('b:max_results')
let name = "__SQLResult__-" . b:profile . '__' . b:unique_id
if (!bufexists(name))
let profile = b:profile
let s_below = &splitbelow
set splitbelow
execute "split " . name
call sw#session#init_section()
call sw#set_special_buffer(profile)
if !s_below
set nosplitbelow
endif
call sw#session#set_buffer_variable('state', 'resultsets')
endif
endif
let highlight = ''
if exists('b:highlight')
let highlight = b:highlight
call sw#session#unset_buffer_variable('highlight')
if exists('b:highlight_case')
let highlight = b:highlight_case . highlight
call sw#session#unset_buffer_variable('highlight_case')
endif
let highlight = '\V' . highlight
endif
wincmd b
if exists('b:match_id')
try
call matchdelete(b:match_id)
catch
endtry
call sw#session#unset_buffer_variable('match_id')
endif
setlocal modifiable
normal ggdG
let resultsets = []
for line in result
put =line
call add(resultsets, line)
endfor
if exists('b:state')
call sw#session#set_buffer_variable('resultsets', resultsets)
endif
normal ggdd
if highlight != ''
call sw#session#set_buffer_variable('match_id', matchadd('Search', highlight))
endif
setlocal nomodifiable
endfunction
function! sw#search#data_defaults(value)
if !exists('b:profile')
throw 'The search can be performed from a database explorer or an sql buffer.'
endif
let command = 'WbGrepData -searchValue="' . escape(a:value, '"') . '" -ignoreCase=' . g:sw_search_default_ignore_case . ' -compareType=' . g:sw_search_default_compare_types . ' -tables=' . g:sw_search_default_tables . ' -types="' . g:sw_search_default_data_types . '" -excludeTables=' . g:sw_search_default_exclude_tables . ' -excludeLobs=' . g:sw_search_default_exclude_lobs
call sw#session#set_buffer_variable('highlight', value)
call sw#session#set_buffer_variable('highlight_case', '')
if g:sw_search_default_ignore_case == 'Y'
call sw#session#set_buffer_variable('highlight_case', '\c')
endif
call sw#search#do(command, '')
endfunction
function! sw#search#object_defaults(values)
if !exists('b:profile')
throw 'The search can be performed from a database explorer or an sql buffer.'
endif
let command = 'WbGrepSource -searchValues="' . escape(a:values, '"') . '" -useRegex=' . g:sw_search_default_regex . ' -matchAll=' . g:sw_search_default_match_all . ' -ignoreCase=' . g:sw_search_default_ignore_case . ' -types="' . g:sw_search_default_types . '" -objects=' . g:sw_search_default_objects
call sw#search#do(command, g:sw_search_default_result_columns)
endfunction
function! s:get_search_parameters(v)
let result = ''
echo 'You can cancel at any time by returning an empty response at any question.'
for p in a:v
let default = ''
if has_key(p, 'default')
let default = p['default']
endif
if p['type'] == 'string'
let v = input(p['prompt'], default)
elseif p['type'] == 'boolean'
let v = s:input_boolean(p['prompt'], default)
elseif p['type'] == 'select'
let v = s:input_select(p['prompt'], default, p['options'])
endif
let cont = 0
if has_key(p, 'continue_on_null')
let cont = p['continue_on_null']
endif
if has_key(p, 'highlight')
call sw#session#set_buffer_variable('highlight', v)
endif
if !cont
if v == ''
return ''
endif
endif
if has_key(p, 'highlight_case')
if p['highlight_case']
call sw#session#set_buffer_variable('highlight_case', '')
else
call sw#session#set_buffer_variable('highlight_case', '\c')
endif
endif
if has_key(p, 'escape')
if p['escape']
let v = '"' . escape(v, '"') . '"'
endif
endif
let result = result . ' -' . p['name'] . '=' . v
endfor
return result
endfunction
function! sw#search#prepare(cmd, ...)
if !exists('b:profile')
throw 'The search can be performed from a database explorer or an sql buffer.'
endif
if !a:0
if a:cmd == 'WbGrepSource'
let command = a:cmd . s:get_search_parameters(s:obj_parameters)
else
let command = a:cmd . s:get_search_parameters(s:data_parameters)
endif
if command == a:cmd
return
endif
if a:cmd == 'WbGrepSource'
let columns = input('Available columns are: NAME,TYPE,SOURCE. Select columns to display: ', g:sw_search_default_result_columns)
else
let columns = ''
endif
else
let i = 1
let command = a:cmd
if a:cmd == 'WbGrepSource'
let columns = g:sw_search_default_result_columns
else
let columns = ''
endif
while i <= a:0
let cmd = "let arg = a:" . i
execute cmd
let command = command . ' -searchValues=' . arg
let i = i + 1
endwhile
endif
call sw#search#do(command, columns)
endfunction
function! sw#search#object(...)
let command = 'call sw#search#prepare("WbGrepSource"'
let i = 1
while i <= a:0
let cmd = "let arg = a:" . i
execute cmd
let command = command . ', "' . escape(arg, '"') . '"'
let i = i + 1
endwhile
let command = command . ")"
execute command
endfunction
function! sw#search#data(...)
let command = 'call sw#search#prepare("WbGrepData"'
let i = 1
while i <= a:0
let cmd = "let arg = a:" . i
execute cmd
let command = command . ', "' . escape(arg, '"') . '"'
let i = i + 1
endwhile
let command = command . ")"
execute command
endfunction
"============================================================================"
"
" Vim SQL Workbench/J Implementation
"
" Copyright (c) Cosmin Popescu
"
" Author: Cosmin Popescu <cosminadrianpopescu at gmail dot com>
" Version: 1.00 (2015-01-08)
" Requires: Vim 7
" License: GPL
"
" Description:
"
" Provides SQL database access to any DBMS supported by SQL Workbench/J. The
" only dependency is SQL Workbench/J. Also includes powefull intellisense
" autocomplete based on the current selected database
"
"============================================================================"
if !exists('g:Str_sw_session')
let g:Str_sw_session = ''
endif
if !exists('g:sw_session')
let g:sw_session = {}
endif
if !exists('g:Str_sw_autocommands')
let g:Str_sw_autocommands = ''
endif
if !exists('g:sw_autocommands')
let g:sw_autocommands = {}
endif
function! s:key_name(...)
if a:0
let name = a:1
else
let name = bufname('%')
endif
if name =~ '\v^__'
return name
endif
return fnamemodify(name, ':p')
endfunction
function! sw#session#init_section(...)
if a:0
let name = s:key_name(a:1)
else
let name = s:key_name()
endif
if name != ''
if !has_key(g:sw_session, name)
let g:sw_session[name] = {}
endif
if !has_key(g:sw_autocommands, name)
let g:sw_autocommands[name] = {}
endif
endif
endfunction
function! sw#session#set_buffer_variable(var, value)
let cmd = "let b:" . a:var . " = a:value"
execute cmd
let g:sw_session[s:key_name()][a:var] = a:value
let g:Str_sw_session = string(g:sw_session)
endfunction
function! sw#session#autocommand(event, func)
let cmd = "autocmd " . a:event . " <buffer> " . "call " . a:func
execute cmd
let g:sw_autocommands[s:key_name()][a:event] = a:func
let g:Str_sw_autocommands = string(g:sw_autocommands)
endfunction
function! sw#session#unset_buffer_variable(var)
if has_key(g:sw_session[s:key_name()], a:var)
unlet g:sw_session[s:key_name()][a:var]
endif
if exists('b:' . a:var)
let cmd = "unlet b:" . a:var
execute cmd
endif
let g:Str_sw_session = string(g:sw_session)
endfunction
function! sw#session#sync()
if !exists("g:SessionLoad")
for buffer in keys(g:sw_session)
if !buffer_exists(buffer)
unlet g:sw_session[buffer]
unlet g:sw_autocommands[buffer]
endif
endfor
let g:Str_sw_session = string(g:sw_session)
let g:Str_sw_autocommands = string(g:sw_autocommands)
endif
endfunction
function! sw#session#restore()
let g:sw_session = {}
let g:sw_autocommands = {}
if exists('g:Str_sw_session')
if g:Str_sw_session != ''
let cmd = "let g:sw_session = " . g:Str_sw_session
execute cmd
endif
endif
if exists('g:Str_sw_autocommands')
if g:Str_sw_autocommands != ''
let cmd = "let g:sw_autocommands = " . g:Str_sw_autocommands
execute cmd
endif
endif
if exists('g:Str_sw_autocomplete_default_tables')
if g:Str_sw_autocomplete_default_tables != ''
execute "let g:sw_autocomplete_default_tables = " . g:Str_sw_autocomplete_default_tables
endif
endif
if exists('g:Str_sw_autocomplete_default_procs')
if g:Str_sw_autocomplete_default_procs != ''
execute "let g:sw_autocomplete_default_procs = " . g:Str_sw_autocomplete_default_procs
endif
endif
let g:session_restored = 1
endfunction
function! sw#session#reload_from_cache()
let name = s:key_name()
if has_key(g:sw_session, name)
for k in keys(g:sw_session[name])
let cmd = "let b:" . k . " = g:sw_session[name][k]"
execute cmd
endfor
endif
if has_key(g:sw_autocommands, name)
for event in keys(g:sw_autocommands[name])
let cmd = "autocmd " . event . " <buffer> call " . g:sw_autocommands[name][event]
execute cmd
endfor
endif
let b:restored_from_session = 1
endfunction
function! sw#session#check()
let name = s:key_name()
if has_key(g:sw_session, name) && !exists('b:profile')
call sw#session#reload_from_cache()
endif
endfunction
function! sw#session#restore_dbexplorer()
call sw#session#check()
call sw#dbexplorer#restore_from_session()
endfunction
function! sw#session#restore_sqlbuffer()
call sw#session#check()
wincmd b
call sw#session#check()
wincmd t
endfunction
"============================================================================"
"
" Vim SQL Workbench/J Implementation
"
" Copyright (c) Cosmin Popescu
"
" Author: Cosmin Popescu <cosminadrianpopescu at gmail dot com>
" Version: 1.00 (2015-01-08)
" Requires: Vim 7
" License: GPL
"
" Description:
"
" Provides SQL database access to any DBMS supported by SQL Workbench/J. The
" only dependency is SQL Workbench/J. Also includes powefull intellisense
" autocomplete based on the current selected database
"
"============================================================================"
let s:pattern_resultset_start = '\v^([\-]+\+)+([\-]*)$'
let s:pattern_empty_line = '\v^[\r \s\t]*$'
let s:script_path = expand('<sfile>:p:h') . '/../../'
function! s:check_sql_buffer()
if (!exists('b:profile'))
throw "The current buffer is not an SQL Workbench buffer. Open it using the SWOpenSQL command."
endif
endfunction
function! s:set_shortcuts(default_var, path)
if a:default_var == 'default'
let cmd = "so " . s:script_path . a:path
execute cmd
else
so a:default_var
endif
endfunction
function! sw#sqlwindow#set_statement_shortcuts()
call s:set_shortcuts(g:sw_shortcuts_sql_buffer_statement, "resources/shortcuts_sql_buffer_statement.vim")
call sw#sqlwindow#check_hidden_results()
endfunction
function! sw#sqlwindow#set_results_shortcuts()
call s:set_shortcuts(g:sw_shortcuts_sql_results, "resources/shortcuts_sql_results.vim")
endfunction
function! sw#sqlwindow#hide_results()
let i = 1
let pagen = tabpagenr()
while i <= bufnr('$')
if (bufexists(i))
if tabpagenr() == pagen
endif
endif
let i = i + 1
endwhile
endfunction
function! s:do_open_buffer()
call sw#session#set_buffer_variable('display_result_as', g:sw_display_result_as)
call sw#session#set_buffer_variable('max_results', g:sw_max_results)
call sw#session#set_buffer_variable('delimiter', g:sw_delimiter)
call sw#session#set_buffer_variable('abort_on_errors', g:sw_abort_on_errors)
call sw#session#set_buffer_variable('feedback', g:sw_feedback)
call sw#session#set_buffer_variable('unique_id', sw#generate_unique_id())
call sw#session#autocommand('BufEnter', 'sw#sqlwindow#set_statement_shortcuts()')
call sw#sqlwindow#set_statement_shortcuts()
""normal gg
""put ='-- Current profile: ' . b:profile
endfunction
function! sw#sqlwindow#open_buffer(profile, file, command)
execute a:command . " " . a:file
call sw#session#init_section()
call sw#session#set_buffer_variable('profile', a:profile)
call s:do_open_buffer()
endfunction
function! sw#sqlwindow#open_buffer_no_profile(...)
if !a:0
throw "You need to supply at least the file name"
endif
call sw#session#init_section(a:1)
execute g:sw_sqlopen_command . " " . a:1
let i = 2
call sw#session#set_buffer_variable('connection', '')
while i <= a:0
let cmd = "let arg = a:" . i
execute cmd
call sw#session#set_buffer_variable('connection', b:connection . ' ' . arg)
let i = i + 1
endwhile
call sw#session#set_buffer_variable('profile', '__no__' . sw#generate_unique_id())
call s:do_open_buffer()
endfunction
function! sw#sqlwindow#display_options(a1, a2, a3)
let options = ['tab', 'record']
let result = []
for option in options
if option =~ '^' . a:a1
call add(result, option)
endif
endfor
return result
endfunction
function! sw#sqlwindow#set_display(what)
call s:check_sql_buffer()
call sw#session#set_buffer_variable('display_result_as', a:what)
endfunction
function! sw#sqlwindow#set_max_rows(n)
call s:check_sql_buffer()
call sw#session#set_buffer_variable('max_results', a:n)
endfunction
function! sw#sqlwindow#set_abort_on_errors(what)
call s:check_sql_buffer()
call sw#session#set_buffer_variable('abort_on_errors', a:what)
endfunction
function! sw#sqlwindow#set_delimiter(new_del)
call s:check_sql_buffer()
call sw#session#set_buffer_variable('delimiter', a:new_del)
endfunction
function! sw#sqlwindow#set_feedback(what)
call s:check_sql_buffer()
call sw#session#set_buffer_variable('feedback', a:what)
endfunction
function! sw#sqlwindow#export_last()
call sw#export_ods(b:profile, g:sw_last_sql_query)
endfunction
function! sw#sqlwindow#extract_current_sql(...)
let lines = getbufline(bufname(bufnr('.')), 1, '$')
let pos = getpos('.')
let n = pos[2] - 2
let m = n + 1
let i = pos[1] - 1
if n < 0
let lines[i] = '#CURSOR#' . lines[i]
else
let cmd = 'let lines[' . i . '] = lines[' . i . '][0:' . n . '] . "#CURSOR#" . lines[' . i . '][' . m . ':]'
execute cmd
endif
let s = ''
for line in lines
let s = s . line . "\n"
endfor
let sqls = sw#sql_split(s, b:delimiter)
for sql in sqls
if sql =~ '#CURSOR#'
if (!a:0 || (a:0 && !a:1))
let sql = substitute(sql, '#CURSOR#', '', 'g')
endif
return sql
endif
endfor
throw "Could not identifiy the current query"
return ""
endfunction
function! sw#sqlwindow#extract_selected_sql()
let z_save = @z
normal gv"zy
let sql = @z
let @z = z_save
return sql
endfunction
function! sw#sqlwindow#extract_all_sql()
let pos = getpos('.')
let z_save = @z
normal ggVG"zy
let sql = @z
let @z = z_save
call setpos('.', pos)
return sql
endfunction
function! sw#sqlwindow#toggle_messages()
if (!exists('b:messages') || !(exists('b:resultsets')))
return
endif
if b:state != 'resultsets' && b:state != 'messages'
return
endif
wincmd b
if b:state == 'resultsets'
call sw#session#set_buffer_variable('position', getpos('.'))
endif
setlocal modifiable
normal ggdG
if b:state == 'messages'
call s:display_resultsets()
elseif b:state == 'resultsets'
call sw#session#set_buffer_variable('state', 'messages')
for line in b:messages
put =line
endfor
endif
normal ggdd
setlocal nomodifiable
if (exists('b:position') && b:state == 'resultsets')
call setpos('.', b:position)
endif
endfunction
function! sw#sqlwindow#toggle_display()
if (!exists('b:resultsets') || !exists('b:state'))
return
endif
if b:state == 'form'
setlocal modifiable
normal ggdG
call s:display_resultsets()
normal ggdd
setlocal nomodifiable
if (exists('b:position'))
call setpos('.', b:position)
endif
return
endif
if b:state != 'resultsets'
return
endif
let line = line('.')
if (line <= 3 || getline('.') =~ s:pattern_empty_line || getline('.') == '')
throw "You have to be on a row in a resultset"
endif
let row_limits = s:get_row_limits()
call s:display_as_form(row_limits)
call sw#session#set_buffer_variable('state', 'form')
endfunction
function! s:display_as_form(row_limits)
let resultset_start = s:get_resultset_start()
call sw#session#set_buffer_variable('position', getpos('.'))
let _columns = split(b:resultsets[resultset_start - 2], '|')
let s_len = 0
let columns = []
for column in _columns
let column = substitute(column, '\v^[ ]?([^ ]+)[ ]+$', '\1', 'g')
call add(columns, column)
if strlen(column) > s_len
let s_len = strlen(column) + 1
endif
endfor
let lines = []
let n = 0
let k = 0
for column in columns
let line = column
let i = strlen(line)
while i < s_len
let line = line . ' '
let i = i + 1
endwhile
let line = line . ': '
if column == columns[len(columns) - 1]
let m = n + strlen(b:resultsets[a:row_limits[0] - 1]) - n
else
let m = n + strlen(_columns[k]) - 1
if (k > 0)
let m = m - 1
endif
endif
let cmd = "let line = line . b:resultsets[a:row_limits[0] - 1][" . n . ":" . m . "]"
execute cmd
let i = a:row_limits[0] + 1
while i <= a:row_limits[1]
let cmd = "let txt = b:resultsets[i - 1][" . n . ":" . m . "]"
execute cmd
if !(txt =~ s:pattern_empty_line)
call add(lines, line)
let line = ''
let j = 0
while j < s_len
let line = line . ' '
let j = j + 1
endwhile
let line = line . ': '
let line = line . txt
endif
let i = i + 1
endwhile
let n = m + 3
let k = k + 1
let line = substitute(line, '\v^([^:]+):[ ]*([0-9]+)[ ]*$', '\1: \2', 'g')
call add(lines, line)
endfor
setlocal modifiable
normal ggdG
for line in lines
put =line
endfor
normal ggdd
setlocal modifiable
endfunction
function! s:get_resultset_start()
let resultset_start = line('.')
while resultset_start > 1
if getline(resultset_start) =~ s:pattern_resultset_start
break
endif
let resultset_start = resultset_start - 1
endwhile
if (resultset_start == 1)
throw "Could not indentifiy the resultset"
endif
return resultset_start
endfunction
function! s:get_row_limits()
let resultset_start = s:get_resultset_start()
let row_start = line('.')
let row_end = line('.') + 1
let columns = split(b:resultsets[resultset_start - 2], '|')
while (row_start > resultset_start)
let n = 0
let line = b:resultsets[row_start - 1]
let stop = 0
for column in columns
if line[n + strlen(column)] == '|'
let stop = 1
break
endif
let n = n + strlen(column) + 1
endfor
if (stop)
break
endif
if line =~ s:pattern_resultset_start
let row_start = row_start + 1
break
endif
let row_start = row_start - 1
endwhile
while (row_end < len(b:resultsets))
let n = 0
let line = b:resultsets[row_end - 1]
let stop = 0
for column in columns
if line[n + strlen(column)] == '|'
let stop = 1
break
endif
let n = n + strlen(column) + 1
endfor
if (stop)
let row_end = row_end - 1
break
endif
if (line =~ s:pattern_empty_line || line == '')
let row_end = row_end - 1
break
endif
let row_end = row_end + 1
endwhile
return [row_start, row_end]
endfunction
function! s:display_resultsets()
for line in b:resultsets
put =line
endfor
call sw#session#set_buffer_variable('state', 'resultsets')
endfunction
function! sw#sqlwindow#execute_sql(sql)
let w:auto_added1 = "-- auto\n"
let w:auto_added2 = "-- end auto\n"
call s:check_sql_buffer()
let _sql = a:sql
if (b:display_result_as != 'tab')
let _sql = w:auto_added1 . 'WbDisplay ' . b:display_result_as . "\n" . b:delimiter . "\n" . w:auto_added2 . _sql
endif
if (b:max_results != 0)
let _sql = w:auto_added1 . 'set maxrows = ' . b:max_results . "\n" . b:delimiter . "\n" . w:auto_added2 . _sql
endif
let result = sw#execute_sql(b:profile, _sql, 0)
let uid = b:unique_id
let name = "__SQLResult__-" . b:profile . '__' . b:unique_id
let profile = b:profile
if (bufexists(name))
wincmd b
setlocal modifiable
normal ggdG
else
let s_below = &splitbelow
set splitbelow
execute "split " . name
call sw#session#init_section()
call sw#set_special_buffer(profile)
call sw#sqlwindow#set_results_shortcuts()
call sw#session#set_buffer_variable('r_unique_id', uid)
call sw#session#autocommand('BufEnter', 'sw#sqlwindow#set_results_shortcuts()')
setlocal modifiable
if !s_below
set nosplitbelow
endif
endif
if exists('b:messages')
call sw#session#unset_buffer_variable('messages')
endif
if exists('b:resultsets')
call sw#session#unset_buffer_variable('resultsets')
endif
call sw#session#set_buffer_variable('messages', [])
call sw#session#set_buffer_variable('resultsets', [])
let i = 0
let n = -1
let mode = 'message'
let pattern = '\v\c^\(([0-9]+) row[s]?\)$'
while i < len(result)
if (i + 1 < len(result))
if result[i + 1] =~ s:pattern_resultset_start
let mode = 'resultset'
let n = len(b:resultsets)
call add(b:resultsets, '')
endif
endif
if (mode == 'resultset' && (result[i] =~ s:pattern_empty_line || result[i] == ''))
let mode = 'message'
call add(b:resultsets, '')
endif
if (mode == 'resultset')
call add(b:resultsets, result[i])
elseif mode == 'message'
call add(b:messages, substitute(result[i], "\r", '', 'g'))
if result[i] =~ pattern
if (n != -1)
let rows = substitute(result[i], pattern, '\1', 'g')
let b:resultsets[n] = 'Query returned ' . rows . ' rows'
call sw#session#set_buffer_variable('resultsets', b:resultsets)
let n = -1
endif
endif
endif
let i = i + 1
endwhile
if len(b:resultsets) > 0
call s:display_resultsets()
else
for line in b:messages
put =line
endfor
call sw#session#set_buffer_variable('state', 'messages')
call sw#session#unset_buffer_variable('resultsets')
endif
normal ggdd
setlocal nomodifiable
wincmd t
endfunction
function! sw#sqlwindow#get_object_info()
if (!exists('b:profile'))
return
endif
let obj = expand('<cword>')
let sql = "desc " . obj
wincmd t
call sw#sqlwindow#execute_sql(sql)
endfunction
function! s:get_resultset_name()
if exists('b:profile') && exists('b:unique_id')
return '__SQLResult__-' . b:profile . '__' . b:unique_id
endif
return ''
endfunction
function! sw#sqlwindow#close_all_result_sets()
if bufname('%') =~ '\v__SQLResult__'
return
endif
if exists('g:sw_session')
let name = bufname('%')
let rs_name = ''
if exists('b:profile')
let rs_name = s:get_resultset_name()
endif
for k in keys(g:sw_session)
if k =~ '\v^__SQLResult__' && k != rs_name
if bufwinnr(k) != -1
call sw#goto_window(k)
call sw#session#set_buffer_variable('hidden', 1)
hide
call sw#goto_window(name)
endif
endif
endfor
endif
endfunction
function! sw#sqlwindow#check_hidden_results()
if exists('g:sw_session')
let name = '__SQLResult__-' . b:profile . '__' . b:unique_id
if bufwinnr(name) != -1
return
endif
if has_key(g:sw_session, name)
if has_key(g:sw_session[name], 'hidden')
if g:sw_session[name]['hidden']
let s_below = &splitbelow
set splitbelow
execute "split " . name
call sw#session#reload_from_cache()
call sw#session#unset_buffer_variable('hidden')
call sw#set_special_buffer(b:profile)
call sw#sqlwindow#set_results_shortcuts()
call sw#session#autocommand('BufEnter', 'sw#sqlwindow#set_results_shortcuts()')
setlocal modifiable
if !s_below
set nosplitbelow
endif
if b:state == 'messages'
for line in b:messages
put =line
endfor
else
call s:display_resultsets()
endif
normal ggdd
setlocal nomodifiable
wincmd t
endif
endif
endif
endif
endfunction
function! sw#sqlwindow#get_object_source()
if (!exists('b:profile'))
return
endif
let obj = expand('<cword>')
let sql = 'WbGrepSource -searchValues="' . obj . '" -objects=' . obj . ' -types=* -useRegex=true;'
wincmd t
call sw#sqlwindow#execute_sql(sql)
endfunction
此差异已折叠。
SWDbExplore sw.txt /*SWDbExplore*
SWDbExplorerClose sw.txt /*SWDbExplorerClose*
SWDbExplorerDirect sw.txt /*SWDbExplorerDirect*
SWDbExplorerRestore sw.txt /*SWDbExplorerRestore*
SWSearchData sw.txt /*SWSearchData*
SWSearchDataAdvanced sw.txt /*SWSearchDataAdvanced*
SWSearchDataDefaults sw.txt /*SWSearchDataDefaults*
SWSearchObject sw.txt /*SWSearchObject*
SWSearchObjectAdvanced sw.txt /*SWSearchObjectAdvanced*
SWSearchObjectDefaults sw.txt /*SWSearchObjectDefaults*
SWSqlAbortOnErrors sw.txt /*SWSqlAbortOnErrors*
SWSqlAutocomplete sw.txt /*SWSqlAutocomplete*
SWSqlAutocompleteSetDefault sw.txt /*SWSqlAutocompleteSetDefault*
SWSqlAutocompleteWithDefault sw.txt /*SWSqlAutocompleteWithDefault*
SWSqlBufferAddProfile sw.txt /*SWSqlBufferAddProfile*
SWSqlBufferRestore sw.txt /*SWSqlBufferRestore*
SWSqlDelimiter sw.txt /*SWSqlDelimiter*
SWSqlDisplayResultsAs sw.txt /*SWSqlDisplayResultsAs*
SWSqlExecuteAll sw.txt /*SWSqlExecuteAll*
SWSqlExecuteCurrent sw.txt /*SWSqlExecuteCurrent*
SWSqlExecuteSelected sw.txt /*SWSqlExecuteSelected*
SWSqlExport sw.txt /*SWSqlExport*
SWSqlMaxResults sw.txt /*SWSqlMaxResults*
SWSqlObjectInfo sw.txt /*SWSqlObjectInfo*
SWSqlObjectSource sw.txt /*SWSqlObjectSource*
SWSqlOpen sw.txt /*SWSqlOpen*
SWSqlOpenDirect sw.txt /*SWSqlOpenDirect*
SWSqlShowFeedback sw.txt /*SWSqlShowFeedback*
SWSqlToggleFormDisplay sw.txt /*SWSqlToggleFormDisplay*
SWSqlToggleMessages sw.txt /*SWSqlToggleMessages*
sw sw.txt /*sw*
sw-commands sw.txt /*sw-commands*
sw-connecting sw.txt /*sw-connecting*
sw-dbexplorer sw.txt /*sw-dbexplorer*
sw-export sw.txt /*sw-export*
sw-missing-features sw.txt /*sw-missing-features*
sw-requirements sw.txt /*sw-requirements*
sw-search sw.txt /*sw-search*
sw-sessions sw.txt /*sw-sessions*
sw-settings sw.txt /*sw-settings*
sw-sqlbuffer sw.txt /*sw-sqlbuffer*
vim-sql-workbench sw.txt /*vim-sql-workbench*
"============================================================================"
"
" Vim SQL Workbench/J Implementation
"
" Copyright (c) Cosmin Popescu
"
" Author: Cosmin Popescu <cosminadrianpopescu at gmail dot com>
" Version: 1.00 (2015-01-08)
" Requires: Vim 7
" License: GPL
"
" Description:
"
" Provides SQL database access to any DBMS supported by SQL Workbench/J. The
" only dependency is SQL Workbench/J. Also includes powefull intellisense
" autocomplete based on the current selected database
"
"============================================================================"
if exists('g:loaded_vim_sql_workbench') || v:version < 700
finish
endif
let g:loaded_vim_sql_workbench = 1
let g:session_restored = 0
if !exists('g:sw_search_default_regex')
let g:sw_search_default_regex = 'Y'
endif
if !exists('g:sw_search_default_match_all')
let g:sw_search_default_match_all = 'Y'
endif
if !exists('g:sw_search_default_ignore_case')
let g:sw_search_default_ignore_case = 'Y'
endif
if !exists('g:sw_search_default_types')
let g:sw_search_default_types = 'LOCAL TEMPORARY,TABLE,VIEW,FUNCTION,PROCEDURE,TRIGGER,SYNONYM'
endif
if !exists('g:sw_search_default_data_types')
let g:sw_search_default_data_types = 'TABLE,VIEW'
endif
if !exists('g:sw_search_default_exclude_lobs')
let g:sw_search_default_exclude_lobs = 'Y'
endif
if !exists('g:sw_search_default_tables')
let g:sw_search_default_tables = '%'
endif
if !exists('g:sw_search_default_exclude_tables')
let g:sw_search_default_exclude_tables = ''
endif
if !exists('g:sw_search_default_objects')
let g:sw_search_default_objects = '%'
endif
if !exists('g:sw_search_default_result_columns')
let g:sw_search_default_result_columns = ''
endif
if !exists('g:sw_search_default_compare_types')
let g:sw_search_default_compare_types = 'contains'
endif
if (!exists('g:sw_feedback'))
let g:sw_feedback = 1
endif
if (!exists('g:sw_abort_on_errors'))
let g:sw_abort_on_errors = 1
endif
if (!exists('g:sw_display_result_as'))
let g:sw_display_result_as = 'tab'
endif
if (!exists('g:sw_max_results'))
let g:sw_max_results = 0
endif
if (!exists('g:sw_delimiter'))
let g:sw_delimiter = ';'
endif
if !exists('g:sw_sqlopen_command')
let g:sw_sqlopen_command = 'e'
endif
if (!exists('g:sw_default_right_panel_type'))
let g:sw_default_right_panel_type = 'txt'
endif
if (!exists('g:sw_show_shell_output'))
let g:sw_show_shell_output = 0
endif
if (!exists('g:sw_open_export'))
let g:sw_open_export = 'soffice'
endif
if (!exists('g:sw_show_command'))
let g:sw_show_command = 0
endif
if (!exists('g:sw_exe'))
let g:sw_exe = 'sqlwbconsole.sh'
endif
if (!exists('g:sw_tmp'))
let g:sw_tmp = '/tmp'
endif
if !exists('g:sw_bufexplorer_new_tab')
let g:sw_bufexplorer_new_tab = 1
endif
if !exists('g:sw_bufexplorer_left_extratabs')
let g:sw_bufexplorer_left_extratabs = []
endif
if !exists('g:sw_bufexplorer_right_extratabs')
let g:sw_bufexplorer_right_extratabs = []
endif
if !exists('g:sw_shortcuts_sql_buffer_statement')
let g:sw_shortcuts_sql_buffer_statement = 'default'
endif
if !exists('g:sw_shortcuts_sql_results')
let g:sw_shortcuts_sql_results = 'default'
endif
if (!exists('g:extra_sw_tabs'))
let g:extra_sw_tabs = {}
endif
let g:sw_instance_id = strftime('%s')
if !exists('g:sw_dbexplorer_panel')
let file = expand('<sfile>:p:h') . '/../resources/dbexplorer.vim'
execute "so " . file
else
execute "so " . g:sw_dbexplorer_panel
endif
for _profile in items(g:extra_sw_tabs)
let profile = _profile[0]
let tabs = _profile[1]
if (!has_key(g:SW_Tabs, profile))
let g:SW_Tabs[profile] = []
endif
for tab in tabs
call add(g:SW_Tabs[profile], tab)
endfor
endfor
command! -nargs=1 -complete=customlist,sw#autocomplete_profile SWDbExplorer call sw#dbexplorer#show_panel(<f-args>)
command! -nargs=+ SWDbExplorerDirect call sw#dbexplorer#show_panel_no_profile(<f-args>)
command! -nargs=? SWDbExplorerClose call sw#dbexplorer#hide_panel(<f-args>)
command! SWDbExplorerRestore call sw#session#restore_dbexplorer()
command! -nargs=1 -complete=customlist,sw#autocomplete_profile SWSqlBufferAddProfile call sw#sqlwindow#open_buffer(<f-args>, bufname('%'), 'e')
command! -nargs=+ -complete=customlist,sw#autocomplete_profile_for_buffer SWSqlOpen call sw#sqlwindow#open_buffer(<f-args>, g:sw_sqlopen_command)
command! -nargs=+ -complete=file SWSqlOpenDirect call sw#sqlwindow#open_buffer_no_profile(<f-args>)
command! SWSqlExecuteCurrent call sw#sqlwindow#execute_sql(sw#sqlwindow#extract_current_sql())
command! SWSqlExecuteSelected call sw#sqlwindow#execute_sql(sw#sqlwindow#extract_selected_sql())
command! SWSqlExecuteAll call sw#sqlwindow#execute_sql(sw#sqlwindow#extract_all_sql())
command! -nargs=1 -complete=customlist,sw#sqlwindow#display_options SWSqlDisplayResultsAs call sw#sqlwindow#set_display(<f-args>)
command! -nargs=1 SWSqlMaxResults call sw#sqlwindow#set_max_rows(<f-args>)
command! -nargs=1 SWSqlDelimiter call sw#sqlwindow#set_delimiter(<f-args>)
command! -nargs=1 SWSqlAbortOnErrors call sw#sqlwindow#set_abort_on_errors(<f-args>)
command! -nargs=1 SWSqlShowFeedback call sw#sqlwindow#set_feedback(<f-args>)
command! SWSqlToggleMessages call sw#sqlwindow#toggle_messages()
command! SWSqlToggleFormDisplay call sw#sqlwindow#toggle_display()
command! SWSqlObjectInfo call sw#sqlwindow#get_object_info()
command! SWSqlObjectSource call sw#sqlwindow#get_object_source()
command! SWSqlExport call sw#sqlwindow#export_last()
command! -nargs=+ SWSearchObject call sw#search#object(<f-args>)
command! SWSearchObjectAdvanced call sw#search#object()
command! -nargs=1 SWSearchObjectDefaults call sw#search#object_defaults(<f-args>)
command! -nargs=+ SWSearchData call sw#search#data(<f-args>)
command! SWSearchDataAdvanced call sw#search#data()
command! -nargs=1 SWSearchDataDefaults call sw#search#data_defaults(<f-args>)
command! SWSqlAutocomplete call sw#autocomplete#cache()
command! SWSqlAutocompleteSetDefault call sw#autocomplete#set_cache_default()
command! SWSqlAutocompleteWithDefault setlocal omnifunc=sw#autocomplete#perform
command! SWSqlBufferRestore call sw#session#restore_sqlbuffer()
augroup sw
autocmd sw BufDelete,BufWipeout * call sw#session#sync()
autocmd sw SessionLoadPost * call sw#session#restore()
autocmd sw BufEnter * call sw#sqlwindow#close_all_result_sets()
""autocmd sw BufEnter * call sw#session#check()
""autocmd sw TabEnter * call sw#dbexplorer#restore_from_session()
let sw_columns = {'title': 'Columns', 'shortcut': 'C', 'command': 'desc %object%;'}
let sw_sql_source = {'title': 'SQL Source', 'shortcut': 'S', 'command': 'WbGrepSource -searchValues="%object%" -objects=%object% -types=* -useRegex=true; -- AFTERcall sw#dbexplorer#fix_source_code()', 'skip_columns': [0, 1], 'hide_header': 1, 'filetype': 'sql'}
let sw_data = {'title': 'Data', 'shortcut': 'D', 'command': 'set maxrows=100; select * from %object%;'}
let sw_indexes = {'title': 'Indexes', 'shortcut': 'I', 'command': 'WbListIndexes -tableName=%object%;'}
let sw_referenced_by = {'title': 'Referenced by', 'shortcut': 'R', 'command': 'WbGrepSource -searchValues="references %object%" -types=TABLE -useRegex=false;', 'skip_columns': [2]}
let objects = {'title': 'Objects', 'shortcut': 'O', 'command': 'WbList -objects=% -types=SYNONYM,SEQUENCE,TABLE,TYPE,VIEW', 'panels': [sw_columns, sw_sql_source, sw_data, sw_indexes, sw_referenced_by]}
let procedures = {'title': 'Procedures', 'shortcut': 'P', 'command': 'WbListProcs;', 'panels': [sw_sql_source]}
let triggers = {'title': 'Triggers', 'shortcut': 'T', 'command': 'WbListTriggers;', 'panels': [sw_sql_source]}
let g:SW_Tabs = {'*': [objects, procedures, triggers]}
execute "setlocal <M-i>=\ei"
execute "setlocal <M-m>=\em"
execute "setlocal <M-s>=\es"
nmap <buffer> <C-A> :SWSqlExecuteAll<cr>
vmap <buffer> <C-e> :<bs><bs><bs><bs><bs>SWSqlExecuteSelected<cr>
nmap <buffer> <C-@> :SWSqlExecuteCurrent<cr>
imap <buffer> <C-@> <Esc>:SWSqlExecuteCurrent<cr>
nmap <buffer> <M-i> :SWSqlObjectInfo<cr>
nmap <buffer> <M-s> :SWSqlObjectSource<cr>
nmap <buffer> <M-m> <C-w>b:SWSqlToggleMessages<cr><C-w>t
execute "setlocal <M-i>=\ei"
execute "setlocal <M-s>=\es"
execute "setlocal <M-m>=\em"
execute "setlocal <M-d>=\ed"
nmap <buffer> <C-A> :SWSqlExecuteAll<cr>
nmap <buffer> <M-i> :SWSqlObjectInfo<cr>
nmap <buffer> <M-s> :SWSqlObjectSource<cr>
nmap <buffer> <M-m> :SWSqlToggleMessages<cr>
nmap <buffer> <M-d> :SWSqlToggleFormDisplay<cr>
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output
encoding="iso-8859-15"
method="text"
omit-xml-declaration="yes"
doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN"
/>
<xsl:template match="/">
let g:_procedures = [<xsl:call-template name="procedures-list"/>]
</xsl:template>
<xsl:template name="procedures-list">
<xsl:for-each select="/wb-export/data/row-data/column-data[@index='0']">'<xsl:value-of select="."/>',</xsl:for-each>
</xsl:template>
</xsl:transform>
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output
encoding="iso-8859-15"
method="text"
omit-xml-declaration="yes"
doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN"
/>
<xsl:template match="/">
let g:tables = {<xsl:call-template name="table-definitions"/><xsl:call-template name="view-definitions"/>}
</xsl:template>
<xsl:template name="table-definitions">
<xsl:for-each select="/schema-report/table-def">'T#<xsl:value-of select="@name"/>': [<xsl:for-each select="column-def">'<xsl:value-of select="@name"/>',</xsl:for-each>],</xsl:for-each>
</xsl:template>
<xsl:template name="view-definitions">
<xsl:for-each select="/schema-report/view-def">'V#<xsl:value-of select="@name"/>': [<xsl:for-each select="column-def">'<xsl:value-of select="@name"/>',</xsl:for-each>],</xsl:for-each>
</xsl:template>
</xsl:transform>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册