forked from mtxr/SublimeText-SQLTools
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLTools.py
More file actions
Latest commit
516 lines (402 loc) · 15.8 KB
/
Copy pathSQLTools.py
File metadata and controls
516 lines (402 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
__version__="v0.6.7"
importsys
importos
importsublime
fromsublime_pluginimportWindowCommand, EventListener, TextCommand
fromDefault.paragraphimportexpand_to_paragraph
from .SQLToolsAPIimportUtils
from .SQLToolsAPI.LogimportLog, Logger
from .SQLToolsAPI.StorageimportStorage, Settings
from .SQLToolsAPI.ConnectionimportConnection
from .SQLToolsAPI.HistoryimportHistory
USER_FOLDER=None
DEFAULT_FOLDER=None
SETTINGS_FILENAME=None
SETTINGS_FILENAME_DEFAULT=None
CONNECTIONS_FILENAME=None
CONNECTIONS_FILENAME_DEFAULT=None
QUERIES_FILENAME=None
QUERIES_FILENAME_DEFAULT=None
settings=None
queries=None
connections=None
history=None
defstartPlugin():
globalUSER_FOLDER, DEFAULT_FOLDER, SETTINGS_FILENAME, SETTINGS_FILENAME_DEFAULT, CONNECTIONS_FILENAME, CONNECTIONS_FILENAME_DEFAULT, QUERIES_FILENAME, QUERIES_FILENAME_DEFAULT, settings, queries, connections, history
USER_FOLDER=os.path.join(sublime.packages_path(), 'User')
DEFAULT_FOLDER=os.path.dirname(__file__)
SETTINGS_FILENAME=os.path.join(USER_FOLDER, "SQLTools.sublime-settings")
SETTINGS_FILENAME_DEFAULT=os.path.join(DEFAULT_FOLDER, "SQLTools.sublime-settings")
CONNECTIONS_FILENAME=os.path.join(USER_FOLDER, "SQLToolsConnections.sublime-settings")
CONNECTIONS_FILENAME_DEFAULT=os.path.join(DEFAULT_FOLDER, "SQLToolsConnections.sublime-settings")
QUERIES_FILENAME=os.path.join(USER_FOLDER, "SQLToolsSavedQueries.sublime-settings")
QUERIES_FILENAME_DEFAULT=os.path.join(DEFAULT_FOLDER, "SQLToolsSavedQueries.sublime-settings")
settings=Settings(SETTINGS_FILENAME, default=SETTINGS_FILENAME_DEFAULT)
queries=Storage(QUERIES_FILENAME, default=QUERIES_FILENAME_DEFAULT)
connections=Settings(CONNECTIONS_FILENAME, default=CONNECTIONS_FILENAME_DEFAULT)
history=History(settings.get('history_size', 100))
Logger.setPackageVersion(__version__)
Logger.setPackageName(__package__)
Logger.setLogging(settings.get('debug', True))
Connection.setTimeout(settings.get('thread_timeout', 5000))
Connection.setHistoryManager(history)
Log(__package__+" Loaded!")
defgetConnections():
connectionsObj= {}
# fixes #39 and #45
ifnotconnections:
startPlugin()
options=connections.get('connections', {})
forname, configinoptions.items():
connectionsObj[name] =Connection(name, config, settings=settings.all())
# project settings
try:
options=Window().project_data().get('connections', {})
forname, configinoptions.items():
connectionsObj[name] =Connection(name, config, settings=settings.all())
exceptException:
pass
returnconnectionsObj
defloadDefaultConnection():
default=settings.get('default', False)
ifnotdefault:
return
Log('Default database set to '+default+'. Loading options and auto complete.')
returndefault
defoutput(content, panel=None):
ifnotpanel:
panel=getOutputPlace()
panel.run_command('append', {'characters': content})
panel.set_read_only(True)
deftoNewTab(content, name="", suffix="SQLTools Saved Query"):
resultContainer=Window().new_file()
resultContainer.set_name(
((name+" - ") ifname!=""else"") +suffix)
resultContainer.set_syntax_file('Packages/SQL/SQL.tmLanguage')
resultContainer.run_command('append', {'characters': content})
defgetOutputPlace(name="SQLTools Result"):
ifnotsettings.get('show_result_on_window', True):
resultContainer=Window().create_output_panel(name)
Window().run_command("show_panel", {"panel": "output."+name})
else:
resultContainer=None
views=Window().views()
forviewinviews:
ifview.name() ==name:
resultContainer=view
Window().focus_view(resultContainer)
break
ifnotresultContainer:
resultContainer=Window().new_file()
resultContainer.set_name(name)
resultContainer.set_scratch(True) # avoids prompting to save
resultContainer.settings().set("word_wrap", "false")
resultContainer.set_read_only(False)
resultContainer.set_syntax_file('Packages/SQL/SQL.tmLanguage')
ifsettings.get('clear_output', False):
resultContainer.run_command('select_all')
resultContainer.run_command('left_delete')
returnresultContainer
defgetSelection():
text= []
ifView().sel():
forregioninView().sel():
ifregion.empty():
ifnotsettings.get('expand_to_paragraph', False):
text.append(View().substr(View().line(region)))
else:
text.append(View().substr(expand_to_paragraph(View(), region.b)))
else:
text.append(View().substr(region))
returntext
classST(EventListener):
conn=None
tables= []
functions= []
columns= []
connectionList=None
autoCompleteList= []
@staticmethod
defbootstrap():
ST.connectionList=getConnections()
ST.checkDefaultConnection()
@staticmethod
defcheckDefaultConnection():
default=loadDefaultConnection()
ifnotdefault:
return
try:
ST.conn=ST.connectionList.get(default)
ST.loadConnectionData()
exceptException:
Log("Invalid connection setted")
@staticmethod
defloadConnectionData(tablesCallback=None, columnsCallback=None, functionsCallback=None):
ifnotST.conn:
return
deftbCallback(tables):
setattr(ST, 'tables', tables)
iftablesCallback:
tablesCallback()
defcolCallback(columns):
setattr(ST, 'columns', columns)
ifcolumnsCallback:
columnsCallback()
deffuncCallback(functions):
setattr(ST, 'functions', functions)
iffunctionsCallback:
functionsCallback()
ST.conn.getTables(tbCallback)
ST.conn.getColumns(colCallback)
ST.conn.getFunctions(funcCallback)
@staticmethod
defsetConnection(index, tablesCallback=None, columnsCallback=None, functionsCallback=None):
ifindex<0orindex> (len(ST.connectionList) -1):
return
connListNames=list(ST.connectionList.keys())
connListNames.sort()
ST.conn=ST.connectionList.get(connListNames[index])
ST.loadConnectionData(tablesCallback, columnsCallback, functionsCallback)
Log('Connection {0} selected'.format(ST.conn))
@staticmethod
defselectConnection(tablesCallback=None, columnsCallback=None, functionsCallback=None):
ST.connectionList=getConnections()
iflen(ST.connectionList) ==0:
sublime.message_dialog('You need to setup your connections first.')
return
menu= []
forname, conninST.connectionList.items():
menu.append([name, conn._info()])
menu.sort()
Window().show_quick_panel(menu, lambdaindex: ST.setConnection(index, tablesCallback, columnsCallback, functionsCallback))
@staticmethod
defselectTable(callback):
iflen(ST.tables) ==0:
sublime.message_dialog('Your database has no tables.')
return
Window().show_quick_panel(ST.tables, callback)
@staticmethod
defselectFunction(callback):
iflen(ST.functions) ==0:
sublime.message_dialog('Your database has no functions.')
return
Window().show_quick_panel(ST.functions, callback)
@staticmethod
defon_query_completions(view, prefix, locations):
completions=view.extract_completions(prefix)
ifprefix=="":
region=sublime.Region(locations[0], locations[0])
try:
prefix=view.substr(view.line(region)).split(" ").pop()
exceptException:
pass
selectors=settings.get('selectors', [])
ifnotselectors:
returncompletions+ST.getAutoCompleteList(prefix)
forselectorinselectors:
ifview.match_selector(locations[0], selector):
returncompletions+ST.getAutoCompleteList(prefix)
returnNone
@staticmethod
defgetAutoCompleteList(word):
ST.autoCompleteList= []
forwinST.tables:
try:
ifword.lower() inw.lower():
ST.autoCompleteList.append(
("{0}\t({1})".format(w, 'Table'), w))
exceptUnicodeDecodeError:
continue
forwinST.columns:
try:
ifword.lower() inw.lower():
w=w.split(".")
ST.autoCompleteList.append(("{0}\t({1})".format(
w[1], w[0] +' Col'), w[1]))
exceptException:
continue
forwinST.functions:
try:
ifword.lower() inw.lower():
ST.autoCompleteList.append(
("{0}\t({1})".format(w, 'Func'), w))
exceptException:
continue
ST.autoCompleteList.sort()
return (ST.autoCompleteList)
# #
# # Commands
# #
# Usage for old keybindings defined by users
classStShowConnectionMenu(WindowCommand):
@staticmethod
defrun():
Window().run_command('st_select_connection')
classStSelectConnection(WindowCommand):
@staticmethod
defrun():
ST.selectConnection()
classStShowRecords(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnection(tablesCallback=lambda: Window().run_command('st_show_records'))
return
defcb(index):
ifindex<0:
returnNone
returnST.conn.getTableRecords(ST.tables[index], output)
ST.selectTable(cb)
classStDescTable(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnection(tablesCallback=lambda: Window().run_command('st_desc_table'))
return
defcb(index):
ifindex<0:
returnNone
returnST.conn.getTableDescription(ST.tables[index], output)
ST.selectTable(cb)
classStDescFunction(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnection(functionsCallback=lambda: Window().run_command('st_desc_function'))
return
defcb(index):
ifindex<0:
returnNone
functionName=ST.functions[index].split('(', 1)[0]
returnST.conn.getFunctionDescription(functionName, output)
# get everything until first occurence of "(", e.g. get "function_name"
# from "function_name(int)"
ST.selectFunction(cb)
classStExecute(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnection(tablesCallback=lambda: ST.conn.execute(getSelection(), output))
return
ST.conn.execute(getSelection(), output)
classStFormat(TextCommand):
@staticmethod
defrun(edit):
forregioninView().sel():
ifregion.empty():
region=sublime.Region(0, View().size())
selection=View().substr(region)
View().replace(edit, region, Utils.formatSql(selection, settings.get('format', {})))
View().set_syntax_file("Packages/SQL/SQL.tmLanguage")
else:
text=View().substr(region)
View().replace(edit, region, Utils.formatSql(text, settings.get('format', {})))
classStVersion(WindowCommand):
@staticmethod
defrun():
sublime.message_dialog('Using {0} {1}'.format(__package__, __version__))
classStHistory(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnection(functionsCallback=lambda: Window().run_command('st_history'))
return
iflen(history.all()) ==0:
sublime.message_dialog('History is empty.')
return
defcb(index):
ifindex<0:
returnNone
returnST.conn.execute(history.get(index), output)
Window().show_quick_panel(history.all(), cb)
classStSaveQuery(WindowCommand):
@staticmethod
defrun():
query=getSelection()
defcb(alias):
queries.add(alias, query)
Window().show_input_panel('Query alias', '', cb, None, None)
classStListQueries(WindowCommand):
@staticmethod
defrun(mode="run"):
ifnotST.conn:
ST.selectConnection(functionsCallback=lambda: Window().run_command('st_list_queries'))
return
queriesList=queries.all()
iflen(queriesList) ==0:
sublime.message_dialog('No saved queries.')
return
options= []
foralias, queryinqueriesList.items():
options.append([str(alias), str(query)])
options.sort()
defcb(index):
ifindex<0:
returnNone
param2=outputifmode=="run"elseoptions[index][0]
func=ST.conn.executeifmode=="run"elsetoNewTab
returnfunc(options[index][1], param2)
try:
Window().show_quick_panel(options, cb)
exceptException:
pass
classStRemoveSavedQuery(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnection(functionsCallback=lambda: Window().run_command('st_remove_saved_query'))
return
queriesList=queries.all()
iflen(queriesList) ==0:
sublime.message_dialog('No saved queries.')
return
options= []
foralias, queryinqueriesList.items():
options.append([str(alias), str(query)])
options.sort()
defcb(index):
ifindex<0:
returnNone
returnqueries.delete(options[index][0])
try:
Window().show_quick_panel(options, cb)
exceptException:
pass
defWindow():
returnsublime.active_window()
defView():
returnWindow().active_view()
defreload():
try:
# python 3.0 to 3.3
importimp
imp.reload(sys.modules[__package__+".SQLToolsAPI"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Utils"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Storage"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.History"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Log"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Command"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Connection"])
exceptExceptionase:
raise (e)
pass
try:
ST.bootstrap()
exceptException:
pass
defplugin_loaded():
try:
frompackage_controlimportevents
ifevents.install(__name__):
Log('Installed %s!'%events.install(__name__))
elifevents.post_upgrade(__name__):
Log('Upgraded to %s!'%events.post_upgrade(__name__))
sublime.message_dialog(('{0} was upgraded.'+
'If you have any problem,'+
'just restart your Sublime Text.'
).format(__name__)
)
exceptException:
pass
startPlugin()
reload()