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 actions map to a pair of methods: PyMSSQL (_mssql) driver and ResultsProcessor handler |
17
|
|
|
ACTION_MAPPING = { |
18
|
|
|
'execute_insert': ('execute_non_query', 'execute_insert') |
19
|
|
|
# default: (action_name, action_name) |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
def __init__(self, config): |
23
|
|
|
super(MSSQLRunner, self).__init__(config) |
24
|
|
|
self.processor = ResultsProcessor(self.config, self.logger) |
25
|
|
|
|
26
|
|
|
def run(self, action, query_string, params=None, |
27
|
|
|
database=None, server=None, user=None, password=None): |
28
|
|
|
try: |
29
|
|
|
# action corresponds to a pair of _mssql and ResultsProcessor methods |
30
|
|
|
driver_action, processor_action = self.ACTION_MAPPING.get(action, (action, action)) |
31
|
|
|
with self.connect(database, server, user, password) as cursor: |
32
|
|
|
params = ast.literal_eval(params) if params else None |
33
|
|
|
response = getattr(cursor, driver_action)(query_string, params) |
34
|
|
|
return getattr(self.processor, processor_action)(response, cursor) |
35
|
|
|
except MSSQLException as e: |
36
|
|
|
self.logger.error(e) |
37
|
|
|
sys.exit(1) |
38
|
|
|
|