Skip to content
This repository was archived by the owner on Mar 12, 2020. It is now read-only.

Commit 4af4f1e

Browse files
committed
Seg Out 3 02:56:14 BRT 2016
1 parent ad01506 commit 4af4f1e

32 files changed

+3937
-1
lines changed

SQLToolsAPI

Lines changed: 0 additions & 1 deletion
This file was deleted.

SQLToolsAPI/.bumpversion.cfg

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[bumpversion]
2+
current_version = 0.0.2
3+
files = __init__.py README.md
4+
commit = True
5+
tag = True
6+

SQLToolsAPI/Command.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import os
2+
import signal
3+
import subprocess
4+
5+
from threading import Thread, Timer
6+
from .Log import Log
7+
8+
9+
class Command:
10+
timeout = 5000
11+
12+
def __init__(self, args, callback, query=None, encoding='utf-8'):
13+
self.query = query
14+
self.process = None
15+
self.args = args
16+
self.encoding = encoding
17+
self.callback = callback
18+
Thread.__init__(self)
19+
20+
def run(self):
21+
if not self.query:
22+
return
23+
24+
self.args = map(str, self.args)
25+
si = None
26+
if os.name == 'nt':
27+
si = subprocess.STARTUPINFO()
28+
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
29+
30+
self.process = subprocess.Popen(self.args,
31+
stdout=subprocess.PIPE,
32+
stderr=subprocess.PIPE,
33+
stdin=subprocess.PIPE,
34+
env=os.environ.copy(),
35+
startupinfo=si)
36+
37+
results, errors = self.process.communicate(input=self.query.encode())
38+
39+
resultString = ''
40+
41+
if results:
42+
resultString += results.decode(self.encoding,
43+
'replace').replace('\r', '')
44+
45+
if errors:
46+
resultString += errors.decode(self.encoding,
47+
'replace').replace('\r', '')
48+
49+
self.callback(resultString)
50+
51+
@staticmethod
52+
def createAndRun(args, query, callback):
53+
command = Command(args, callback, query)
54+
command.run()
55+
56+
57+
class ThreadCommand(Command, Thread):
58+
def __init__(self, args, callback, query=None, encoding='utf-8',
59+
timeout=Command.timeout):
60+
self.query = query
61+
self.process = None
62+
self.args = args
63+
self.encoding = encoding
64+
self.callback = callback
65+
self.timeout = timeout
66+
Thread.__init__(self)
67+
68+
def stop(self):
69+
if not self.process:
70+
return
71+
72+
try:
73+
os.kill(self.process.pid, signal.SIGKILL)
74+
self.process = None
75+
76+
Log.debug("Your command is taking too long to run. Process killed")
77+
except Exception:
78+
pass
79+
80+
@staticmethod
81+
def createAndRun(args, query, callback):
82+
command = ThreadCommand(args, callback, query)
83+
command.start()
84+
killTimeout = Timer(command.timeout, command.stop)
85+
killTimeout.start()

