This repository was archived by the owner on Mar 12, 2020. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathSQLTools.py
More file actions
Latest commit
867 lines (681 loc) · 27.8 KB
/
Copy pathSQLTools.py
File metadata and controls
867 lines (681 loc) · 27.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
__version__="v0.9.12"
importsys
importos
importre
importlogging
fromcollectionsimportOrderedDict
importsublime
fromsublime_pluginimportWindowCommand, EventListener, TextCommand
fromDefault.paragraphimportexpand_to_paragraph
from .SQLToolsAPIimportUtils
from .SQLToolsAPI.StorageimportStorage, Settings
from .SQLToolsAPI.ConnectionimportConnection
from .SQLToolsAPI.HistoryimportHistory
from .SQLToolsAPI.CompletionimportCompletion
MESSAGE_RUNNING_CMD='Executing SQL command...'
SYNTAX_PLAIN_TEXT='Packages/Text/Plain text.tmLanguage'
SYNTAX_SQL='Packages/SQL/SQL.tmLanguage'
SQLTOOLS_SETTINGS_FILE='SQLTools.sublime-settings'
SQLTOOLS_CONNECTIONS_FILE='SQLToolsConnections.sublime-settings'
SQLTOOLS_QUERIES_FILE='SQLToolsSavedQueries.sublime-settings'
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
settingsStore=None
queriesStore=None
connectionsStore=None
historyStore=None
# create pluggin logger
DEFAULT_LOG_LEVEL=logging.WARNING
plugin_logger=logging.getLogger(__package__)
# some plugins are not playing by the rules and configure the root loger
plugin_logger.propagate=False
ifnotplugin_logger.handlers:
plugin_logger_handler=logging.StreamHandler()
plugin_logger_formatter=logging.Formatter("[{name}] {levelname}: {message}", style='{')
plugin_logger_handler.setFormatter(plugin_logger_formatter)
plugin_logger.addHandler(plugin_logger_handler)
plugin_logger.setLevel(DEFAULT_LOG_LEVEL)
logger=logging.getLogger(__name__)
defgetSublimeUserFolder():
returnos.path.join(sublime.packages_path(), 'User')
defstartPlugin():
globalUSER_FOLDER, DEFAULT_FOLDER
globalSETTINGS_FILENAME, SETTINGS_FILENAME_DEFAULT
globalCONNECTIONS_FILENAME, CONNECTIONS_FILENAME_DEFAULT
globalQUERIES_FILENAME, QUERIES_FILENAME_DEFAULT
globalsettingsStore, queriesStore, connectionsStore, historyStore
USER_FOLDER=getSublimeUserFolder()
DEFAULT_FOLDER=os.path.dirname(__file__)
SETTINGS_FILENAME=os.path.join(USER_FOLDER, SQLTOOLS_SETTINGS_FILE)
SETTINGS_FILENAME_DEFAULT=os.path.join(DEFAULT_FOLDER, SQLTOOLS_SETTINGS_FILE)
CONNECTIONS_FILENAME=os.path.join(USER_FOLDER, SQLTOOLS_CONNECTIONS_FILE)
CONNECTIONS_FILENAME_DEFAULT=os.path.join(DEFAULT_FOLDER, SQLTOOLS_CONNECTIONS_FILE)
QUERIES_FILENAME=os.path.join(USER_FOLDER, SQLTOOLS_QUERIES_FILE)
QUERIES_FILENAME_DEFAULT=os.path.join(DEFAULT_FOLDER, SQLTOOLS_QUERIES_FILE)
try:
settingsStore=Settings(SETTINGS_FILENAME, default=SETTINGS_FILENAME_DEFAULT)
exceptExceptionase:
msg='{0}: Failed to parse {1} file'.format(__package__, SQLTOOLS_SETTINGS_FILE)
logging.exception(msg)
Window().status_message(msg)
try:
connectionsStore=Settings(CONNECTIONS_FILENAME, default=CONNECTIONS_FILENAME_DEFAULT)
exceptExceptionase:
msg='{0}: Failed to parse {1} file'.format(__package__, SQLTOOLS_CONNECTIONS_FILE)
logging.exception(msg)
Window().status_message(msg)
queriesStore=Storage(QUERIES_FILENAME, default=QUERIES_FILENAME_DEFAULT)
historyStore=History(settingsStore.get('history_size', 100))
ifsettingsStore.get('debug', False):
plugin_logger.setLevel(logging.DEBUG)
else:
plugin_logger.setLevel(DEFAULT_LOG_LEVEL)
Connection.setTimeout(settingsStore.get('thread_timeout', 15))
Connection.setHistoryManager(historyStore)
logger.info('plugin (re)loaded')
logger.info('version %s', __version__)
defreadConnections():
mergedConnections= {}
# fixes #39 and #45
ifnotconnectionsStore:
startPlugin()
# global connections
globalConnectionsDict=connectionsStore.get('connections', {})
# project-specific connections
projectConnectionsDict= {}
projectData=Window().project_data()
ifprojectData:
projectConnectionsDict=projectData.get('connections', {})
# merge connections
mergedConnections=globalConnectionsDict.copy()
mergedConnections.update(projectConnectionsDict)
ordered=OrderedDict(sorted(mergedConnections.items()))
returnordered
defgetDefaultConnectionName():
default=connectionsStore.get('default', False)
ifnotdefault:
return
returndefault
defcreateOutput(panel=None, syntax=None, prependText=None):
onInitialOutput=None
ifnotpanel:
panel, onInitialOutput=getOutputPlace(syntax)
ifprependText:
panel.run_command('append', {'characters': str(prependText)})
initial=True
defappend(outputContent):
nonlocalinitial
ifinitial:
initial=False
ifonInitialOutput:
onInitialOutput()
# append content
panel.set_read_only(False)
panel.run_command('append', {'characters': outputContent})
panel.set_read_only(True)
returnappend
deftoNewTab(content, name="", suffix="SQLTools Saved Query"):
resultContainer=Window().new_file()
resultContainer.set_name(
((name+" - ") ifname!=""else"") +suffix)
resultContainer.set_syntax_file(SYNTAX_SQL)
resultContainer.run_command('append', {'characters': content})
definsertContent(content):
view=View()
# getting the settings local to this view/tab
viewSettings=view.settings()
# saving the original settings for "auto_indent", or True if none set
autoIndent=viewSettings.get('auto_indent', True)
# turn off automatic indenting otherwise the tabbing of the original
# string is not respected after a newline is encountered
viewSettings.set('auto_indent', False)
view.run_command('insert', {'characters': content})
# restore "auto_indent" setting
viewSettings.set('auto_indent', autoIndent)
defgetOutputPlace(syntax=None, name="SQLTools Result"):
showResultOnWindow=settingsStore.get('show_result_on_window', False)
ifnotshowResultOnWindow:
resultContainer=Window().find_output_panel(name)
ifresultContainerisNone:
resultContainer=Window().create_output_panel(name)
else:
resultContainer=None
views=Window().views()
forviewinviews:
ifview.name() ==name:
resultContainer=view
break
ifnotresultContainer:
resultContainer=Window().new_file()
resultContainer.set_name(name)
resultContainer.set_scratch(True) # avoids prompting to save
resultContainer.set_read_only(True)
resultContainer.settings().set("word_wrap", "false")
defonInitialOutputCallback():
ifsettingsStore.get('clear_output', False):
resultContainer.set_read_only(False)
resultContainer.run_command('select_all')
resultContainer.run_command('left_delete')
resultContainer.set_read_only(True)
# set custom syntax highlight, only if one was passed explicitly,
# otherwise use Plain Text syntax
ifsyntax:
# if custom and SQL related, use that, otherwise defaults to SQL
if'sql'insyntax.lower():
resultContainer.set_syntax_file(syntax)
else:
resultContainer.set_syntax_file(SYNTAX_SQL)
else:
resultContainer.set_syntax_file(SYNTAX_PLAIN_TEXT)
# hide previously set command running message (if any)
Window().status_message('')
ifnotshowResultOnWindow:
# if case this is an output pannel, show it
Window().run_command("show_panel", {"panel": "output."+name})
ifsettingsStore.get('focus_on_result', False):
Window().focus_view(resultContainer)
returnresultContainer, onInitialOutputCallback
defgetSelectionText():
text= []
selectionRegions=getSelectionRegions()
ifnotselectionRegions:
returntext
forregioninselectionRegions:
text.append(View().substr(region))
returntext
defgetSelectionRegions():
expandedRegions= []
ifnotView().sel():
returnNone
# If we would need to expand the empty selection, then which type:
# 'file', 'view' = use text of current view
# 'paragraph' = paragraph(s) (text between newlines)
# 'line' = current line(s)
expandTo=settingsStore.get('expand_to', 'file')
ifnotexpandTo:
expandTo='file'
# keep compatibility with previous settings
expandToParagraph=settingsStore.get('expand_to_paragraph')
ifexpandToParagraphisTrue:
expandTo='paragraph'
expandTo=str(expandTo).strip()
ifexpandTonotin ['file', 'view', 'paragraph', 'line']:
expandTo='file'
forregioninView().sel():
# if user did not select anything - expand selection,
# otherwise use the currently selected region
ifregion.empty():
ifexpandToin ['file', 'view']:
region=sublime.Region(0, View().size())
# no point in further iterating over selections, just use entire file
return [region]
elifexpandTo=='paragraph':
region=expand_to_paragraph(View(), region.b)
else:
# expand to line
region=View().line(region)
# even if we could not expand, avoid adding empty regions
ifnotregion.empty():
expandedRegions.append(region)
returnexpandedRegions
defgetCurrentSyntax():
view=View()
currentSyntax=None
ifview:
currentSyntax=view.settings().get('syntax')
returncurrentSyntax
classST(EventListener):
connectionDict=None
conn=None
tables= []
columns= []
functions= []
completion=None
@staticmethod
defbootstrap():
ST.connectionDict=readConnections()
ST.setDefaultConnection()
@staticmethod
defsetDefaultConnection():
default=getDefaultConnectionName()
ifnotdefault:
return
ifdefaultnotinST.connectionDict:
logger.error('connection "%s" set as default, but it does not exists', default)
return
logger.info('default connection is set to "%s"', default)
ST.setConnection(default)
@staticmethod
defsetConnection(connectionName, callback=None):
ifnotconnectionName:
return
ifconnectionNamenotinST.connectionDict:
return
settings=settingsStore.all()
config=ST.connectionDict.get(connectionName)
promptKeys= [keyforkey, valueinconfig.items() ifvalueisNone]
promptDict= {}
logger.info('[setConnection] prompt keys {}'.format(promptKeys))
defmergeConfig(config, promptedKeys=None):
merged=config.copy()
ifpromptedKeys:
merged.update(promptedKeys)
returnmerged
defcreateConnection(connectionName, config, settings, callback=None):
# if DB cli binary could not be found in path a FileNotFoundError is thrown
try:
ST.conn=Connection(connectionName, config, settings=settings)
exceptFileNotFoundErrorase:
# use only first line of the Exception in status message
Window().status_message(__package__+": "+str(e).splitlines()[0])
raisee
ST.loadConnectionData(callback)
ifnotpromptKeys:
createConnection(connectionName, config, settings, callback)
return
defsetMissingKey(key, value):
nonlocalpromptDict
ifvalueisNone:
return
promptDict[key] =value
ifpromptKeys:
promptNext()
else:
merged=mergeConfig(config, promptDict)
createConnection(connectionName, merged, settings, callback)
defpromptNext():
nonlocalpromptKeys
ifnotpromptKeys:
merged=mergeConfig(config, promptDict)
createConnection(connectionName, merged, settings, callback)
key=promptKeys.pop();
Window().show_input_panel(
'Connection '+key,
'',
lambdauserInput: setMissingKey(key, userInput),
None,
None)
promptNext()
@staticmethod
defloadConnectionData(callback=None):
# clear the list of identifiers (in case connection is changed)
ST.tables= []
ST.columns= []
ST.functions= []
ST.completion=None
objectsLoaded=0
ifnotST.conn:
return
defafterAllDataHasLoaded():
ST.completion=Completion(ST.tables, ST.columns, ST.functions, settings=settingsStore)
logger.info('completions loaded')
if (callback):
callback()
deftablesCallback(tables):
ST.tables=tables
nonlocalobjectsLoaded
objectsLoaded+=1
logger.info('loaded tables : "{0}"'.format(tables))
ifobjectsLoaded==3:
afterAllDataHasLoaded()
defcolumnsCallback(columns):
ST.columns=columns
nonlocalobjectsLoaded
objectsLoaded+=1
logger.info('loaded columns : "{0}"'.format(columns))
ifobjectsLoaded==3:
afterAllDataHasLoaded()
deffunctionsCallback(functions):
ST.functions=functions
nonlocalobjectsLoaded
objectsLoaded+=1
logger.info('loaded functions: "{0}"'.format(functions))
ifobjectsLoaded==3:
logger.info('all objects loaded')
afterAllDataHasLoaded()
ST.conn.getTables(tablesCallback)
ST.conn.getColumns(columnsCallback)
ST.conn.getFunctions(functionsCallback)
@staticmethod
defselectConnectionQuickPanel(callback=None):
ST.connectionDict=readConnections()
iflen(ST.connectionDict) ==0:
sublime.message_dialog('You need to setup your connections first.')
return
defconnectionMenuList(connDictionary):
menuItemsList= []
template='{dbtype}://{user}{host}{port}{db}'
forname, configinST.connectionDict.items():
dbtype=config.get('type', '')
user='{}@'.format(config.get('username', '')) if'username'inconfigelse''
# user = config.get('username', '')
host=config.get('host', '')
port=':{}'.format(config.get('port', '')) if'port'inconfigelse''
db='/{}'.format(config.get('database', '')) if'database'inconfigelse''
connectionInfo=template.format(
dbtype=dbtype,
user=user,
host=host,
port=port,
db=db)
menuItemsList.append([name, connectionInfo])
menuItemsList.sort()
returnmenuItemsList
defonConnectionSelected(index, callback):
menuItemsList=connectionMenuList(ST.connectionDict)
ifindex<0orindex>=len(menuItemsList):
return
connectionName=menuItemsList[index][0]
ST.setConnection(connectionName, callback)
logger.info('Connection "{0}" selected'.format(connectionName))
menu=connectionMenuList(ST.connectionDict)
# show pannel with callback above
Window().show_quick_panel(menu, lambdaindex: onConnectionSelected(index, callback))
@staticmethod
defshowTablesQuickPanel(callback):
iflen(ST.tables) ==0:
sublime.message_dialog('Your database has no tables.')
return
ST.showQuickPanelWithSelection(ST.tables, callback)
@staticmethod
defshowFunctionsQuickPanel(callback):
iflen(ST.functions) ==0:
sublime.message_dialog('Your database has no functions.')
return
ST.showQuickPanelWithSelection(ST.functions, callback)
@staticmethod
defshowQuickPanelWithSelection(arrayOfValues, callback):
w=Window();
view=w.active_view()
selection=view.sel()[0]
initialText=''
# ignore obvious non-identifier selections
ifselection.size() <=128:
(row_begin,_) =view.rowcol(selection.begin())
(row_end,_) =view.rowcol(selection.end())
# only consider selections within same line
ifrow_begin==row_end:
initialText=view.substr(selection)
w.show_quick_panel(arrayOfValues, callback)
w.run_command('insert', {'characters': initialText})
w.run_command("select_all")
@staticmethod
defon_query_completions(view, prefix, locations):
# skip completions, if no connection
ifST.connisNone:
returnNone
ifST.completionisNone:
returnNone
ifST.completion.isDisabled():
returnNone
ifnotlen(locations):
returnNone
ignoreSelectors=ST.completion.getIgnoreSelectors()
ifignoreSelectors:
forselectorinignoreSelectors:
ifview.match_selector(locations[0], selector):
returnNone
activeSelectors=ST.completion.getActiveSelectors()
ifactiveSelectors:
forselectorinactiveSelectors:
ifview.match_selector(locations[0], selector):
break
else:
returnNone
# sublimePrefix = prefix
# sublimeCompletions = view.extract_completions(sublimePrefix, locations[0])
# preferably get prefix ourselves instead of using default sublime "prefix".
# Sublime will return only last portion of this preceding text. Given:
# SELECT table.col|
# sublime will return: "col", and we need: "table.col"
# to know more precisely which completions are more appropriate
# get a Region that starts at the beginning of current line
# and ends at current cursor position
currentPoint=locations[0]
lineStartPoint=view.line(currentPoint).begin()
lineStartToLocation=sublime.Region(lineStartPoint, currentPoint)
try:
lineStr=view.substr(lineStartToLocation)
prefix=re.split('[^`\"\w.\$]+', lineStr).pop()
exceptExceptionase:
logger.debug(e)
# use current paragraph as sql text to parse
sqlRegion=expand_to_paragraph(view, currentPoint)
sql=view.substr(sqlRegion)
sqlToCursorRegion=sublime.Region(sqlRegion.begin(), currentPoint)
sqlToCursor=view.substr(sqlToCursorRegion)
# get completions
autoCompleteList, inhibit=ST.completion.getAutoCompleteList(prefix, sql, sqlToCursor)
# safe check here, so even if we return empty completions and inhibit is true
# we return empty completions to show default sublime completions
ifautoCompleteListisNoneorlen(autoCompleteList) ==0:
returnNone
ifinhibit:
return (autoCompleteList, sublime.INHIBIT_WORD_COMPLETIONS)
returnautoCompleteList
# #
# # Commands
# #
# Usage for old keybindings defined by users
classStShowConnectionMenu(WindowCommand):
@staticmethod
defrun():
Window().run_command('st_select_connection')
classStSelectConnection(WindowCommand):
@staticmethod
defrun():
ST.selectConnectionQuickPanel()
classStShowRecords(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_show_records'))
return
defonTableSelected(index):
ifindex<0:
returnNone
Window().status_message(MESSAGE_RUNNING_CMD)
tableName=ST.tables[index]
prependText='Table "{tableName}"\n'.format(tableName=tableName)
returnST.conn.getTableRecords(
tableName,
createOutput(prependText=prependText))
ST.showTablesQuickPanel(callback=onTableSelected)
classStDescTable(WindowCommand):
@staticmethod
defrun():
currentSyntax=getCurrentSyntax()
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_desc_table'))
return
defonTableSelected(index):
ifindex<0:
returnNone
Window().status_message(MESSAGE_RUNNING_CMD)
returnST.conn.getTableDescription(ST.tables[index], createOutput(syntax=currentSyntax))
ST.showTablesQuickPanel(callback=onTableSelected)
classStDescFunction(WindowCommand):
@staticmethod
defrun():
currentSyntax=getCurrentSyntax()
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_desc_function'))
return
defonFunctionSelected(index):
ifindex<0:
returnNone
Window().status_message(MESSAGE_RUNNING_CMD)
functionName=ST.functions[index].split('(', 1)[0]
returnST.conn.getFunctionDescription(functionName, createOutput(syntax=currentSyntax))
# get everything until first occurrence of "(", e.g. get "function_name"
# from "function_name(int)"
ST.showFunctionsQuickPanel(callback=onFunctionSelected)
classStRefreshConnectionData(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
return
ST.loadConnectionData()
classStExplainPlan(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_explain_plan'))
return
Window().status_message(MESSAGE_RUNNING_CMD)
ST.conn.explainPlan(getSelectionText(), createOutput())
classStExecute(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_execute'))
return
Window().status_message(MESSAGE_RUNNING_CMD)
ST.conn.execute(getSelectionText(), createOutput())
classStExecuteAll(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_execute_all'))
return
Window().status_message(MESSAGE_RUNNING_CMD)
allText=View().substr(sublime.Region(0, View().size()))
ST.conn.execute(allText, createOutput())
classStFormat(TextCommand):
@staticmethod
defrun(edit):
selectionRegions=getSelectionRegions()
ifnotselectionRegions:
return
forregioninselectionRegions:
textToFormat=View().substr(region)
View().replace(edit, region, Utils.formatSql(textToFormat, settingsStore.get('format', {})))
classStFormatAll(TextCommand):
@staticmethod
defrun(edit):
region=sublime.Region(0, View().size())
textToFormat=View().substr(region)
View().replace(edit, region, Utils.formatSql(textToFormat, settingsStore.get('format', {})))
classStVersion(WindowCommand):
@staticmethod
defrun():
sublime.message_dialog('Using {0} {1}'.format(__package__, __version__))
classStHistory(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_history'))
return
iflen(historyStore.all()) ==0:
sublime.message_dialog('History is empty.')
return
defcb(index):
ifindex<0:
returnNone
returnST.conn.execute(historyStore.get(index), createOutput())
Window().show_quick_panel(historyStore.all(), cb)
classStSaveQuery(WindowCommand):
@staticmethod
defrun():
query=getSelectionText()
defcb(alias):
queriesStore.add(alias, query)
Window().show_input_panel('Query alias', '', cb, None, None)
classStListQueries(WindowCommand):
@staticmethod
defrun(mode="run"):
ifmode=="run"andnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_list_queries',
{'mode': mode}))
return
queriesList=queriesStore.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
alias, query=options[index]
ifmode=="run":
ST.conn.execute(query, createOutput())
elifmode=="insert":
insertContent(query)
else:
toNewTab(query, alias)
return
try:
Window().show_quick_panel(options, cb)
exceptException:
pass
classStRemoveSavedQuery(WindowCommand):
@staticmethod
defrun():
ifnotST.conn:
ST.selectConnectionQuickPanel(callback=lambda: Window().run_command('st_remove_saved_query'))
return
queriesList=queriesStore.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
returnqueriesStore.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.Completion"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Storage"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.History"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Command"])
imp.reload(sys.modules[__package__+".SQLToolsAPI.Connection"])
exceptExceptionase:
raise (e)
try:
ST.bootstrap()
exceptException:
pass
defplugin_loaded():
try:
frompackage_controlimportevents
ifevents.install(__name__):
logger.info('Installed %s!'%events.install(__name__))
elifevents.post_upgrade(__name__):
logger.info('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()
defplugin_unloaded():
ifplugin_logger.handlers:
plugin_logger.handlers.pop()