1
|
|
|
from _mssql import MSSQLException |
2
|
|
|
import ast |
3
|
|
|
import sys |
4
|
|
|
|
5
|
|
|
from lib.mssql_action import MSSQLAction |
6
|
|
|
from lib.results_processor import ResultsProcessor |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
class MSSQLRunner(MSSQLAction): |
10
|
|
|
""" |
11
|
|
|
Sends an action to MS SQL Server. An exception is logged on failure. |
12
|
|
|
|
13
|
|
|
The query_string accepts Python formatting. Please see README for details. |
14
|
|
|
""" |
15
|
|
|
|
16
|
|
|
# pack action maps to PyMSSQL driver and ResultsProcessor handler |
17
|
|
|
ACTION_DRIVER_PROCESSOR_MAPPING = { |
18
|
|
|
'execute_insert': ('execute_non_query', 'execute_insert') |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
def __init__(self, config): |
22
|
|
|
super(MSSQLRunner, self).__init__(config) |
23
|
|
|
self.processor = ResultsProcessor(self.config) |
24
|
|
|
|
25
|
|
|
def run(self, action, query_string, params=None, server=None, user=None, password=None, database=None): |
26
|
|
|
try: |
27
|
|
|
# action corresponds to a pair of _mssql and ResultsProcessor methods |
28
|
|
|
driver_action, processor_action = self.ACTION_DRIVER_PROCESSOR_MAPPING.get(action, (action, action)) |
29
|
|
|
with self.connect(server, user, password, database) as cursor: |
30
|
|
|
response = getattr(cursor, driver_action)(query_string, ast.literal_eval(params) if params else None) |
31
|
|
|
return getattr(self.processor, processor_action)(response, cursor) |
32
|
|
|
except MSSQLException as e: |
33
|
|
|
self.logger.error(e) |
34
|
|
|
sys.exit(1) |
35
|
|
|
|