SQLToolsAPI/Connection.py

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import shutil
2+
import shlex
3+
4+
from .Log import Log
5+
from . import Utils as U
6+
from .Command import ThreadCommand as Command
7+
8+
9+
class Connection:
10+
history=None
11+
12+
def __init__(self, name, options, settings={}):
13+
14+
self.cli = settings.get('cli')[options['type']]
15+
cli_path = shutil.which(self.cli)
16+
17+
if cli_path is None:
18+
Log((
19+
"'{0}' could not be found by Sublime Text.\n\n" +
20+
"Please set the '{0}' path in your SQLTools settings " +
21+
"before continue.").format(self.cli))
22+
return
23+
24+
self.settings = settings
25+
self.rowsLimit = settings.get('show_records', {}).get('limit', 50)
26+
self.options = options
27+
self.name = name
28+
self.type = options['type']
29+
self.host = options['host']
30+
self.port = options['port']
31+
self.username = options['username']
32+
self.database = options['database']
33+
34+
if 'encoding' in options:
35+
self.encoding = options['encoding']
36+
37+
if 'password' in options:
38+
self.password = options['password']
39+
40+
if 'service' in options:
41+
self.service = options['service']
42+
43+
def __str__(self):
44+
return self.name
45+
46+
def _info(self):
47+
return 'DB: {0}, Connection: {1}@{2}:{3}'.format(
48+
self.database, self.username, self.host, self.port)
49+
50+
def getTables(self, callback):
51+
query = self.getOptionsForSgdbCli()['queries']['desc']['query']
52+
53+
def cb(result):
54+
callback(U.getResultAsList(result))
55+
56+
Command.createAndRun(self.builArgs('desc'), query, cb)
57+
58+
def getColumns(self, callback):
59+
60+
def cb(result):
61+
callback(U.getResultAsList(result))
62+
63+
try:
64+
query = self.getOptionsForSgdbCli()['queries']['columns']['query']
65+
Command.createAndRun(self.builArgs('columns'), query, cb)
66+
except Exception:
67+
pass
68+
69+
def getFunctions(self, callback):
70+
71+
def cb(result):
72+
callback(U.getResultAsList(result))
73+
74+
try:
75+
query = self.getOptionsForSgdbCli()['queries'][
76+
'functions']['query']
77+
Command.createAndRun(self.builArgs(
78+
'functions'), query, cb)
79+
except Exception:
80+
pass
81+
82+
def getTableRecords(self, tableName, callback):
83+
query = self.getOptionsForSgdbCli()['queries']['show records'][
84+
'query'].format(tableName, self.rowsLimit)
85+
Command.createAndRun(self.builArgs('show records'), query, callback)
86+
87+
def getTableDescription(self, tableName, callback):
88+
query = self.getOptionsForSgdbCli()['queries']['desc table'][
89+
'query'] % tableName
90+
Command.createAndRun(self.builArgs('desc table'), query, callback)
91+
92+
def getFunctionDescription(self, functionName, callback):
93+
query = self.getOptionsForSgdbCli()['queries']['desc function'][
94+
'query'] % functionName
95+
Command.createAndRun(self.builArgs('desc function'), query, callback)
96+
97+
def execute(self, queries, callback):
98+
queryToRun = ''
99+
100+
for query in self.getOptionsForSgdbCli()['before']:
101+
queryToRun += query + "\n"
102+
103+
if isinstance(queries, str):
104+
queries = [queries]
105+
106+
for query in queries:
107+
queryToRun += query + "\n"
108+
109+
queryToRun = queryToRun.rstrip('\n')
110+
111+
Log("Query: " + queryToRun)
112+
113+
if Connection.history:
114+
Connection.history.add(queryToRun)
115+
116+
Command.createAndRun(self.builArgs(), queryToRun, callback)
117+
118+
def builArgs(self, queryName=None):
119+
cliOptions = self.getOptionsForSgdbCli()
120+
args = [self.cli]
121+
122+
if len(cliOptions['options']) > 0:
123+
args = args + cliOptions['options']
124+
125+
if queryName and len(cliOptions['queries'][queryName]['options']) > 0:
126+
args = args + cliOptions['queries'][queryName]['options']
127+
128+
if isinstance(cliOptions['args'], list):
129+
cliOptions['args'] = ' '.join(cliOptions['args'])
130+
131+
cliOptions = cliOptions['args'].format(**self.options)
132+
args = args + shlex.split(cliOptions)
133+
134+
# Log('Using cli args ' + ' '.join(args))
135+
return args
136+
137+
def getOptionsForSgdbCli(self):
138+
return self.settings.get('cli_options', {}).get(self.type)
139+
140+
@staticmethod
141+
def setTimeout(timeout):
142+
Connection.timeout = timeout
143+
Log('Connection timeout setted to {0} seconds'.format(timeout))
144+
145+
@staticmethod
146+
def setHistoryManager(manager):
147+
Connection.history = manager
148+
Log('Connection history defined with max size {0}'.format(manager.getMaxSize()))

SQLToolsAPI/History.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
__version__ = "v0.1.0"
2+
3+
4+
class SizeException(Exception):
5+
pass
6+
7+
8+
class NotFoundException(Exception):
9+
pass
10+
11+
12+
class History:
13+
14+
def __init__(self, maxSize=100):
15+
self.items = []
16+
self.maxSize = maxSize
17+
18+
def add(self, query):
19+
if self.getSize() >= self.getMaxSize():
20+
self.items.pop(0)
21+
self.items.insert(0, query)
22+
23+
def get(self, index):
24+
if index < 0 or index > (len(self.items) - 1):
25+
raise NotFoundException("No query selected")
26+
27+
return self.items[index]
28+
29+
def setMaxSize(self, size=100):
30+
if size < 1:
31+
raise SizeException("Size can't be lower than 1")
32+
33+
self.maxSize = size
34+
return self.maxSize
35+
36+
def getMaxSize(self):
37+
return self.maxSize
38+
39+
def getSize(self):
40+
return len(self.items)
41+
42+
def all(self):
43+
return self.items
44+
45+
def clear(self):
46+
self.items = []
47+
return self.items

SQLToolsAPI/Log.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
VERSION = "v0.1.0"
2+
3+
4+
class Logger:
5+
logging = False
6+
packageName = "SQLTools"
7+
packageVersion = VERSION
8+
9+
@staticmethod
10+
def debug(message):
11+
if not Logger.isLogging():
12+
return
13+
14+
print ("%s (%s): %s" % (Logger.packageName,
15+
Logger.packageVersion,
16+
message))
17+
18+
@staticmethod
19+
def setLogging(param):
20+
Logger.logging = param
21+
Log('Logging is active')
22+
23+
@staticmethod
24+
def isLogging():
25+
return Logger.logging
26+
27+
@staticmethod
28+
def setPackageName(param):
29+
Logger.packageName = param
30+
31+
@staticmethod
32+
def getPackageName():
33+
return Logger.packageName
34+
35+
@staticmethod
36+
def setPackageVersion(param):
37+
Logger.packageVersion = param
38+
39+
@staticmethod
40+
def getPackageVersion():
41+
return Logger.packageVersion
42+
43+
44+
def Log(message):
45+
return Logger.debug(message)

SQLToolsAPI/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## SQLTools API for plugins - v0.0.2
2+
3+
Docs will be ready soon

0 commit comments

Comments
 (0)