提交 0a30f28f 编写于 作者: C Cosmin Popescu

version 3.3

上级 63b8da5a
......@@ -26,18 +26,19 @@ CONTENTS:
2. Connecting to a DBMS
3. The database explorer
4. The SQL Buffer
5. Searching
6. Exporting
7. Sessions
8. Variables
9. Commands
10. Settings
11. Screen shots
5. SQL commands
6. Searching
7. Exporting
8. Sessions
9. Variables
10. Commands
11. Settings
12. Screen shots
Requirements
========================================
* `Vim` compiled with `python` supported
* `Vim` compiled with `python` support
* `Python` installed on the machine
* `SQL Workbench/J` installed on the machine
* Optional: [`vim dispatch`](https://github.com/tpope/vim-dispatch) plugin
......@@ -478,6 +479,29 @@ shortcut.
Alternatively, you can execute the `WbDisplay` command. See
[here](http://www.sql-workbench.net/manual/console-mode.html) for more detail.
SQL commands
========================================
You can send a sql query to the DBMS from the vim command line using the
command `SWSqlExecuteNow`. The first parameter is the port of the server on
which to execute, and the next parameters are the sql query. Please note that
by default no results will be shown. If you want to see all that happened on
the server side, use the `SWSqlExecuteNowLastResult` command. This will show
you what happened with the last command sent from the vim command line.
This is useful if you want to put vim shortcuts for simple things. Like, for
example, you could have in your `vimrc`:
```
nnoremap <leader>t :SWSqlExecuteNow 5000 wbdisplay tab;<cr>
```
Then pressing `<leader>t` in normal mode, would set the display to tab for the
instance listening on port 5000.
*Note*: This command will not be recorded in `g:sw_last_sql_query`. The
delimiter is the `;`.
Searching
========================================
......@@ -600,50 +624,11 @@ By default, in `SQL Workbench`, the variables are enclosed between `$[` and
`]`. [These can be
changed](http://www.sql-workbench.net/manual/using-variables.html#access-variable).
By default, in `VIM SQL Workbench` the variable substitution is on. This
means, that when you send a query to the database, the plugin will search for
anything enclosed between the parameter prefix and suffix. Once a match is
found, if a value is defined with `SWVarSet` then the match is replaced with
this value. Please note that exactly the literal is replaced. No quotes are
added and no escaping is executed. If you want quotes, you need to add then in
the value.
If the variable is not defined using `SWVarSet` the plugin will ask for a
value. If you don't want this string to be replaced when the query is sent to
the database, then you can use an empty string as a value. If you want to send
to the database an empty string, then you have to set the value `''`.
If you set already a value for a variable, you can always change it by
executing again `SWVarSet`.
A variable can be unset using `SWVarUnset`.
If you don't want the plugin doing parameters substitution for a given buffer,
you can call `SWVarDisable`. You can always re-enable the parameter
substitution by calling `SWVarEnable`.
Example:
In your `workbench.settings` file:
```
workbench.sql.parameter.prefix=:
workbench.sql.parameter.suffix=
```
The sql query: `select * from table where d = '2015-01-01 00:00:00'`.
When launching this query, you will be asked for the value of the `00`
variable. You can just press `enter` and the `:00` will not be replace.
The sql query: `select * from table where name = :name`.
When launching this query, you will be asked for the value of the `name`
variable. If you enter `'Cosmin Popescu'`, the query sent to the DBMS will be
`select * from table where name = 'Cosmin Popescu'`. Please note that if you
just enter `Cosmin Popescu` (notice the missing quotes), the query sent to the
DBMS will be `select * from table where name = Cosmin Popescu` which will
obviously return an error.
You can use `WbVarSet` and `WbVarUnset` in a sql buffer. If you want the
system to ask for a value, then you can use the `$[?` form of a parameter.
Please note that in `VIM Sql Workbench` there is no difference between `?` and
`&`, since there is no way to get a list of vars in `vimscript` from `SQL
Workbench/J`
Commands
========================================
......@@ -719,6 +704,19 @@ call this command, the plugin will return it's source code, if the selected
word is an object in the database. Otherwise, it will return an empty result
set.
## SWSqlExecuteNow
*Parameters*:
* port: the port on which to execute the command
* sql: The query to be sent to the DBMS
Executes a query against the DBMS on the indicated port.
## SWSqlExecuteNowLastResult
Shows the communication with the server for the last `SWSqlExecuteNow` command.
## SWSqlExport
This command will export the last executed statement. Of course, if your last
......@@ -823,35 +821,6 @@ This command will restore the properties of the sql buffer following a vim
session restore. This includes the autocomplete intellisense of the buffer, if
this was active when `mksession` was executed.
## SWVarSet
*Parameters*:
* the variable name: the name of the variable to be set
* the value: the value that you want to set for this variable
If you want to set a string enclosed between the `SQL Workbench/J` parameters
suffix and prefix without being substituted, then set it to an empty string.
If you want to replace a parameter with an empty string, set the value of the
variable to `''`.
## SWVarUnset
Unsets a variable
## SWVarDisable
Disables the replacement of the parameters in the queries sent to the DBMS.
## SWVarEnable
Enables the replacement of the parameters in the queries sent to the DBMS
(enabled by default).
## SWVarList
Lists the parameters values
## SWServerStart
*Parameters*:
......@@ -946,6 +915,8 @@ and
in a db explorer will switch between the bottom panels
* `g:sw_autocomplete_cache_dir`: the location where the autocomplete
information is saved. You'll need to set it on Windows to work.
* `g:sw_switch_to_results_tab`: If true, then switch to the results buffer
after executting a query
## Database explorer settings
......
......@@ -470,6 +470,16 @@ function! sw#autocomplete#perform(findstart, base)
endfor
return sort(result, "sw#autocomplete#sort")
elseif b:autocomplete_type == 'wbconnect'
let profiles = sw#parse_profile_xml()
let result = []
for profile in profiles
if profile =~ '^' . a:base
call add(result, profile)
endif
endfor
return result
endif
return []
......@@ -496,6 +506,8 @@ function! s:get_sql_type(sql)
return 'proc'
elseif sql =~ '\v\c[\s \t\r]*delete'
return 'delete'
elseif sql =~ '\v\c^[\s \t\r]*wbconnect'
return 'wbconnect'
endif
return 'other'
......
"============================================================================"
"
" 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:last_result = ''
function! sw#cmdline#execute(wait_result, port, ...)
let sql = ''
let i = 1
while i <= a:0
execute "let sql .= ' ' . a:" . i
let i = i + 1
endwhile
let b:on_async_result = 'sw#sqlwindow#check_results'
let b:delimiter = ';'
let result = sw#server#execute_sql(sql, a:wait_result, a:port)
if result != ''
call s:process_results(result)
endif
endfunction
function! sw#cmdline#got_result()
let s:last_result = sw#server#fetch_result()
if results != ''
call s:process_results(result)
endif
endfunction
function! s:process_results(result)
let s:last_result = a:result
endfunction
function! sw#cmdline#show_last_result()
let s_below = &splitbelow
set splitbelow
execute "split __TMP__-" . sw#generate_unique_id()
call sw#set_special_buffer()
setlocal modifiable
if !s_below
set nosplitbelow
endif
let lines = split(s:last_result, "\n")
for line in lines
put =line
endfor
setlocal nomodifiable
endfunction
......@@ -94,19 +94,19 @@ import vim
import socket
import re
identifier = vim.eval('v:servername') + "#" + vim.eval('uid')
cmd = vim.eval('a:cmd') + "\n"
cmd = vim.eval('a:cmd')
port = int(vim.eval('port'))
type = vim.eval('a:type')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', port))
s.sendall(type)
packet = ''
packet += type
if vim.eval('a:wait_result') == '0':
s.sendall("!#identifier = " + identifier + "\n")
#end if
s.sendall(cmd)
if vim.eval('a:wait_result') == '0' or (vim.eval('a:wait_result') == '1' and type != 'RES' and type != 'DBE'):
s.sendall("!#end = 1\n")
packet += "!#identifier = " + identifier + "\n"
#end if
packet += cmd
packet = str(len(packet)) + "#" + packet
s.sendall(packet)
result = ''
if vim.eval('a:wait_result') == '1':
while 1:
......
......@@ -444,10 +444,15 @@ function! s:process_result(result)
normal ggdd
setlocal nomodifiable
let b = sw#find_buffer_by_unique_id(b:r_unique_id)
if b != ''
call sw#goto_window(b)
if !g:sw_switch_to_results_tab
let b = sw#find_buffer_by_unique_id(b:r_unique_id)
if b != ''
call sw#goto_window(b)
else
wincmd t
endif
endif
echomsg "Command completed"
endfunction
function! sw#sqlwindow#execute_sql(wait_result, sql)
......@@ -465,6 +470,7 @@ function! sw#sqlwindow#execute_sql(wait_result, sql)
let _sql = w:auto_added1 . 'wbvardef ' . var . ' = ' . value . "\n" . b:delimiter . "\n" . w:auto_added2 . _sql
endif
endfor
let _sql = substitute(_sql, g:parameters_pattern, g:sw_p_prefix . '\1' . g:sw_p_suffix, 'g')
endif
endif
let b:on_async_result = 'sw#sqlwindow#check_results'
......
......@@ -36,6 +36,11 @@ function! s:set_delimiters()
if !exists('g:sw_p_suffix')
let g:sw_p_suffix = '\]'
endif
let g:parameters_pattern = g:sw_p_prefix . '[?&]\([a-zA-Z_].\{\-\}\)' . g:sw_p_suffix
if g:sw_p_suffix == ''
let g:parameters_pattern = g:parameters_pattern . '\>'
endif
endif
endfunction
......@@ -87,43 +92,24 @@ endfunction
function! sw#variables#get(key)
call s:init_vars()
if has_key(b:variables, a:key)
return b:variables[a:key]
endif
let value = input('Please input the value for ' . a:key . ': ')
call sw#variables#set(a:key, value)
return value
endfunction
function! sw#variables#enable()
call sw#session#unset_buffer_variable('no_variables')
endfunction
function! sw#variables#disable()
call sw#session#set_buffer_variable('no_variables', 1)
endfunction
function! sw#variables#extract(sql)
call s:set_delimiters()
let pattern = g:sw_p_prefix . '\([a-zA-Z_].\{\-\}\)' . g:sw_p_suffix
if g:sw_p_suffix == ''
let pattern = pattern . '\>'
endif
let result = []
let n = 0
let i = match(a:sql, pattern, n)
let i = match(a:sql, g:parameters_pattern, n)
while i != -1
let l = matchlist(a:sql, pattern, n)
let s = substitute(l[0], '^' . g:sw_p_prefix, '', 'g')
if g:sw_p_suffix != ''
let s = substitute(s, g:sw_p_suffix . '$', '', 'g')
endif
let l = matchlist(a:sql, g:parameters_pattern, n)
let s = substitute(l[0], '^' . g:sw_p_prefix . '?', '', 'g')
let n = i + strlen(l[0]) + 1
if index(result, s) == -1
call add(result, s)
if index(result, l[1]) == -1
call add(result, l[1])
endif
let i = match(a:sql, pattern, n)
let i = match(a:sql, g:parameters_pattern, n)
endwhile
return result
endfunction
*vim-sql-workbench* SQL Workbench implementation in VIM
=============================================================================
Introduction *sw*
This is an implementation of [SQL Workbench/J](http://www.sql-workbench.net/)
in VIM. It works with any DBMS supported by `SQL Workbench/J` (PostgreSQL,
Oracle, SQLite, MySQL, SQL Server etc.). See the complete list
[here](http://www.sql-workbench.net/databases.html).
You can connect to any DBMS directly from VIM.
*Features:*
* database explorer (e.g.: table lists, procedures list, views list, triggers
list), extensible (you can have your own objects list)
* SQL buffer with performant autocomplete
* export any sql statement as `text`, `sqlinsert`, `sqlupdate`,
`sqldeleteinsert`, `xml`, `ods`, `html`, `json`
* search in object source
* search in table or views data
* asynchronous (you can execute any command asynchronous)
* fully customizable
CONTENTS:
1. Requirements
2. Connecting to a DBMS
3. The database explorer
4. The SQL Buffer
5. Searching
6. Exporting
7. Sessions
8. Variables
9. Commands
10. Settings
=============================================================================
Requirements *sw-requirements*
* `Vim` compiled with `python` supported
* `Python` installed on the machine
* `SQL Workbench/J` installed on the machine
* Optional: [`vim dispatch`](https://github.com/tpope/vim-dispatch) plugin
installed.
* `VIM` started in server mode
Of course you need VIM 7 or above. You also need [`SQL
Workbench/J`](http://www.sql-workbench.net/) installed on your computer. It is
platform independent, since `SQL Workbench` is written in JAVA and it should
work anywhere where VIM works.
Before getting started, you have to set the `g:sw_exe` vim variable. The
default value is `sqlwbconsole.sh`. If you have `SQL Workbench` in your PATH,
then you can skip this step. Otherwise, just set the value of the variable to
point to your `sqlwbconsole` file. If you are on Windows, it should be
`sqlwbconsole.exe`.
Also, if you are on Windows, you have to set the `g:sw_tmp` value in your
`vimrc`. The default value is `/tmp`.
The communication with the DBMS is made through the `sqlwbserver` script, that
you can find in the `resources` folder of the plugin. This is a `python`
script (hence the need to have `python` installed on the machine) and it will
spawn a `sqlwbconsole` instance in memory and then open a port on which will
listen for requests. After this, whenever you want to send a command to the
DBMS from `VIM`, the plugin will connect on the specified port, send the
command and retrieve the result which will be displayed in `VIM`.
=============================================================================
Connecting to a DBMS *sw-dbms-connect*
First of all, you need to open have a `sqlwbserver` running in memory. There
are two ways to run a server.
## Starting a server from vim
For this you need to have the `vim dispatch` plugin installed. If you want to
start the server from `vim`, you can call the command `SWServerStart` with the
port on which the server will listen. Also, you can choose a profile for the
new connection. If you don't choose a profile now, you will have to execute
[`WbConnect`](http://www.sql-workbench.net/manual/wb-commands.html#command-connect)
in order to connect to a database.
For example: `SWServerStart 5000`.
## Starting a server from command line
If you don't want or you can't install the `vim dispatch` plugin, you can
always start a server from command line. From your terminal, you need to
run the `resources/sqlwbserver` script. For a list of parameters you can do
`resources/sqlwbserver --help`. The following parameters are mandatory:
* The path to your `sqlwbconsole` executable (`-c`).
The default port on which the server will listen is 5000. You can change this
with the `-o` parameter.
Please note that a server handles only one `sqlwbconsole` instance, which is
not multi threading, so also the server is not multi-threading. Since a
command sent to a DBMS through `sqlwbconsole` cannot be interrupted, there is
no reason to have `sqlwbserver` working multi-threading. A new command will
have to wait anyway for the old one to finish.
If you want to have several connections to a database, you can open another
server (run again `sqlwbserver`) on another port. Of course, each server will
have it's own opened transactions. You cannot do an `update` on a port and a
`rollback` on the other port.
Though, when you open a database explorer (which requires a profile), a new
instance of `sqlwbconsole.sh` will be launched on a different thread. So any
commands for the database explorer will be run in parallel with any command
launched from any `vim` buffer connected to the same port.
*Example*:
```
`resources/sqlwbconsole -t /tmp -c /usr/bin/sqlwbconsole.sh -o 5000`
```
## Connecting a vim buffer
Once you have a server opened, you can connect any vim buffer to that server
using `SWSqlConnectToServer` command. Once a buffer is connected to a server,
you can send any command from that buffer to the DBMS using the
`SWSqlExecuteCurrent`, `SWSqlExecuteSelected` or `SWSqlExecuteAll` commands.
=============================================================================
The database explorer *sw-dbexplorer*
In order to open a database explorer, you need a profile.
You can create `SQL Workbench` profiles, either by using the `SQL Workbench`
GUI, like
[here](http://www.sql-workbench.net/manual/profiles.html#profile-intro),
either opening a sql buffer with `SWSqlConnectToServer` and then executing
`WbStoreProfile`.
Once you have your profiles created, you can use `SWDbExplorer` with the
desired profile as argument and you will connect to the database.
For example, `:SWDbExplorer 5000 myProfile` will open a database explorer
using the profile `myProfile` and the server which listens on the 5000 port.
The database explorer is composed from three parts: on the top, there is a
list of available shortcuts at any moment. On the bottom left, you will see
the list of objects in your database (the list of tables and views or the list
of procedures or the list of triggers etc.) and on the bottom right, you will
see the selected object desired properties. Like in the second or third screen
shot.
So, if you want to see the columns of a table, you will have to move the
cursor in the bottom left panel, go to the desired table and press 'C'. This
will display in the right panel the table columns, indices and triggers. If
you want to see its source code, you press 'S' and so on. For all the
available shortcuts, see the top panel.
The database explorer if fully customizable. You can use the existing one and
extend it or you can create your own from scratch.
_NOTE_: For `PostgreSQL`, you should use the as database explorer the
`resources/dbexplorer-postgresql.vim` file. This is because in `PostgreSQL`
the objects have to be prefixed by the schema. You can achieve this either by
just overwriting the `resources/dbexplorer.vim` file with the
`resources/dbexplorer-postgresql.vim` file, either by following the
documentation bellow.
## Creating a new database explorer from scratch
The database explorer is loaded from the `resources/dbexplorer.vim` file by
default. If you want to write your own, set the `g:sw_dbexplorer_panel`
variable to point to your own file and that file will be loaded. The file has
to be a `vimscript` file, since it's going to be sourced and it needs to set
the `g:SW_Tabs` variable. For an example, take a look at the
`resources/dbexplorer.vim` file.
The `g:SW_Tabs` has to be a vim dictionary. The keys are the profiles for
which the panel will be applied. `*` profile, means that the options appear on
all profiles. If you want to have separate database explorers for separate
profiles, you can create a key in the dictionary for each explorer.
*NOTE:* At the moment you can only create profiles for different profiles, not
for different DBMS.
The values for each profile, have to be a list which will contain all the
options for the left panel. For example, in the default one, the database
objects, triggers and procedures.
Each list of objects of this list is another dictionary, with the following
keys:
* `title` (the title which will be displayed in the top panel)
* `shortcut` (the shortcut to access it; please note that you can have several
letters)
* `command` (the sql command which will be executed when selecting the object)
* `panels` (a list of options accessible in the right panel for each selected
object in the left panel)
The panels are also a list of dictionaries. Each element of the list has the
following keys:
* `title` (the title which will be displayed in the top panel)
* `shortcut` (the shortcut which will be used to display it)
* `command` (the sql command which will be executed; please note that the sql
command should contain the `%object%` string, which will be replaced with
the name of the selected object)
Optional, the panels might contain the following keys:
* `skip_columns` (a list with the column indices from the result set that
should not be displayed)
* `hide_header` (if set and `true`, then the header of the result set will not
be displayed in the bottom right panel)
* `filetype` (if present, the bottom right panel `filetype` will be set
according when selecting an object in the left panel)
*NOTES*:
1. In the command that creates the left panel, the object for which you want
to select the informations in the right panel should always be on the first
column. The `%object%` string in the column will be replaced by it.
Alternatively, you can have `%n%` (n being a number from 0 to the number of
columns in the left panel). If you have `%n%`, this will be replaced by the
value of that column
2. The command can contain a comment in the format `-- AFTER` at the end.
Everything following "AFTER" word will be interpreted as a VIM command and
will be executed after the result has been displayed in the right panel. For
an example, see the SQL Source panel in the default database explorer vim
file (`resources/dbexplorer.vim`).
3. The shortcuts for the left panel (the list of objects) have to be unique.
They are used to identify the current option selected to be displayed, so
that the shourtcuts for the left panel are loaded according to the panels.
However, the shortcuts for the right panel can be the same from one list of
objects to the other. For example, you can have "O" as shortcut for objects
list and then for each object you can have "S" for showing the source code.
Then, you can have "P" for listing the procedures. Again, for each procedure
you can have again "S" as shortcut for listing the source code of a
procedure or for something else.
## Extending the default database explorer
If you are happy with the default options of the database explorer (which are
the same with the ones of `SQL Workbench/J`) but you just want to add your
own, you can do so by extending the default database explorer.
This is done by calling the `vimscript` function `sw#dbexplorer#add_tab`. The
function takes the following arguments:
* The profile (the profile for which the option should be active; it can be
`*` for all profiles)
* The title (this is the title that will appear on the top panel)
* The shortcut (this is the shortcut to access it)
* The command (this is the SQL command to be sent to the DBMS once this option
is selected)
* The list of panels (the list of properties to be displayed in the bottom
right split for each object from the list)
The list of panels is an array of dictionaries. Each dictionary has the same
keys as indicated in the previous section for the list of panels. For example,
if you want to add the database links for all the profiles, you have to add
this in your `vimrc`:
```
call sw#dbexplorer#add_tab('*', 'DB Links', 'L', 'select db_link, username,
created from user_db_links;', [{'title': 'Show the host', 'shortcut': 'H',
'command': "select host from user_db_links where db_link = '%object%'"}])
```
Now on all profiles, you will have an extra option. Every time when you click
"L" in normal mode, in the bottom left panel you will have a list of database
links from your schema. For each link, you can move the cursor on top of it
and click H. You will see in the right panel the source of the link.
Every time when "L" is clicked, `vim-sqlworkbench` sends the `select db_link,
username, created from user_db_links;` command to the DBMS. The result will be
a list of database links displayed in the bottom left panel. When you move
your cursor on top of one of this links and press "H", the plugin sends to
your DBMS `select host from user_db_links where db_link =
'<selected_link_name>';`. The result is displayed in the right panel.
=============================================================================
The SQL buffer *sw-sql-buffer*
The SQL buffer is a normal `vim` buffer from which you can send SQL commands
to your DBMS and in which you can use the omni completion (&lt;C-x&gt;&lt;C-o&gt;) to have
intellisense autocompletion.
You can connect an opened vim buffer to a server using the
`SWSqlConnectToServer <port>` command. Or, you can open a buffer which will be
directly connected to a server by specifying the path to the buffer after the
port. For example `SWSqlConnectToServer 5000 /tmp/dbms.sql`
Once in an sql buffer, you have several ways to execute commands against your
DBMS:
* execute the current SQL
* execute the selected statement
* execute all statements
All the shortcuts for these commands are fully customizable. But to do this,
you cannot just map the commands in `vimrc`. This is because these shortcuts
are mapped local to the sql buffer, or to the result sets buffer. If you want
to change the default shortcuts, you need to define the
`g:sw_shortcuts_sql_buffer_statement` variable or the
`g:sw_shortcuts_sql_results` variable. This variables should point each to a
`vimscript` file which will define the mappings.
The `g:sw_shortcuts_sql_buffer_statement` variable is used for the sql buffer
itself, while the `g:sw_shortcuts_sql_results` variable is used for the result
set buffer (see the 4th scren shot).
As soon as a SQL buffer is opened the shortcuts from the
`g:sw_shortcuts_sql_buffer_statement` will be mapped. If the variable is not
set, then the `resources/shortcuts_sql_buffer_statement.vim` file is loaded.
So, have a look at this file for further details. Please note that for
executing the current SQL, the default shortcut is `ctrl + space`.
The same goes for a result set buffer. The shortcuts from the file pointed by
the `g:sw_shortcuts_sql_results` variable are loaded. If the variable is not
set, then the shortcuts from `resources/shortcuts_sql_results.vim` are loaded.
If you want further details, please have a look at this file.
You can also have comment in the format `-- before <command>` on a single
line. This comments will be parsed by the plugin. If the command begins with a
`:` it will be interpreted as a `vim` command and executed by vim. Otherwise,
the command will be sent to the DBMS when opening the file.
Examples:
`-- before :SWSqlAutocompleteLoad <file>`
This command will load the intellisense autocomplete options saved in with
`SWSqlAutocompletePersist <file>`.
`-- before start transaction;`
This command will be sent to the DBMS and will start a new transaction every
time when you open this buffer.
## Execute the current statement
As stated already, you can press `ctrl + space` in normal or insert mode or
you can have your own shortcut. Alternatively, in normal mode, you can execute
`SWSqlExecuteCurrent` command.
The statement between the last 2 delimiters will be sent to the server, or
from the beginning of the file until the first delimiter, or from the last
delimiter to the end of the file, depending on where your cursor is placed.
By default, if you execute `SWSqlExecuteCurrent`, vim will wait for the result
before continuing. If you don't want to wait for the result, you can execute
`SWSqlExecuteCurrent!`.
*Note*: The default shortcut is mapped using `SWSqlExecuteCurrent!`, which
means that pressing `Ctrl + space` will execute the current command asynchronous.
## Execute the selected statement
In visual mode, you can press `ctrl + e` or your own custom shortcut.
Alternatively, you can execute the `SWSqlExecuteSelected` command. Please be
careful to delete the range before, if you want to execute the command from
the visual mode.
The selected text is going to be sent to the DBMS.
Like before, if you want the command executed asynchronous, you have to use
the exclamation mark after it (`SWSqlExecuteSelected!`). By default, this is
mapped on `ctrl + e`. You can change this mapping.
## Execute all statements
In visual mode, you can press `ctrl + a` or your own custom shortcut.
Alternatively, you can execute the `SWSqlExecuteAll` command. All the buffer
is going to be sent to the DBMS.
Also here you can use an exclamation mark to execute the command asynchronous,
which is the default mapping.
## Intellisense
`vim-sqlworkbench` plugin comes with intellisense out of the box. In order to
take advantage of the auto complete intellisense, you have to execute first
the `SWSqlAutocomplete` command. Depending on how many tables and views you
have in your database, it might take even more than one minute. After the
command is executed, normally you can press &lt;C-x&gt;&lt;C-u&gt; in insert
mode in a sql statement.
*Note*: due to constant conflicts with dbext plugin (which apparently has some
parts included in the `/usr/share/vim` folder) I prefer to switch to
&lt;C-x&gt;&lt;C-u&gt;. So, you cannot use &lt;C-x&gt;&lt;C-u&gt; anymore for
intellisense
The plugin will try to determine where you are in the sql and return the
appropriate options. For example, if you are in the fields part of a `select`
statement, the options returned will be the fields based on the tables from
the `from` part of the `select`. If you are in the `from` part, then the list
of tables is returned. If you have an identifier followed by a dot, then if
that identifier is a table, a view or an alias of a view or subquery, the
system will return the corresponding list of fields.
Also the subqueries are parsed and the appropriate fields are returned.
If you are in a subquery in a bigger query, the auto complete will be executed
at the level of the subquery.
If you are in a `union` `select` statement, the system will try to determine
in which `select` the cursor is placed and execute auto completion for that sql.
As stated before, enabling the auto completion for a buffer can take some
time. Normally, whenever you execute a `SWSqlAutocomplete`, the data is cached
in memory in vim buffer variables. If you want to persist in on the hard
drive with `SWSqlAutocompletePersist myProfile` command. This will save the
data on hard drive. Later you can reload it with `SWSqlAutocompleteLoad
myProfile`. Combined with `-- before` comments in the file, you can have the
autocomplete loaded every time you open a file.
If you modify a table then, you can do `SWSqlAutocomplete modified_table`.
This will be very fast, as it will only load the data for the table. You can
sent as many tables at once. Of course, more tables you send, the longer it
will take to complete. For example, you can do `SWSqlAutocomplete
modified_table1 modified_table2`. This will reload the data for
`modified_table1` and `modified_table2`.
If you drop a table, you can always execute `SWSqlAutocomplete` with the name
of the table preceded by a `-`. This will eliminate the table from the
autocomplete list. For example: `SWSqlAutocomplete -dropped_table`. You can
combine in the same statement adding and deleting of tables. For example:
`SWSqlAutocomplete -dropped_table new_table`.
You can also execute `SWSqlAutocomplete!`. This will reset any autocomplete
option and will reload again all the tables.
Unfortunately, the autocomplete for the function and procedures is limited.
This is because `SQL Workbench/J` does not provide also a list of parameters
through a `SQL Workbench` command. I can only retrieve the name of the
function or procedure. Also, the autocomplete for the procedure and functions
is limited to the `WbCall` command.
*NOTE*: The autocomplete feature is implemented using regular expressions.
Because of using regular expressions, it's possible that I've missed cases. If
you notice any case where the autocomplete is not working properly, please let
me know.
## Get an object definition
When with the cursor on top of any word in the buffer or in the result set,
you can click `alt + i` or your own custom shortcut. This will display that
object definition if the object exists in the result set buffer or an error
message.
Alternatively you can execute the `SWSqlObjectInfo` command from normal mode.
Basically the command `desc <object>` is sent to the DBMS and the output
returned.
## Get an object definition
When you are with the cursor on top of any word in the buffer or in the result
set, you can click `alt + s` or your own custom shortcut. This will display
the object source if the object exists in the result set buffer or an error
message.
Alternatively, you can execute the `SWSqlObjectSource` command from normal
mode.
## Maximum number of rows.
By default, the maximum number of results returned by a select is 5000. You
can change this with the `set maxrows` command. See
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-set)
## Changing result sets display mode
In the result set buffer, you can click `alt + d` or your own custom shortcut
on top of a row. This will toggle the row display to have each column on a row
for the selected row. To change back the display mode, click again the same
shortcut.
Alternatively, you can execute the `WbDisplay` command. See
[here](http://www.sql-workbench.net/manual/console-mode.html) for more detail.
=============================================================================
Searching *sw-searching*
`SQL Workbench/J` comes with two very handy and powerful commands:
`WbGrepSource` and `WbGrepData`. `vim-sqlworkbench` takes advantage of both of
them and implements searching options. You can search in objects source code,
or you can search tables data.
## Searching in objects source code
Of course, you can always execute `WbGrepSource` in a sqlbuffer and send it to
the DBMS. For a full documentation of the command, please see
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-search-source).
Alternatively, you can call one of the three `vim-sqlworkbench` search
commands available: `SWSearchObject`, `SWSearchObjectAdvanced` or
`SWSearchObjectDefaults`.
The `SWSearchObject` command will take one argument, which is the search
string. The command which will be sent to the DBMS is `WbGrepSource
<your_terms>`. This means that you execute a search with `SQL Workbench/J`
default values. For a list of these, see the above link.
*Example:* `:SWSearchObject my_table<cr>`
The `SWSearchObjectAdvanced` command will open an interactive command prompt
asking for every parameter value, beginning with the search terms.
Additionally, it will also require the columns to be displayed from the search
result. If you want to only search for some objects that contain a certain
term in their definition, you might not want to include the code of the
object. This might take multiple rows. In this case you will have to scroll in
the result buffer to see all the objects containing your term. If this is the
case, you can include only the "NAME" and "TYPE" columns.
If you leave the columns empty, then the plugin will return all the columns
but will remove all the rows from the source column. Only the first row from
each column will be displayed. If you want to see all the columns with all the
rows, you have to specify all the columns in the columns section
(`NAME,TYPE,SOURCE`). Please note that you cannot change the order of the
columns.
The `SWSearchObjectDefaults` command takes one argument (the search terms) and
will perform a search using all the defaults defined in `vim-sqlworkbench`
plugin. These defaults can be changed in `vimrc`.
*Example:* `:SWSearchObjectDefaults my_table<cr>`
## Searching for data inside tables
You can execute `WbGrepData` in a sql buffer and send it to the DBMS. For a
full documentation of the command, please see
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-search-data).
Alternatively, you can call one of the three `vim-sqlworkbench` search
commands available: `SWSearchData`, `SWSearchDataAdvanced` or
`SWSearchDataDefaults`.
All the three commands work as their counter parts for searching object with
the exception that no column can be selected any more.
If you are in an sql buffer, then the results are displayed in the result sets
buffer. If you are in a database explorer, then the search results are
displayed in the bottom right panel.
=============================================================================
Exporting *sw-exporting*
`vim-sqlworkbench` takes advantage of the very powerful `SQL Workbench/J`
command, `WbExport`.
As usual, you can always execute the `WbExport` command inside a sql buffer.
To see the full documentation of the `WbExport` command, have a look
[here](http://www.sql-workbench.net/manual/command-export.html).
*Note*: If you use the wbexport command, you need to send both of the queries
at once, by selecting both queries (first the `WbExport` query and then the
exported query) and then running `SWSqlExecuteSelected`. This happens because
the plugin will send after each statement a silent command to notice vim that
a new result is waiting. So, if you execute `WbExport`, the exported statement
will be the silent one which is void and is not a `select` statement.
Or you can execute the `SWSqlExport` command. This will open an interactive
input dialog which will ask for the format and the destination file and will
export the last sql command. If you are in a database explorer, in the right
panel, you can click on "E". This shortcut is not modifiable. This will export
what ever is in the right panel, after asking for the format and the
destination file. Please note that because of extra dependencies required for
`xls` export, `vim-sqlworkbench` does not provide support for this format.
However, you can export as `ods`, which is what you should use anyway. See
[here](http://www.fsf.org/campaigns/opendocument/) or
[here](http://www.fsf.org/campaigns/opendocument/download)
=============================================================================
Sessions *sw-sessions*
`vim-sqlworkbench` provides support for vim sessions. You have to have the
`globals` enabled in your session options (`set sessionoptions+=globals`).
However, the session restore is done in two steps. As soon as you restore a
vim session, you will notice that for example a database explorer is empty and
pressing the shortcuts will have no effect. You have, when entering in the
tab, to call the command `SWDbExplorerRestore`.
Similar, when entering an sql buffer after a session restore, you will notice
that executing statements against the DBMS will produce vim errors. Before
executing any statement, you have to call the `SWSqlBufferRestore`. This will
also restore the autocomplete list, so you will also have the autocomplete.
=============================================================================
Variables *sw-variables*
`SQL Workbench/j` supports user defined variables (you can have your queries
sent to the database parameterized). See
[here](http://www.sql-workbench.net/manual/using-variables.html).
This plugin takes advantage of that and implements a few commands to help you
use variables.
By default, in `SQL Workbench`, the variables are enclosed between `$[` and
`]`. [These can be
changed](http://www.sql-workbench.net/manual/using-variables.html#access-variable).
By default, in `VIM SQL Workbench` the variable substitution is on. This
means, that when you send a query to the database, the plugin will search for
anything enclosed between the parameter prefix and suffix. Once a match is
found, if a value is defined with `SWVarSet` then the match is replaced with
this value. Please note that exactly the literal is replaced. No quotes are
added and no escaping is executed. If you want quotes, you need to add then in
the value.
If the variable is not defined using `SWVarSet` the plugin will ask for a
value. If you don't want this string to be replaced when the query is sent to
the database, then you can use an empty string as a value. If you want to send
to the database an empty string, then you have to set the value `''`.
If you set already a value for a variable, you can always change it by
executing again `SWVarSet`.
A variable can be unset using `SWVarUnset`.
If you don't want the plugin doing parameters substitution for a given buffer,
you can call `SWVarDisable`. You can always re-enable the parameter
substitution by calling `SWVarEnable`.
Example:
In your `workbench.settings` file:
```
workbench.sql.parameter.prefix=:
workbench.sql.parameter.suffix=
```
The sql query: `select * from table where d = '2015-01-01 00:00:00'`.
When launching this query, you will be asked for the value of the `00`
variable. You can just press `enter` and the `:00` will not be replace.
The sql query: `select * from table where name = :name`.
When launching this query, you will be asked for the value of the `name`
variable. If you enter `'Cosmin Popescu'`, the query sent to the DBMS will be
`select * from table where name = 'Cosmin Popescu'`. Please note that if you
just enter `Cosmin Popescu` (notice the missing quotes), the query sent to the
DBMS will be `select * from table where name = Cosmin Popescu` which will
obviously return an error.
=============================================================================
Commands *sw-commands*
## SWDbExplorer
*Parameters*:
* profile name: the name of the profile for which to open the database explorer.
* port: the port on which the server listens
Opens a database explorer for the desired profile using the server from the
specified port.
*NOTE*: If you set the
`g:sw_config_dir` variable to point to the `SQL Workbench/J` settings folder,
the command will autocomplete the profile names. See
[here](http://www.sql-workbench.net/manual/install.html#config-dir)
## SWDbExplorerClose
*Parameters*;
* profile name (optional): the name of the database explorer that should be
closed.
Closes a database explorer. If no profile name is specified, if you are inside
a database explorer, then that database explorer is closed. Otherwise, the
system will generate an error.
If you specify a profile name, then the database explorer which is opened for
the indicated profile is closed.
## SWDbExplorerRestore
After a session restore, this command will restore an opened database panel
## SWSqlExecuteCurrent
In an sql buffer executes the current statement. You can execute this command
in normal or insert mode. This is the statement between two consecutive
identifiers, or from the beginning of the file to the first identifier or from
the last identifier to the end of the file. You can change the delimiter using
the `SWSqlDelimiter` command.
## SWSqlExecuteSelected
In an sql buffer, executes the current selected statement. The command works
in visual mode. Be careful to delete the range before typing the command.
## SWSqlExecuteAll
Send all sql statements from the buffer to the DBMS.
## SWSqlToggleMessages
If you have a result set displayed in the result set buffer, you can toggle
between the result displayed and the messages produced by the command with
this command. The command works from the sql buffer and from the result set
buffer.
## SWSqlObjectInfo
In a sql buffer or in a result set buffer, you can position the cursor on top
of any word and call this command. The plugin will send to the DBMS `DESC
<word>`. If the word that you selected is a valid database object, you will
see its definition. Otherwise it will return an error.
## SWSqlObjectSource
Like the previous command, if you are with your cursor on top of a word and
call this command, the plugin will return it's source code, if the selected
word is an object in the database. Otherwise, it will return an empty result
set.
## SWSqlExport
This command will export the last executed statement. Of course, if your last
statement did not produced any results, you will have an empty file. The
plugin will ask you about the format and about the output file. You can export
in one of the following formats: `text`, `sqlinsert`, `sqlupdate`,
`sqldeleteinsert`, `xml`, `ods`, `html`, `json`.
## SWSearchObject
*Parameters*:
* search terms: the terms that you are searching.
This command performs a search in the source code of the database objects. It
uses the defaults of `SQL Workbench/J`. The command which is used is
`WbGrepSource`. You can see more details about the parameters and their
default values
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-search-source).
The search result will only return the first row of each column. This means
that you will have to select each term that you want to inspect and see it's
source using the `SWSqlObjectSource` command. If you want to see the full
output you have to either set `g:sw_search_default_result_columns` to
'NAME,TYPE,SOURCE' and execute the command `SWSearchObjectDefaults`, or you
can execute the `SWSearchObjectAdvanced` command and select all three columns
when asked.
## SWSearchObjectAdvanced
This command will perform an advanced search. It will ask for each possible
parameter. You can cancel the search at any time by replying with an empty
value. This, however, is not possible for the columns input, since the empty
string in the columns means that you want all the columns but only the first
row of each.
## SWSearchObjectDefaults
*Parameters*:
* search terms: the terms that you are searching.
This command will perform a search using as default values for all the
parameters the values defined through the vim variables:
* `g:sw_search_default_regex`
* `g:sw_search_default_match_all`
* `g:sw_search_default_ignore_case`
* `g:sw_search_default_types`
* `g:sw_search_default_compare_types`
## SWSearchData
*Parameters*:
* search terms: the terms that you are searching.
This command performs a search in the data in the tables. It uses the defaults
of `SQL Workbench/J`. The command which is used is `WbGrepData`. You can see
more details about the parameters and their default values
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-search-data).
## SWSearchDataAdvanced
This command will perform an advanced search in the tables data. It will ask
for each possible parameter. You can cancel the search at any time by replying
with an empty value, with the exception of the `excludeTables` parameter,
since an empty value here means that you want to search in all the tables and
is not an unusual request.
## SWSearchDataDefaults
*Parameters*:
* search terms: the terms that you are searching.
This command will perform a search in tables data using as default values for
all the parameters the values defined through the vim variables:
* `g:sw_search_default_ignore_case`
* `g:sw_search_default_compare_types`
* `g:sw_search_default_tables`
* `g:sw_search_default_data_types`
* `g:sw_search_default_exclude_tables`
* `g:sw_search_default_exclude_lobs`
## SWSqlAutocomplete
This command enables the intellisense autocomplete for the current sql buffer.
After this command you can use &lt;C-x&gt;&lt;C-o&gt; for autocomplete.
You can have as arguments any number of tables from the database to fetch the
autocomplete information only about those tables. You can also precede any
name table with a `-`. In this case, the information will be deleted from the
plugin cache.
The arguments are useful, if you use the `g:sw_autocomplete_on_load` option.
## SWSqlBufferRestore
This command will restore the properties of the sql buffer following a vim
session restore. This includes the autocomplete intellisense of the buffer, if
this was active when `mksession` was executed.
## SWVarSet
*Parameters*:
* the variable name: the name of the variable to be set
* the value: the value that you want to set for this variable
If you want to set a string enclosed between the `SQL Workbench/J` parameters
suffix and prefix without being substituted, then set it to an empty string.
If you want to replace a parameter with an empty string, set the value of the
variable to `''`.
## SWVarUnset
Unsets a variable
## SWVarDisable
Disables the replacement of the parameters in the queries sent to the DBMS.
## SWVarEnable
Enables the replacement of the parameters in the queries sent to the DBMS
(enabled by default).
## SWVarList
Lists the parameters values
## SWServerStart
*Parameters*:
* the port: the port on which the server will listen
* the profile: optional, you can choose a profile when starting the server
This command will spawn a new server which will launch a `SQL Workbench/J` in
console mode. This can be used if you want to use transactions.
Please note that you need `vim dispatch` plugin in order to run this from
`vim`.
## SWServerStop
*Parameters*:
* the port: the port of the server to close.
This command will stop a server. Also the `SQL Workbench/J` instance in
console mode will be closed.
## SWSqlConnectToServer
*Parameters*:
* port: the port of the server
* file name (optional): the name of the file to open.
This will open a new buffer which will be connected to an existing
`sqlwbconsole` server. If the file name is not specified, then it will connect
the current buffer to the server on the specified port.
## SWDbExplorerReconnect
Reconnects the database explorer. This is useful if a timeout has occured
while having a database connection opened. Then you call the
`SWDbExplorerReconnect` in order to be able to execute commands again.
=============================================================================
Settings *sw-settings*
## Search object source settings:
* `g:sw_search_default_result_columns`: the default list of columns to be
included in a search result; default value: ""
* `g:sw_search_default_regex`: whether to use regular expressions or not when
performing a search; default value: "Y"
* `g:sw_search_default_match_all`: whether to match or not all the search
terms or only one (use `OR` or `AND` when performing the search); default
value: "Y"
* `g:sw_search_default_ignore_case`: whether to ignore the case or not when
performing a search; default value: "Y"
* `g:sw_search_default_types`: the types of object in which to search; default
value: "LOCAL TEMPORARY,TABLE,VIEW,FUNCTION,PROCEDURE,TRIGGER,SYNONYM"
*Note*: this values apply for the `SWSearchObjectDefaults` command. The
`SWSearchObjectAdvanced` will ask for the value of each parameter and
`SWSearchObject` command will use the defaults of `SQL Workbench`.
## Search data in tables settings:
* `g:sw_search_default_match_all`: whether to match or not all the search
terms or only one (use `OR` or `AND` when performing the search); default
value: "Y"
* `g:sw_search_default_compare_types`: the type of search to be performed (the
operator for the search); default value: "contains"
* `g:sw_search_default_tables`: the tables to be included in the search;
default value: "%", which means all tables
* `g:sw_search_default_data_types`: the types of objects in which to perform
the search; default value: "TABLE,VIEW"
* `g:sw_search_default_exclude_tables`: the list of tables to exclude from
search; default value: ""
* `g:sw_search_default_exclude_lobs`: whether or not to exclude the `blob` and
`clob` columns from search; default value: "Y"
*Note*: this values apply for the `SWSearchDataDefaults` command. The
`SWSearchDataAdvanced` will ask for the value of each parameter and
`SWSearchData` command will use the defaults of `SQL Workbench`.
To see more about these parameters, see
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-search-source)
and
[here](http://www.sql-workbench.net/manual/wb-commands.html#command-search-data)
## Sql buffer settings:
* `g:sw_sqlopen_command`: the vim command used by `SWSqlConnectToServer`
command to open a buffer; possible values: `e|tabnew`; default value: "e",
which means open with vim `edit` command
* `g:sw_tab_switches_between_bottom_panels`: if set to true, then clicking tab
in a db explorer will switch between the bottom panels
* `g:sw_autocomplete_cache_dir`: the location where the autocomplete
information is saved. You'll need to set it on Windows to work.
## Database explorer settings
* `g:sw_default_right_panel_type`: the file type of the bottom right panel
when not specified; default value: "txt"
## General settings:
* `g:sw_exe`: the location of the `SQL Workbench` executable; default value:
"sqlwbconsole.sh"
* `g:sw_tmp`: the location of your temporary folder; default value: "/tmp"
* `g:sw_asynchronious`: by default, the commands are executed synchronous; if
you set this to 1, then the commands will be executed asynchronous
* `g:sw_vim_exe`: the default VIM executable location; this is used in
conjunction with the asynchronous mode; default value: `vim`
* `g:sw_delete_tmp`: if true, then delete the temporary files created to
execute any command. Useful for debugging. You can set it to 0 and check all
the generated files
Example: sw.txt /*Example:*
Example: sw.txt /*Example:*
Features: sw.txt /*Features:*
NOTE: sw.txt /*NOTE:*
sw sw.txt /*sw*
sw-commands sw.txt /*sw-commands*
sw-dbexplorer sw.txt /*sw-dbexplorer*
sw-dbms-connect sw.txt /*sw-dbms-connect*
sw-exporting sw.txt /*sw-exporting*
sw-requirements sw.txt /*sw-requirements*
sw-searching sw.txt /*sw-searching*
sw-sessions sw.txt /*sw-sessions*
sw-settings sw.txt /*sw-settings*
sw-sql-buffer sw.txt /*sw-sql-buffer*
sw-variables sw.txt /*sw-variables*
vim-sql-workbench sw.txt /*vim-sql-workbench*
sql-workbench vim-sql-workbench.txt /*sql-workbench*
sql-workbench-changing-result-sets-display-mode vim-sql-workbench.txt /*sql-workbench-changing-result-sets-display-mode*
sql-workbench-commands vim-sql-workbench.txt /*sql-workbench-commands*
sql-workbench-connecting-to-dbms vim-sql-workbench.txt /*sql-workbench-connecting-to-dbms*
sql-workbench-connecting-vim-buffer vim-sql-workbench.txt /*sql-workbench-connecting-vim-buffer*
sql-workbench-creating-new-database-explorer-from-scratch vim-sql-workbench.txt /*sql-workbench-creating-new-database-explorer-from-scratch*
sql-workbench-database-explorer vim-sql-workbench.txt /*sql-workbench-database-explorer*
sql-workbench-database-explorer-settings vim-sql-workbench.txt /*sql-workbench-database-explorer-settings*
sql-workbench-execute-all-statements vim-sql-workbench.txt /*sql-workbench-execute-all-statements*
sql-workbench-execute-current-statement vim-sql-workbench.txt /*sql-workbench-execute-current-statement*
sql-workbench-execute-selected-statement vim-sql-workbench.txt /*sql-workbench-execute-selected-statement*
sql-workbench-exporting vim-sql-workbench.txt /*sql-workbench-exporting*
sql-workbench-extending-default-database-explorer vim-sql-workbench.txt /*sql-workbench-extending-default-database-explorer*
sql-workbench-general-settings vim-sql-workbench.txt /*sql-workbench-general-settings*
sql-workbench-get-an-object-definition vim-sql-workbench.txt /*sql-workbench-get-an-object-definition*
sql-workbench-intellisense vim-sql-workbench.txt /*sql-workbench-intellisense*
sql-workbench-introduction vim-sql-workbench.txt /*sql-workbench-introduction*
sql-workbench-maximum-number-of-rows. vim-sql-workbench.txt /*sql-workbench-maximum-number-of-rows.*
sql-workbench-references vim-sql-workbench.txt /*sql-workbench-references*
sql-workbench-requirements vim-sql-workbench.txt /*sql-workbench-requirements*
sql-workbench-screen-shots vim-sql-workbench.txt /*sql-workbench-screen-shots*
sql-workbench-search-data-in-tables-settings vim-sql-workbench.txt /*sql-workbench-search-data-in-tables-settings*
sql-workbench-search-object-source-settings vim-sql-workbench.txt /*sql-workbench-search-object-source-settings*
sql-workbench-searching vim-sql-workbench.txt /*sql-workbench-searching*
sql-workbench-searching-for-data-inside-tables vim-sql-workbench.txt /*sql-workbench-searching-for-data-inside-tables*
sql-workbench-searching-in-objects-source-code vim-sql-workbench.txt /*sql-workbench-searching-in-objects-source-code*
sql-workbench-sessions vim-sql-workbench.txt /*sql-workbench-sessions*
sql-workbench-settings vim-sql-workbench.txt /*sql-workbench-settings*
sql-workbench-sql-buffer vim-sql-workbench.txt /*sql-workbench-sql-buffer*
sql-workbench-sql-buffer-settings vim-sql-workbench.txt /*sql-workbench-sql-buffer-settings*
sql-workbench-sql-commands vim-sql-workbench.txt /*sql-workbench-sql-commands*
sql-workbench-starting-server-from-command-line vim-sql-workbench.txt /*sql-workbench-starting-server-from-command-line*
sql-workbench-starting-server-from-vim vim-sql-workbench.txt /*sql-workbench-starting-server-from-vim*
sql-workbench-swdbexplorer vim-sql-workbench.txt /*sql-workbench-swdbexplorer*
sql-workbench-swdbexplorerclose vim-sql-workbench.txt /*sql-workbench-swdbexplorerclose*
sql-workbench-swdbexplorerreconnect vim-sql-workbench.txt /*sql-workbench-swdbexplorerreconnect*
sql-workbench-swdbexplorerrestore vim-sql-workbench.txt /*sql-workbench-swdbexplorerrestore*
sql-workbench-swsearchdata vim-sql-workbench.txt /*sql-workbench-swsearchdata*
sql-workbench-swsearchdataadvanced vim-sql-workbench.txt /*sql-workbench-swsearchdataadvanced*
sql-workbench-swsearchdatadefaults vim-sql-workbench.txt /*sql-workbench-swsearchdatadefaults*
sql-workbench-swsearchobject vim-sql-workbench.txt /*sql-workbench-swsearchobject*
sql-workbench-swsearchobjectadvanced vim-sql-workbench.txt /*sql-workbench-swsearchobjectadvanced*
sql-workbench-swsearchobjectdefaults vim-sql-workbench.txt /*sql-workbench-swsearchobjectdefaults*
sql-workbench-swserverstart vim-sql-workbench.txt /*sql-workbench-swserverstart*
sql-workbench-swserverstop vim-sql-workbench.txt /*sql-workbench-swserverstop*
sql-workbench-swsqlautocomplete vim-sql-workbench.txt /*sql-workbench-swsqlautocomplete*
sql-workbench-swsqlbufferrestore vim-sql-workbench.txt /*sql-workbench-swsqlbufferrestore*
sql-workbench-swsqlconnecttoserver vim-sql-workbench.txt /*sql-workbench-swsqlconnecttoserver*
sql-workbench-swsqlexecuteall vim-sql-workbench.txt /*sql-workbench-swsqlexecuteall*
sql-workbench-swsqlexecutecurrent vim-sql-workbench.txt /*sql-workbench-swsqlexecutecurrent*
sql-workbench-swsqlexecutenow vim-sql-workbench.txt /*sql-workbench-swsqlexecutenow*
sql-workbench-swsqlexecutenowlastresult vim-sql-workbench.txt /*sql-workbench-swsqlexecutenowlastresult*
sql-workbench-swsqlexecuteselected vim-sql-workbench.txt /*sql-workbench-swsqlexecuteselected*
sql-workbench-swsqlexport vim-sql-workbench.txt /*sql-workbench-swsqlexport*
sql-workbench-swsqlobjectinfo vim-sql-workbench.txt /*sql-workbench-swsqlobjectinfo*
sql-workbench-swsqlobjectsource vim-sql-workbench.txt /*sql-workbench-swsqlobjectsource*
sql-workbench-swsqltogglemessages vim-sql-workbench.txt /*sql-workbench-swsqltogglemessages*
sql-workbench-variables vim-sql-workbench.txt /*sql-workbench-variables*
*sql-workbench* Introduction
===============================================================================
Contents ~
1. Introduction |sql-workbench-introduction|
2. Requirements |sql-workbench-requirements|
3. Connecting to a DBMS |sql-workbench-connecting-to-dbms|
4. The database explorer |sql-workbench-database-explorer|
5. The SQL buffer |sql-workbench-sql-buffer|
6. SQL commands |sql-workbench-sql-commands|
7. Searching |sql-workbench-searching|
8. Exporting |sql-workbench-exporting|
9. Sessions |sql-workbench-sessions|
10. Variables |sql-workbench-variables|
11. Commands |sql-workbench-commands|
12. Settings |sql-workbench-settings|
13. Screen shots |sql-workbench-screen-shots|
14. References |sql-workbench-references|
===============================================================================
*sql-workbench-introduction*
Introduction ~
This is an implementation of SQL Workbench/J [1] in VIM. It works with any DBMS
supported by 'SQL Workbench/J' (PostgreSQL, Oracle, SQLite, MySQL, SQL Server
etc.). See the complete list here [2].
You can connect to any DBMS directly from VIM.
_Features:_
- database explorer (e.g.: table lists, procedures list, views list, triggers
list), extensible (you can have your own objects list)
- SQL buffer with performant autocomplete
- export any sql statement as 'text', 'sqlinsert', 'sqlupdate',
'sqldeleteinsert', 'xml', 'ods', 'html', 'json'
- search in object source
- search in table or views data
- asynchronous (you can execute any command asynchronous)
- fully customizable
CONTENTS:
1. Requirements
2. Connecting to a DBMS
3. The database explorer
4. The SQL Buffer
5. SQL commands
6. Searching
7. Exporting
8. Sessions
9. Variables
10. Commands
11. Settings
12. Screen shots
===============================================================================
*sql-workbench-requirements*
Requirements ~
- 'Vim' compiled with 'python' support
- 'Python' installed on the machine
- 'SQL Workbench/J' installed on the machine
- Optional: 'vim dispatch' [3] plugin installed.
- 'VIM' started in server mode
Of course you need VIM 7 or above. You also need 'SQL Workbench/J' [1]
installed on your computer. It is platform independent, since 'SQL Workbench'
is written in JAVA and it should work anywhere where VIM works.
Before getting started, you have to set the 'g:sw_exe' vim variable. The
default value is 'sqlwbconsole.sh'. If you have 'SQL Workbench' in your PATH,
then you can skip this step. Otherwise, just set the value of the variable to
point to your 'sqlwbconsole' file. If you are on Windows, it should be
'sqlwbconsole.exe'.
Also, if you are on Windows, you have to set the 'g:sw_tmp' value in your
'vimrc'. The default value is '/tmp'.
The communication with the DBMS is made through the 'sqlwbserver' script, that
you can find in the 'resources' folder of the plugin. This is a 'python' script
(hence the need to have 'python' installed on the machine) and it will spawn a
'sqlwbconsole' instance in memory and then open a port on which will listen for
requests. After this, whenever you want to send a command to the DBMS from
'VIM', the plugin will connect on the specified port, send the command and
retrieve the result which will be displayed in 'VIM'.
===============================================================================
*sql-workbench-connecting-to-dbms*
Connecting to a DBMS ~
First of all, you need to open have a 'sqlwbserver' running in memory. There
are two ways to run a server.
-------------------------------------------------------------------------------
*sql-workbench-starting-server-from-vim*
Starting a server from vim ~
For this you need to have the 'vim dispatch' plugin installed. If you want to
start the server from 'vim', you can call the command 'SWServerStart' with the
port on which the server will listen. Also, you can choose a profile for the
new connection. If you don't choose a profile now, you will have to execute
'WbConnect' [4] in order to connect to a database.
For example: 'SWServerStart 5000'.
-------------------------------------------------------------------------------
*sql-workbench-starting-server-from-command-line*
Starting a server from command line ~
If you don't want or you can't install the 'vim dispatch' plugin, you can
always start a server from command line. From your terminal, you need to run
the 'resources/sqlwbserver' script. For a list of parameters you can do
'resources/sqlwbserver --help'. The following parameters are mandatory:
- The path to your 'sqlwbconsole' executable ('-c').
The default port on which the server will listen is 5000. You can change this
with the '-o' parameter.
Please note that a server handles only one 'sqlwbconsole' instance, which is
not multi threading, so also the server is not multi-threading. Since a command
sent to a DBMS through 'sqlwbconsole' cannot be interrupted, there is no reason
to have 'sqlwbserver' working multi-threading. A new command will have to wait
anyway for the old one to finish.
If you want to have several connections to a database, you can open another
server (run again 'sqlwbserver') on another port. Of course, each server will
have it's own opened transactions. You cannot do an 'update' on a port and a
'rollback' on the other port.
Though, when you open a database explorer (which requires a profile), a new
instance of 'sqlwbconsole.sh' will be launched on a different thread. So any
commands for the database explorer will be run in parallel with any command
launched from any 'vim' buffer connected to the same port.
_Example_:
>
`resources/sqlwbconsole -t /tmp -c /usr/bin/sqlwbconsole.sh -o 5000`
<
-------------------------------------------------------------------------------
*sql-workbench-connecting-vim-buffer*
Connecting a vim buffer ~
Once you have a server opened, you can connect any vim buffer to that server
using 'SWSqlConnectToServer' command. Once a buffer is connected to a server,
you can send any command from that buffer to the DBMS using the
'SWSqlExecuteCurrent', 'SWSqlExecuteSelected' or 'SWSqlExecuteAll' commands.
===============================================================================
*sql-workbench-database-explorer*
The database explorer ~
In order to open a database explorer, you need a profile.
You can create 'SQL Workbench' profiles, either by using the 'SQL Workbench'
GUI, like here [5], either opening a sql buffer with 'SWSqlConnectToServer' and
then executing 'WbStoreProfile'.
Once you have your profiles created, you can use 'SWDbExplorer' with the
desired profile as argument and you will connect to the database.
For example, ':SWDbExplorer 5000 myProfile' will open a database explorer using
the profile 'myProfile' and the server which listens on the 5000 port.
The database explorer is composed from three parts: on the top, there is a list
of available shortcuts at any moment. On the bottom left, you will see the list
of objects in your database (the list of tables and views or the list of
procedures or the list of triggers etc.) and on the bottom right, you will see
the selected object desired properties. Like in the second or third screen
shot.
So, if you want to see the columns of a table, you will have to move the cursor
in the bottom left panel, go to the desired table and press 'C'. This will
display in the right panel the table columns, indices and triggers. If you want
to see its source code, you press 'S' and so on. For all the available
shortcuts, see the top panel.
The database explorer if fully customizable. You can use the existing one and
extend it or you can create your own from scratch.
_NOTE_: For 'PostgreSQL', you should use the as database explorer the
'resources/dbexplorer-postgresql.vim' file. This is because in 'PostgreSQL' the
objects have to be prefixed by the schema. You can achieve this either by just
overwriting the 'resources/dbexplorer.vim' file with the 'resources/dbexplorer-
postgresql.vim' file, either by following the documentation bellow.
-------------------------------------------------------------------------------
*sql-workbench-creating-new-database-explorer-from-scratch*
Creating a new database explorer from scratch ~
The database explorer is loaded from the 'resources/dbexplorer.vim' file by
default. If you want to write your own, set the 'g:sw_dbexplorer_panel'
variable to point to your own file and that file will be loaded. The file has
to be a 'vimscript' file, since it's going to be sourced and it needs to set
the 'g:SW_Tabs' variable. For an example, take a look at the
'resources/dbexplorer.vim' file.
The 'g:SW_Tabs' has to be a vim dictionary. The keys are the profiles for which
the panel will be applied. '*' profile, means that the options appear on all
profiles. If you want to have separate database explorers for separate
profiles, you can create a key in the dictionary for each explorer.
_NOTE:_ At the moment you can only create profiles for different profiles, not
for different DBMS.
The values for each profile, have to be a list which will contain all the
options for the left panel. For example, in the default one, the database
objects, triggers and procedures.
Each list of objects of this list is another dictionary, with the following
keys:
- 'title' (the title which will be displayed in the top panel)
- 'shortcut' (the shortcut to access it; please note that you can have
several letters)
- 'command' (the sql command which will be executed when selecting the
object)
- 'panels' (a list of options accessible in the right panel for each selected
object in the left panel)
The panels are also a list of dictionaries. Each element of the list has the
following keys:
- 'title' (the title which will be displayed in the top panel)
- 'shortcut' (the shortcut which will be used to display it)
- 'command' (the sql command which will be executed; please note that the sql
command should contain the '%object%' string, which will be replaced with
the name of the selected object)
Optional, the panels might contain the following keys:
- 'skip_columns' (a list with the column indices from the result set that
should not be displayed)
- 'hide_header' (if set and 'true', then the header of the result set will
not be displayed in the bottom right panel)
- 'filetype' (if present, the bottom right panel 'filetype' will be set
according when selecting an object in the left panel)
_NOTES_:
1. In the command that creates the left panel, the object for which you want
to select the informations in the right panel should always be on the
first column. The '%object%' string in the column will be replaced by it.
Alternatively, you can have '%n%' (n being a number from 0 to the number
of columns in the left panel). If you have '%n%', this will be replaced
by the value of that column
2. The command can contain a comment in the format '-- AFTER' at the end.
Everything following "AFTER" word will be interpreted as a VIM command
and will be executed after the result has been displayed in the right
panel. For an example, see the SQL Source panel in the default database
explorer vim file ('resources/dbexplorer.vim').
3. The shortcuts for the left panel (the list of objects) have to be unique.
They are used to identify the current option selected to be displayed, so
that the shourtcuts for the left panel are loaded according to the
panels. However, the shortcuts for the right panel can be the same from
one list of objects to the other. For example, you can have "O" as
shortcut for objects list and then for each object you can have "S" for
showing the source code. Then, you can have "P" for listing the
procedures. Again, for each procedure you can have again "S" as shortcut
for listing the source code of a procedure or for something else.
-------------------------------------------------------------------------------
*sql-workbench-extending-default-database-explorer*
Extending the default database explorer ~
If you are happy with the default options of the database explorer (which are
the same with the ones of 'SQL Workbench/J') but you just want to add your own,
you can do so by extending the default database explorer.
This is done by calling the 'vimscript' function 'sw#dbexplorer#add_tab'. The
function takes the following arguments:
- The profile (the profile for which the option should be active; it can be
'*' for all profiles)
- The title (this is the title that will appear on the top panel)
- The shortcut (this is the shortcut to access it)
- The command (this is the SQL command to be sent to the DBMS once this
option is selected)
- The list of panels (the list of properties to be displayed in the bottom
right split for each object from the list)
The list of panels is an array of dictionaries. Each dictionary has the same
keys as indicated in the previous section for the list of panels. For example,
if you want to add the database links for all the profiles, you have to add
this in your 'vimrc':
>
call sw#dbexplorer#add_tab('*', 'DB Links', 'L', 'select db_link, username,
created from user_db_links;', [{'title': 'Show the host', 'shortcut': 'H',
'command': "select host from user_db_links where db_link = '%object%'"}])
<
Now on all profiles, you will have an extra option. Every time when you click
"L" in normal mode, in the bottom left panel you will have a list of database
links from your schema. For each link, you can move the cursor on top of it and
click H. You will see in the right panel the source of the link.
Every time when "L" is clicked, 'vim-sqlworkbench' sends the 'select db_link,
username, created from user_db_links;' command to the DBMS. The result will be
a list of database links displayed in the bottom left panel. When you move your
cursor on top of one of this links and press "H", the plugin sends to your DBMS
"select host from user_db_links where db_link = '<selected_link_name>';". The
result is displayed in the right panel.
===============================================================================
*sql-workbench-sql-buffer*
The SQL buffer ~
The SQL buffer is a normal 'vim' buffer from which you can send SQL commands to
your DBMS and in which you can use the omni completion (<C-x><C-o>) to have
intellisense autocompletion.
You can connect an opened vim buffer to a server using the
'SWSqlConnectToServer <port>' command. Or, you can open a buffer which will be
directly connected to a server by specifying the path to the buffer after the
port. For example 'SWSqlConnectToServer 5000 /tmp/dbms.sql'
Once in an sql buffer, you have several ways to execute commands against your
DBMS:
- execute the current SQL
- execute the selected statement
- execute all statements
All the shortcuts for these commands are fully customizable. But to do this,
you cannot just map the commands in 'vimrc'. This is because these shortcuts
are mapped local to the sql buffer, or to the result sets buffer. If you want
to change the default shortcuts, you need to define the
'g:sw_shortcuts_sql_buffer_statement' variable or the
'g:sw_shortcuts_sql_results' variable. This variables should point each to a
'vimscript' file which will define the mappings.
The 'g:sw_shortcuts_sql_buffer_statement' variable is used for the sql buffer
itself, while the 'g:sw_shortcuts_sql_results' variable is used for the result
set buffer (see the 4th scren shot).
As soon as a SQL buffer is opened the shortcuts from the
'g:sw_shortcuts_sql_buffer_statement' will be mapped. If the variable is not
set, then the 'resources/shortcuts_sql_buffer_statement.vim' file is loaded.
So, have a look at this file for further details. Please note that for
executing the current SQL, the default shortcut is 'ctrl + space'.
The same goes for a result set buffer. The shortcuts from the file pointed by
the 'g:sw_shortcuts_sql_results' variable are loaded. If the variable is not
set, then the shortcuts from 'resources/shortcuts_sql_results.vim' are loaded.
If you want further details, please have a look at this file.
You can also have comment in the format '-- before <command>' on a single line.
This comments will be parsed by the plugin. If the command begins with a ':' it
will be interpreted as a 'vim' command and executed by vim. Otherwise, the
command will be sent to the DBMS when opening the file.
Examples:
'-- before :SWSqlAutocompleteLoad <file>'
This command will load the intellisense autocomplete options saved in with
'SWSqlAutocompletePersist <file>'.
'-- before start transaction;'
This command will be sent to the DBMS and will start a new transaction every
time when you open this buffer.
-------------------------------------------------------------------------------
*sql-workbench-execute-current-statement*
Execute the current statement ~
As stated already, you can press 'ctrl + space' in normal or insert mode or you
can have your own shortcut. Alternatively, in normal mode, you can execute
'SWSqlExecuteCurrent' command.
The statement between the last 2 delimiters will be sent to the server, or from
the beginning of the file until the first delimiter, or from the last delimiter
to the end of the file, depending on where your cursor is placed.
By default, if you execute 'SWSqlExecuteCurrent', vim will wait for the result
before continuing. If you don't want to wait for the result, you can execute
'SWSqlExecuteCurrent!'.
_Note_: The default shortcut is mapped using 'SWSqlExecuteCurrent!', which
means that pressing 'Ctrl + space' will execute the current command
asynchronous.
-------------------------------------------------------------------------------
*sql-workbench-execute-selected-statement*
Execute the selected statement ~
In visual mode, you can press 'ctrl + e' or your own custom shortcut.
Alternatively, you can execute the 'SWSqlExecuteSelected' command. Please be
careful to delete the range before, if you want to execute the command from the
visual mode.
The selected text is going to be sent to the DBMS.
Like before, if you want the command executed asynchronous, you have to use the
exclamation mark after it ('SWSqlExecuteSelected!'). By default, this is mapped
on 'ctrl + e'. You can change this mapping.
-------------------------------------------------------------------------------
*sql-workbench-execute-all-statements*
Execute all statements ~
In visual mode, you can press 'ctrl + a' or your own custom shortcut.
Alternatively, you can execute the 'SWSqlExecuteAll' command. All the buffer is
going to be sent to the DBMS.
Also here you can use an exclamation mark to execute the command asynchronous,
which is the default mapping.
-------------------------------------------------------------------------------
*sql-workbench-intellisense*
Intellisense ~
'vim-sqlworkbench' plugin comes with intellisense out of the box. In order to
take advantage of the auto complete intellisense, you have to execute first the
'SWSqlAutocomplete' command. Depending on how many tables and views you have in
your database, it might take even more than one minute. After the command is
executed, normally you can press <C-x><C-u> in insert mode in a sql statement.
_Note_: due to constant conflicts with dbext plugin (which apparently has some
parts included in the '/usr/share/vim' folder) I prefer to switch to
<C-x><C-u>. So, you cannot use <C-x><C-u> anymore for intellisense
The plugin will try to determine where you are in the sql and return the
appropriate options. For example, if you are in the fields part of a 'select'
statement, the options returned will be the fields based on the tables from the
'from' part of the 'select'. If you are in the 'from' part, then the list of
tables is returned. If you have an identifier followed by a dot, then if that
identifier is a table, a view or an alias of a view or subquery, the system
will return the corresponding list of fields.
Also the subqueries are parsed and the appropriate fields are returned.
If you are in a subquery in a bigger query, the auto complete will be executed
at the level of the subquery.
If you are in a 'union' 'select' statement, the system will try to determine in
which 'select' the cursor is placed and execute auto completion for that sql.
As stated before, enabling the auto completion for a buffer can take some time.
Normally, whenever you execute a 'SWSqlAutocomplete', the data is cached in
memory in vim buffer variables. If you want to persist in on the hard drive
with 'SWSqlAutocompletePersist myProfile' command. This will save the data on
hard drive. Later you can reload it with 'SWSqlAutocompleteLoad myProfile'.
Combined with '-- before' comments in the file, you can have the autocomplete
loaded every time you open a file.
If you modify a table then, you can do 'SWSqlAutocomplete modified_table'. This
will be very fast, as it will only load the data for the table. You can sent as
many tables at once. Of course, more tables you send, the longer it will take
to complete. For example, you can do 'SWSqlAutocomplete modified_table1
modified_table2'. This will reload the data for 'modified_table1' and
'modified_table2'.
If you drop a table, you can always execute 'SWSqlAutocomplete' with the name
of the table preceded by a '-'. This will eliminate the table from the
autocomplete list. For example: 'SWSqlAutocomplete -dropped_table'. You can
combine in the same statement adding and deleting of tables. For example:
'SWSqlAutocomplete -dropped_table new_table'.
You can also execute 'SWSqlAutocomplete!'. This will reset any autocomplete
option and will reload again all the tables.
Unfortunately, the autocomplete for the function and procedures is limited.
This is because 'SQL Workbench/J' does not provide also a list of parameters
through a 'SQL Workbench' command. I can only retrieve the name of the function
or procedure. Also, the autocomplete for the procedure and functions is limited
to the 'WbCall' command.
_NOTE_: The autocomplete feature is implemented using regular expressions.
Because of using regular expressions, it's possible that I've missed cases. If
you notice any case where the autocomplete is not working properly, please let
me know.
-------------------------------------------------------------------------------
*sql-workbench-get-an-object-definition*
Get an object definition ~
When with the cursor on top of any word in the buffer or in the result set, you
can click 'alt + i' or your own custom shortcut. This will display that object
definition if the object exists in the result set buffer or an error message.
Alternatively you can execute the 'SWSqlObjectInfo' command from normal mode.
Basically the command 'desc <object>' is sent to the DBMS and the output
returned.
-------------------------------------------------------------------------------
Get an object definition ~
When you are with the cursor on top of any word in the buffer or in the result
set, you can click 'alt + s' or your own custom shortcut. This will display the
object source if the object exists in the result set buffer or an error
message.
Alternatively, you can execute the 'SWSqlObjectSource' command from normal
mode.
-------------------------------------------------------------------------------
*sql-workbench-maximum-number-of-rows.*
Maximum number of rows. ~
By default, the maximum number of results returned by a select is 5000. You can
change this with the 'set maxrows' command. See here [6]
-------------------------------------------------------------------------------
*sql-workbench-changing-result-sets-display-mode*
Changing result sets display mode ~
In the result set buffer, you can click 'alt + d' or your own custom shortcut
on top of a row. This will toggle the row display to have each column on a row
for the selected row. To change back the display mode, click again the same
shortcut.
Alternatively, you can execute the 'WbDisplay' command. See here [7] for more
detail.
===============================================================================
*sql-workbench-sql-commands*
SQL commands ~
You can send a sql query to the DBMS from the vim command line using the
command 'SWSqlExecuteNow'. The first parameter is the port of the server on
which to execute, and the next parameters are the sql query. Please note that
by default no results will be shown. If you want to see all that happened on
the server side, use the 'SWSqlExecuteNowLastResult' command. This will show
you what happened with the last command sent from the vim command line.
This is useful if you want to put vim shortcuts for simple things. Like, for
example, you could have in your 'vimrc':
>
nnoremap <leader>t :SWSqlExecuteNow 5000 wbdisplay tab;<cr>
<
Then pressing '<leader>t' in normal mode, would set the display to tab for the
instance listening on port 5000.
_Note_: This command will not be recorded in 'g:sw_last_sql_query'. The
delimiter is the ';'.
===============================================================================
*sql-workbench-searching*
Searching ~
'SQL Workbench/J' comes with two very handy and powerful commands:
'WbGrepSource' and 'WbGrepData'. 'vim-sqlworkbench' takes advantage of both of
them and implements searching options. You can search in objects source code,
or you can search tables data.
-------------------------------------------------------------------------------
*sql-workbench-searching-in-objects-source-code*
Searching in objects source code ~
Of course, you can always execute 'WbGrepSource' in a sqlbuffer and send it to
the DBMS. For a full documentation of the command, please see here [8].
Alternatively, you can call one of the three 'vim-sqlworkbench' search commands
available: 'SWSearchObject', 'SWSearchObjectAdvanced' or
'SWSearchObjectDefaults'.
The 'SWSearchObject' command will take one argument, which is the search
string. The command which will be sent to the DBMS is 'WbGrepSource
<your_terms>'. This means that you execute a search with 'SQL Workbench/J'
default values. For a list of these, see the above link.
_Example:_ ':SWSearchObject my_table<cr>'
The 'SWSearchObjectAdvanced' command will open an interactive command prompt
asking for every parameter value, beginning with the search terms.
Additionally, it will also require the columns to be displayed from the search
result. If you want to only search for some objects that contain a certain term
in their definition, you might not want to include the code of the object. This
might take multiple rows. In this case you will have to scroll in the result
buffer to see all the objects containing your term. If this is the case, you
can include only the "NAME" and "TYPE" columns.
If you leave the columns empty, then the plugin will return all the columns but
will remove all the rows from the source column. Only the first row from each
column will be displayed. If you want to see all the columns with all the rows,
you have to specify all the columns in the columns section
('NAME,TYPE,SOURCE'). Please note that you cannot change the order of the
columns.
The 'SWSearchObjectDefaults' command takes one argument (the search terms) and
will perform a search using all the defaults defined in 'vim-sqlworkbench'
plugin. These defaults can be changed in 'vimrc'.
_Example:_ ':SWSearchObjectDefaults my_table<cr>'
-------------------------------------------------------------------------------
*sql-workbench-searching-for-data-inside-tables*
Searching for data inside tables ~
You can execute 'WbGrepData' in a sql buffer and send it to the DBMS. For a
full documentation of the command, please see here [9].
Alternatively, you can call one of the three 'vim-sqlworkbench' search commands
available: 'SWSearchData', 'SWSearchDataAdvanced' or 'SWSearchDataDefaults'.
All the three commands work as their counter parts for searching object with
the exception that no column can be selected any more.
If you are in an sql buffer, then the results are displayed in the result sets
buffer. If you are in a database explorer, then the search results are
displayed in the bottom right panel.
===============================================================================
*sql-workbench-exporting*
Exporting ~
'vim-sqlworkbench' takes advantage of the very powerful 'SQL Workbench/J'
command, 'WbExport'.
As usual, you can always execute the 'WbExport' command inside a sql buffer. To
see the full documentation of the 'WbExport' command, have a look here [10].
_Note_: If you use the wbexport command, you need to send both of the queries
at once, by selecting both queries (first the 'WbExport' query and then the
exported query) and then running 'SWSqlExecuteSelected'. This happens because
the plugin will send after each statement a silent command to notice vim that a
new result is waiting. So, if you execute 'WbExport', the exported statement
will be the silent one which is void and is not a 'select' statement.
Or you can execute the 'SWSqlExport' command. This will open an interactive
input dialog which will ask for the format and the destination file and will
export the last sql command. If you are in a database explorer, in the right
panel, you can click on "E". This shortcut is not modifiable. This will export
what ever is in the right panel, after asking for the format and the
destination file. Please note that because of extra dependencies required for
'xls' export, 'vim-sqlworkbench' does not provide support for this format.
However, you can export as 'ods', which is what you should use anyway. See here
[11] or here [12]
===============================================================================
*sql-workbench-sessions*
Sessions ~
'vim-sqlworkbench' provides support for vim sessions. You have to have the
'globals' enabled in your session options ('set sessionoptions+=globals').
However, the session restore is done in two steps. As soon as you restore a vim
session, you will notice that for example a database explorer is empty and
pressing the shortcuts will have no effect. You have, when entering in the tab,
to call the command 'SWDbExplorerRestore'.
Similar, when entering an sql buffer after a session restore, you will notice
that executing statements against the DBMS will produce vim errors. Before
executing any statement, you have to call the 'SWSqlBufferRestore'. This will
also restore the autocomplete list, so you will also have the autocomplete.
===============================================================================
*sql-workbench-variables*
Variables ~
'SQL Workbench/j' supports user defined variables (you can have your queries
sent to the database parameterized). See here [13].
This plugin takes advantage of that and implements a few commands to help you
use variables.
By default, in 'SQL Workbench', the variables are enclosed between '$[' and
']'. These can be changed [14].
You can use 'WbVarSet' and 'WbVarUnset' in a sql buffer. If you want the system
to ask for a value, then you can use the '$[?' form of a parameter. Please note
that in 'VIM Sql Workbench' there is no difference between '?' and '&', since
there is no way to get a list of vars in 'vimscript' from 'SQL Workbench/J'
===============================================================================
*sql-workbench-commands*
Commands ~
-------------------------------------------------------------------------------
*sql-workbench-swdbexplorer*
SWDbExplorer ~
_Parameters_:
- profile name: the name of the profile for which to open the database
explorer.
- port: the port on which the server listens
Opens a database explorer for the desired profile using the server from the
specified port.
_NOTE_: If you set the 'g:sw_config_dir' variable to point to the 'SQL
Workbench/J' settings folder, the command will autocomplete the profile names.
See here [15]
-------------------------------------------------------------------------------
*sql-workbench-swdbexplorerclose*
SWDbExplorerClose ~
_Parameters_;
- profile name (optional): the name of the database explorer that should be
closed.
Closes a database explorer. If no profile name is specified, if you are inside
a database explorer, then that database explorer is closed. Otherwise, the
system will generate an error.
If you specify a profile name, then the database explorer which is opened for
the indicated profile is closed.
-------------------------------------------------------------------------------
*sql-workbench-swdbexplorerrestore*
SWDbExplorerRestore ~
After a session restore, this command will restore an opened database panel
-------------------------------------------------------------------------------
*sql-workbench-swsqlexecutecurrent*
SWSqlExecuteCurrent ~
In an sql buffer executes the current statement. You can execute this command
in normal or insert mode. This is the statement between two consecutive
identifiers, or from the beginning of the file to the first identifier or from
the last identifier to the end of the file. You can change the delimiter using
the 'SWSqlDelimiter' command.
-------------------------------------------------------------------------------
*sql-workbench-swsqlexecuteselected*
SWSqlExecuteSelected ~
In an sql buffer, executes the current selected statement. The command works in
visual mode. Be careful to delete the range before typing the command.
-------------------------------------------------------------------------------
*sql-workbench-swsqlexecuteall*
SWSqlExecuteAll ~
Send all sql statements from the buffer to the DBMS.
-------------------------------------------------------------------------------
*sql-workbench-swsqltogglemessages*
SWSqlToggleMessages ~
If you have a result set displayed in the result set buffer, you can toggle
between the result displayed and the messages produced by the command with this
command. The command works from the sql buffer and from the result set buffer.
-------------------------------------------------------------------------------
*sql-workbench-swsqlobjectinfo*
SWSqlObjectInfo ~
In a sql buffer or in a result set buffer, you can position the cursor on top
of any word and call this command. The plugin will send to the DBMS 'DESC
<word>'. If the word that you selected is a valid database object, you will see
its definition. Otherwise it will return an error.
-------------------------------------------------------------------------------
*sql-workbench-swsqlobjectsource*
SWSqlObjectSource ~
Like the previous command, if you are with your cursor on top of a word and
call this command, the plugin will return it's source code, if the selected
word is an object in the database. Otherwise, it will return an empty result
set.
-------------------------------------------------------------------------------
*sql-workbench-swsqlexecutenow*
SWSqlExecuteNow ~
_Parameters_:
- port: the port on which to execute the command
- sql: The query to be sent to the DBMS
Executes a query against the DBMS on the indicated port.
-------------------------------------------------------------------------------
*sql-workbench-swsqlexecutenowlastresult*
SWSqlExecuteNowLastResult ~
Shows the communication with the server for the last 'SWSqlExecuteNow' command.
-------------------------------------------------------------------------------
*sql-workbench-swsqlexport*
SWSqlExport ~
This command will export the last executed statement. Of course, if your last
statement did not produced any results, you will have an empty file. The plugin
will ask you about the format and about the output file. You can export in one
of the following formats: 'text', 'sqlinsert', 'sqlupdate', 'sqldeleteinsert',
'xml', 'ods', 'html', 'json'.
-------------------------------------------------------------------------------
*sql-workbench-swsearchobject*
SWSearchObject ~
_Parameters_:
- search terms: the terms that you are searching.
This command performs a search in the source code of the database objects. It
uses the defaults of 'SQL Workbench/J'. The command which is used is
'WbGrepSource'. You can see more details about the parameters and their default
values here [8].
The search result will only return the first row of each column. This means
that you will have to select each term that you want to inspect and see it's
source using the 'SWSqlObjectSource' command. If you want to see the full
output you have to either set 'g:sw_search_default_result_columns' to
'NAME,TYPE,SOURCE' and execute the command 'SWSearchObjectDefaults', or you can
execute the 'SWSearchObjectAdvanced' command and select all three columns when
asked.
-------------------------------------------------------------------------------
*sql-workbench-swsearchobjectadvanced*
SWSearchObjectAdvanced ~
This command will perform an advanced search. It will ask for each possible
parameter. You can cancel the search at any time by replying with an empty
value. This, however, is not possible for the columns input, since the empty
string in the columns means that you want all the columns but only the first
row of each.
-------------------------------------------------------------------------------
*sql-workbench-swsearchobjectdefaults*
SWSearchObjectDefaults ~
_Parameters_:
- search terms: the terms that you are searching.
This command will perform a search using as default values for all the
parameters the values defined through the vim variables:
- 'g:sw_search_default_regex'
- 'g:sw_search_default_match_all'
- 'g:sw_search_default_ignore_case'
- 'g:sw_search_default_types'
- 'g:sw_search_default_compare_types'
-------------------------------------------------------------------------------
*sql-workbench-swsearchdata*
SWSearchData ~
_Parameters_:
- search terms: the terms that you are searching.
This command performs a search in the data in the tables. It uses the defaults
of 'SQL Workbench/J'. The command which is used is 'WbGrepData'. You can see
more details about the parameters and their default values here [9].
-------------------------------------------------------------------------------
*sql-workbench-swsearchdataadvanced*
SWSearchDataAdvanced ~
This command will perform an advanced search in the tables data. It will ask
for each possible parameter. You can cancel the search at any time by replying
with an empty value, with the exception of the 'excludeTables' parameter, since
an empty value here means that you want to search in all the tables and is not
an unusual request.
-------------------------------------------------------------------------------
*sql-workbench-swsearchdatadefaults*
SWSearchDataDefaults ~
_Parameters_:
- search terms: the terms that you are searching.
This command will perform a search in tables data using as default values for
all the parameters the values defined through the vim variables:
- 'g:sw_search_default_ignore_case'
- 'g:sw_search_default_compare_types'
- 'g:sw_search_default_tables'
- 'g:sw_search_default_data_types'
- 'g:sw_search_default_exclude_tables'
- 'g:sw_search_default_exclude_lobs'
-------------------------------------------------------------------------------
*sql-workbench-swsqlautocomplete*
SWSqlAutocomplete ~
This command enables the intellisense autocomplete for the current sql buffer.
After this command you can use <C-x><C-o> for autocomplete.
You can have as arguments any number of tables from the database to fetch the
autocomplete information only about those tables. You can also precede any name
table with a '-'. In this case, the information will be deleted from the plugin
cache.
The arguments are useful, if you use the 'g:sw_autocomplete_on_load' option.
-------------------------------------------------------------------------------
*sql-workbench-swsqlbufferrestore*
SWSqlBufferRestore ~
This command will restore the properties of the sql buffer following a vim
session restore. This includes the autocomplete intellisense of the buffer, if
this was active when 'mksession' was executed.
-------------------------------------------------------------------------------
*sql-workbench-swserverstart*
SWServerStart ~
_Parameters_:
- the port: the port on which the server will listen
- the profile: optional, you can choose a profile when starting the server
This command will spawn a new server which will launch a 'SQL Workbench/J' in
console mode. This can be used if you want to use transactions.
Please note that you need 'vim dispatch' plugin in order to run this from
'vim'.
-------------------------------------------------------------------------------
*sql-workbench-swserverstop*
SWServerStop ~
_Parameters_:
- the port: the port of the server to close.
This command will stop a server. Also the 'SQL Workbench/J' instance in console
mode will be closed.
-------------------------------------------------------------------------------
*sql-workbench-swsqlconnecttoserver*
SWSqlConnectToServer ~
_Parameters_:
- port: the port of the server
- file name (optional): the name of the file to open.
This will open a new buffer which will be connected to an existing
'sqlwbconsole' server. If the file name is not specified, then it will connect
the current buffer to the server on the specified port.
-------------------------------------------------------------------------------
*sql-workbench-swdbexplorerreconnect*
SWDbExplorerReconnect ~
Reconnects the database explorer. This is useful if a timeout has occured while
having a database connection opened. Then you call the 'SWDbExplorerReconnect'
in order to be able to execute commands again.
===============================================================================
*sql-workbench-settings*
Settings ~
-------------------------------------------------------------------------------
*sql-workbench-search-object-source-settings*
Search object source settings: ~
- 'g:sw_search_default_result_columns': the default list of columns to be
included in a search result; default value: ""
- 'g:sw_search_default_regex': whether to use regular expressions or not when
performing a search; default value: "Y"
- 'g:sw_search_default_match_all': whether to match or not all the search
terms or only one (use 'OR' or 'AND' when performing the search); default
value: "Y"
- 'g:sw_search_default_ignore_case': whether to ignore the case or not when
performing a search; default value: "Y"
- 'g:sw_search_default_types': the types of object in which to search;
default value: "LOCAL
TEMPORARY,TABLE,VIEW,FUNCTION,PROCEDURE,TRIGGER,SYNONYM"
_Note_: this values apply for the 'SWSearchObjectDefaults' command. The
'SWSearchObjectAdvanced' will ask for the value of each parameter and
'SWSearchObject' command will use the defaults of 'SQL Workbench'.
-------------------------------------------------------------------------------
*sql-workbench-search-data-in-tables-settings*
Search data in tables settings: ~
- 'g:sw_search_default_match_all': whether to match or not all the search
terms or only one (use 'OR' or 'AND' when performing the search); default
value: "Y"
- 'g:sw_search_default_compare_types': the type of search to be performed
(the operator for the search); default value: "contains"
- 'g:sw_search_default_tables': the tables to be included in the search;
default value: "%", which means all tables
- 'g:sw_search_default_data_types': the types of objects in which to perform
the search; default value: "TABLE,VIEW"
- 'g:sw_search_default_exclude_tables': the list of tables to exclude from
search; default value: ""
- 'g:sw_search_default_exclude_lobs': whether or not to exclude the 'blob'
and 'clob' columns from search; default value: "Y"
_Note_: this values apply for the 'SWSearchDataDefaults' command. The
'SWSearchDataAdvanced' will ask for the value of each parameter and
'SWSearchData' command will use the defaults of 'SQL Workbench'.
To see more about these parameters, see here [8] and here [9]
-------------------------------------------------------------------------------
*sql-workbench-sql-buffer-settings*
Sql buffer settings: ~
- 'g:sw_sqlopen_command': the vim command used by 'SWSqlConnectToServer'
command to open a buffer; possible values: 'e|tabnew'; default value: "e",
which means open with vim 'edit' command
- 'g:sw_tab_switches_between_bottom_panels': if set to true, then clicking
tab in a db explorer will switch between the bottom panels
- 'g:sw_autocomplete_cache_dir': the location where the autocomplete
information is saved. You'll need to set it on Windows to work.
- 'g:sw_switch_to_results_tab': If true, then switch to the results buffer
after executting a query
-------------------------------------------------------------------------------
*sql-workbench-database-explorer-settings*
Database explorer settings ~
- 'g:sw_default_right_panel_type': the file type of the bottom right panel
when not specified; default value: "txt"
-------------------------------------------------------------------------------
*sql-workbench-general-settings*
General settings: ~
- 'g:sw_exe': the location of the 'SQL Workbench' executable; default value:
"sqlwbconsole.sh"
- 'g:sw_tmp': the location of your temporary folder; default value: "/tmp"
- 'g:sw_asynchronious': by default, the commands are executed synchronous; if
you set this to 1, then the commands will be executed asynchronous
- 'g:sw_vim_exe': the default VIM executable location; this is used in
conjunction with the asynchronous mode; default value: 'vim'
- 'g:sw_delete_tmp': if true, then delete the temporary files created to
execute any command. Useful for debugging. You can set it to 0 and check
all the generated files
===============================================================================
*sql-workbench-screen-shots*
Screen shots ~
Image: Database explorer (see reference [16]) Image: Database explorer source
view (see reference [17]) Image: Database explorer column view (see reference
[18]) Image: SQL Buffer result set (see reference [19]) Image: SQL Buffer row
displayed as form (see reference [20]) Image: SQL Buffer resultset messages
(see reference [21])
===============================================================================
*sql-workbench-references*
References ~
[1] http://www.sql-workbench.net/
[2] http://www.sql-workbench.net/databases.html
[3] https://github.com/tpope/vim-dispatch
[4] http://www.sql-workbench.net/manual/wb-commands.html#command-connect
[5] http://www.sql-workbench.net/manual/profiles.html#profile-intro
[6] http://www.sql-workbench.net/manual/wb-commands.html#command-set
[7] http://www.sql-workbench.net/manual/console-mode.html
[8] http://www.sql-workbench.net/manual/wb-commands.html#command-search-source
[9] http://www.sql-workbench.net/manual/wb-commands.html#command-search-data
[10] http://www.sql-workbench.net/manual/command-export.html
[11] http://www.fsf.org/campaigns/opendocument/
[12] http://www.fsf.org/campaigns/opendocument/download
[13] http://www.sql-workbench.net/manual/using-variables.html
[14] http://www.sql-workbench.net/manual/using-variables.html#access-variable
[15] http://www.sql-workbench.net/manual/install.html#config-dir
vim: ft=help
......@@ -81,6 +81,10 @@ if !exists('g:sw_sqlopen_command')
let g:sw_sqlopen_command = 'e'
endif
if !exists('g:sw_switch_to_results_tab')
let g:sw_switch_to_results_tab = 0
endif
if (!exists('g:sw_default_right_panel_type'))
let g:sw_default_right_panel_type = 'txt'
endif
......@@ -166,6 +170,8 @@ 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! -bang -nargs=+ SWSqlExecuteNow call sw#cmdline#execute(<bang>1, <f-args>)
command! -nargs=0 SWSqlExecuteNowLastResult call sw#cmdline#show_last_result()
command! -bang -nargs=+ SWSearchObject call sw#search#object(<bang>1, <f-args>)
command! -bang SWSearchObjectAdvanced call sw#search#object(<bang>1)
command! -bang -nargs=1 SWSearchObjectDefaults call sw#search#object_defaults(<bang>1, <f-args>)
......@@ -177,12 +183,6 @@ command! -nargs=1 -complete=customlist,sw#autocomplete#complete_cache_name SWSql
command! -nargs=1 -complete=customlist,sw#autocomplete#complete_cache_name SWSqlAutocompletePersist call sw#autocomplete#persist(<f-args>)
command! SWSqlBufferRestore call sw#session#restore_sqlbuffer()
command! -nargs=+ -complete=customlist,sw#variables#autocomplete_names SWVarSet call sw#variables#set(<f-args>, '')
command! -nargs=1 -complete=customlist,sw#variables#autocomplete_names SWVarUnset call sw#variables#unset(<f-args>)
command! -nargs=0 SWVarDisable call sw#variables#disable()
command! -nargs=0 SWVarEnable call sw#variables#enable()
command! -nargs=0 SWVarList call sw#variables#list()
command! -nargs=+ -complete=customlist,sw#autocomplete_profile SWServerStart call sw#server#run(<f-args>)
command! -nargs=1 SWServerStop call sw#server#stop(<f-args>)
......
......@@ -6,5 +6,5 @@ nmap <buffer> <C-A> :SWSqlExecuteAll<cr>
nmap <buffer> <C-i> :SWSqlObjectInfo<cr>
nmap <buffer> <Leader>os :SWSqlObjectSource<cr>
nmap <buffer> <C-m> :SWSqlToggleMessages<cr>
nmap <buffer> <C-d> :SWSqlToggleFormDisplay<cr>
nmap <buffer> <Leader>d :SWSqlToggleFormDisplay<cr>
......@@ -22,9 +22,9 @@ class SQLWorkbench(object):
port = 5000
results = {}
debug = 0
threads_started = 0
vim = 'vim'
tmp = "/tmp"
clock = datetime.datetime.now()
quit = False
lock = thread.allocate_lock()
executing = thread.allocate_lock()
......@@ -36,6 +36,20 @@ class SQLWorkbench(object):
dbe_connections = {}
identifier = None
def startThread(self):
# if self.debug:
# print "NEW THREAD STARTED"
# #end if
self.threads_started += 1
#end def startThread
def stopThread(self):
# if self.debug:
# print "THREAD STOPPED"
# #end if
self.threads_started -= 1
#end def stopThread
def parseCustomCommand(self, command):
if command[0] == 'identifier':
self.identifier = command[1]
......@@ -95,7 +109,7 @@ class SQLWorkbench(object):
if record == 1 and re.search(pattern1, line) == None and re.search(pattern2, line) == None:
if re.search('send_to_vim', line) == None:
if i < len(lines) - 1:
if re.search('^\\-\\-[\\-\\+\\s\\t ]+$', lines[i + 1]) != None or re.search('^----', lines[i + 1]) != None:
if re.search('^\\-\\-[\\-\\+\\s\\t ]+$', lines[i + 1]) != None:
to_add_results = True
result += "--results--"
#end if
......@@ -108,7 +122,9 @@ class SQLWorkbench(object):
'\n==============================================================================\n' +
'Query returned ' + p.group(1) + ' row' + ('s' if int(p.group(1)) > 1 else '') + '\n')
else:
result = result + re.sub(self.prompt_pattern_begin, '', line) + "\n"
line = re.sub(self.prompt_pattern_begin, '', line)
line = re.sub("^(\\.\\.> )+", '', line)
result = result + line + "\n"
#end if
#end if
#end if
......@@ -128,22 +144,25 @@ class SQLWorkbench(object):
#end def prepareResult
def spawnDbeConnection(self, profile, conn):
self.startThread()
cmd = "%s -feedback=true -showProgress=false -profile=%s" % (self.cmd, profile)
pipe = subprocess.Popen(shlex.split(cmd), stdin = subprocess.PIPE, stdout = subprocess.PIPE, bufsize = 1)
pipe.stdin.write('set maxrows = 100;\n')
conn.send('DISCONNECT')
self.dbe_connections[profile] = pipe
print "OPENING DBE CONNECTION: " + cmd
if self.debug:
print "OPENING DBE CONNECTION: " + cmd
#end if
while 1:
with self.lock:
if self.quit: break
#end with
time.sleep(0.3)
#end while
pipe.stdin.write("exit\n")
self.stopThread()
#end def spawnDbeConnection
def dbExplorer(self, conn):
def dbExplorer(self, conn, n):
profile = ''
char = ''
while char != '\n':
......@@ -157,11 +176,12 @@ class SQLWorkbench(object):
while (not profile in self.dbe_connections):
time.sleep(0.1)
#end while
else:
#end if
if n - len(profile) - 4 > 0:
pipe = self.dbe_connections[profile]
data = conn.recv(4096)
if (data):
data += "wbvardef send_to_vim = 1;\n"
data += "\nwbvardef send_to_vim = 1;\nwbvardelete send_to_vim;\n"
pipe.stdin.write(data)
result = self.receiverDbe(pipe)
conn.send(self.prepareResult(result))
......@@ -169,11 +189,8 @@ class SQLWorkbench(object):
#end if
#end def dbExplorer
def searchResult(self, conn):
data = conn.recv(4096)
if not data:
return
#end if
def searchResult(self, conn, n):
data = self.readData(conn, n)
p = self.getCaller(data)
if p == None:
return
......@@ -186,42 +203,43 @@ class SQLWorkbench(object):
#end if
#end def searchResult
def receiveData(self, conn, pipe):
def readData(self, conn, n):
result = ''
i = 0
while i < n:
data = conn.recv(4096)
if not data:
break
#end if
result += data
i += len(data)
#end while
return result
#end def readData
def receiveData(self, conn, pipe, n):
with self.processing:
self.identifier = None
cont = True
while 1:
data = conn.recv(4096)
if not data:
break
#end if
lines = data.split("\n")
for line in lines:
if re.search('^!#', line) != None:
command = self.gotCustomCommand(line)
if command != None:
self.parseCustomCommand(command)
if command[0] == 'end':
cont = False
break
#end if
#end if
else:
self.clock = datetime.datetime.now()
if self.debug:
print "SENT TO SERVER: " + line
#end if
if line != '':
pipe.stdin.write(line + "\n")
#end if
buff = self.readData(conn, n)
lines = buff.split("\n")
for line in lines:
if re.search('^!#', line) != None:
command = self.gotCustomCommand(line)
if command != None:
self.parseCustomCommand(command)
#end if
else:
if self.debug:
print "SENT TO SERVER: " + line
#end if
if line != '':
pipe.stdin.write(line + "\n")
#end if
#end for
if not cont:
break
#end if
#end while
#end for
with self.new_loop:
pipe.stdin.write("wbvardef send_to_vim = 1;\n")
pipe.stdin.write("wbvardef send_to_vim = 1;\nwbvardelete send_to_vim;\n")
if self.identifier == None:
with self.executing:
data = self.prepareResult(self.buff)
......@@ -243,22 +261,37 @@ class SQLWorkbench(object):
#end def receiveData
def newConnection(self, conn, pipe):
n = ''
c = ''
while c != '#':
c = conn.recv(1)
if c != '#':
n += c
#end if
#end while
if (n != ''):
n = int(n)
else:
n = 0
#end if
data = conn.recv(3)
if data == 'COM':
self.receiveData(conn, pipe)
self.receiveData(conn, pipe, n - 3)
elif data == 'RES':
self.searchResult(conn)
self.searchResult(conn, n - 3)
elif data == 'DBE':
self.dbExplorer(conn)
self.dbExplorer(conn, n)
#end if
conn.close()
#end def newConnection
def monitor(self, pipe, port):
self.startThread()
HOST = '127.0.0.1' # Symbolic name meaning all available interfaces
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(3)
try:
s.bind((HOST, port))
......@@ -270,14 +303,18 @@ class SQLWorkbench(object):
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
if self.debug:
print 'Connected with ' + addr[0] + ':' + str(addr[1])
try:
conn, addr = s.accept()
except Exception:
conn = None
#end try
if conn != None:
if self.debug:
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#end if
thread.start_new_thread(self.newConnection, (conn, pipe))
#end if
thread.start_new_thread(self.newConnection, (conn, pipe))
with self.lock:
if self.quit:
break
......@@ -285,10 +322,10 @@ class SQLWorkbench(object):
#end with
#end while
s.close()
self.stopThread()
#end def monitor
def receiverDbe(self, pipe):
time = ''
line = ''
buff = ''
while re.search('using.*send_to_vim', line) == None:
......@@ -305,7 +342,7 @@ class SQLWorkbench(object):
def receiver(self, pipe):
first_prompt = False
record_set = False
time = ''
self.startThread()
while True:
with self.new_loop:
line = ''
......@@ -314,22 +351,20 @@ class SQLWorkbench(object):
with self.executing:
while re.search('send_to_vim', line) == None:
line = pipe.stdout.readline()
if re.search(self.prompt_pattern_begin, line) != None:
if not first_prompt:
first_prompt = True
self.buff = ''
else:
self.buff += "\n" + time + "\n"
if line:
if re.search(self.prompt_pattern_begin, line) != None:
if not first_prompt:
first_prompt = True
self.buff = ''
#end if
#end if
#end if
if re.search('^[\\-\\+]+$', line):
time = "SQL execution time: %.2g seconds" % (datetime.datetime.now() - self.clock).total_seconds()
self.clock = datetime.datetime.now()
#end if
self.buff += line
if self.debug:
sys.stdout.write(line)
sys.stdout.flush()
self.buff += line
if self.debug:
sys.stdout.write(line)
sys.stdout.flush()
#end if
else:
break
#end if
#end while
if self.identifier != None:
......@@ -345,6 +380,7 @@ class SQLWorkbench(object):
if self.quit: break
#end with
#end while
self.stopThread()
#end def receiver
def main(self):
......@@ -357,7 +393,9 @@ class SQLWorkbench(object):
if (self.profile != None):
cmd += " -profile=%s" % self.profile
#end if
print "OPENING: " + cmd
if self.debug:
print "OPENING: " + cmd
#end if
pipe = subprocess.Popen(shlex.split(cmd), stdin = subprocess.PIPE, stdout = subprocess.PIPE, bufsize = 1)
thread.start_new_thread(self.receiver, (pipe,))
......@@ -374,7 +412,11 @@ class SQLWorkbench(object):
with self.lock:
self.quit = True
#end try...except
time.sleep(0.3)
print "Waiting for server to stop..."
while self.threads_started > 0:
time.sleep(0.3)
#end while
sys.exit(0)
#end def main
#end class SQLWorkbench
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册