-
Notifications
You must be signed in to change notification settings - Fork 0
/
dm.py
346 lines (261 loc) · 9.03 KB
/
dm.py
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
#!/usr/bin/python3
import argparse
import csv
import os
import re
import sqlite3
from sqlite3 import Error
#import sys
DB_FOLDER = "database"
DB_FILE = "boxiot.db"
DB_SCHEMA = "schema.sql"
CSV_FOLDER = "database/csv"
CSV_ACTIONS = "actions.csv"
CSV_COMBINATIONS = "combinations.csv"
# DB_TABLE_ACTION_TYPES = "ActionTypes"
# DB_TABLE_ACTION = "Actions"
# DB_TABLE_COMBINATION = "Combinations"
# DB_TABLE_COMBINATION_ACTIONS = "CombinationActions"
#region database
def dict_factory(cursor, row):
dict = {}
for idx, col in enumerate(cursor.description):
dict[col[0]] = row[idx]
return dict
def create_connection(database_file):
connection = None
try:
connection = sqlite3.connect(database_file)
connection.row_factory = dict_factory
except Error as e:
print(e)
return connection
def execute_script(connection, sql_script):
cursor = connection.cursor()
cursor.executescript(sql_script)
connection.commit()
def get_action_type(connection, action):
sql = '''
SELECT
*
FROM
ActionTypes
WHERE
Name = :ActionType
'''
cursor = connection.cursor()
cursor.execute(sql, action)
return next(cursor, None)
def insert_action_type(connection, action):
sql = '''
INSERT INTO
ActionTypes
(Name)
VALUES
(:ActionType)
'''
cursor = connection.cursor()
cursor.execute(sql, action)
return cursor.lastrowid
def upsert_action_type(connection, action):
db_action_type = get_action_type(connection, action)
if db_action_type == None:
Id = insert_action_type(connection, action)
else:
Id = db_action_type["Id"]
action["ActionTypeId"] = Id
def get_action(connection, action):
sql = '''
SELECT
*
FROM
Actions
WHERE
Symbol = :Symbol
'''
cursor = connection.cursor()
cursor.execute(sql, action)
return next(cursor, None)
def insert_action(connection, action):
sql = '''
INSERT INTO
Actions
(Symbol, Text, ActionTypeId)
VALUES
(:Symbol, :Text, :ActionTypeId)
'''
cursor = connection.cursor()
cursor.execute(sql, action)
return cursor.lastrowid
def update_action(connection, action):
sql = '''
UPDATE
Actions
SET
Text = :Text
, ActionTypeId = :ActionTypeId
WHERE
Id = :Id
'''
cursor = connection.cursor()
cursor.execute(sql, action)
def upsert_action(connection, action):
upsert_action_type(connection, action)
db_action = get_action(connection, action)
if db_action == None:
insert_action(connection, action)
else:
action['Id'] = db_action['Id']
update_action(connection, action)
def get_combination(connection, combination_actions):
sql = '''
SELECT
*
FROM
Combinations
WHERE
Pattern = :Pattern
'''
cursor = connection.cursor()
cursor.execute(sql, combination_actions)
return next(cursor, None)
def insert_combination(connection, combination_actions):
sql = '''
INSERT INTO
Combinations
(Pattern, Text, ActionCount)
VALUES
(:Pattern, :Text, :ActionCount)
'''
cursor = connection.cursor()
cursor.execute(sql, combination_actions)
return cursor.lastrowid
def update_combination(connection, combination_actions):
sql = '''
UPDATE
Combinations
SET
Text = :Text
WHERE
Id = :Id
'''
cursor = connection.cursor()
cursor.execute(sql, combination_actions)
def get_combination_action(connection, combination_action):
sql = '''
SELECT
*
FROM
CombinationActions
WHERE
CombinationId = :CombinationId
AND ActionId = :ActionId
AND Sequence = :Sequence
AND SubSequence = :SubSequence
'''
cursor = connection.cursor()
cursor.execute(sql, combination_action)
return next(cursor, None)
def insert_combination_action(connection, combination_action):
sql = '''
INSERT INTO
CombinationActions
(CombinationId, ActionId, Sequence, SubSequence)
VALUES
(:CombinationId, :ActionId, :Sequence, :SubSequence)
'''
cursor = connection.cursor()
cursor.execute(sql, combination_action)
return cursor.lastrowid
def upsert_combination(connection, combination_actions):
# upsert_combination_type(connection, combination_actions)
db_combination = get_combination(connection, combination_actions)
if db_combination == None:
combination_actions["Id"] = insert_combination(connection, combination_actions)
else:
combination_actions['Id'] = db_combination['Id']
update_combination(connection, combination_actions)
#endregion database
#region import
regex = re.compile(r"([\[\(\{\/\<]){0,1}([0-9]{0,1})([a-z]{0,5})([\]\)\}\/\>]{0,1})")
def add_action(combination_actions, action, sequence, sub_sequence):
combination_actions["Actions"].append({ "ActionId": action["Id"], "Sequence": sequence, "SubSequence": sub_sequence })
if sub_sequence == 1:
combination_actions["Text"].append(action["Text"])
else:
combination_actions["Text"][-1] += " " + action["Text"]
def convert_combination(combination, actions):
pattern = combination["Combination"]
type = combination["CombinationType"]
combination_actions = { "Pattern": pattern, "CombinationType": type, "Actions": [], "Text": [] }
sequence = 1
for action in pattern.split("-"):
match = regex.match(action)
if match == None:
continue
sub_sequence = 1
if match.group(1):
symbol = match.group(1) + match.group(4)
add_action(combination_actions, actions[symbol], sequence, sub_sequence)
sub_sequence += 1
if match.group(2):
symbol = match.group(2)
add_action(combination_actions, actions[symbol], sequence, sub_sequence)
sub_sequence += 1
if match.group(3):
symbol = match.group(3)
add_action(combination_actions, actions[symbol], sequence, sub_sequence)
sequence += 1
combination_actions["ActionCount"] = len(combination_actions["Text"])
combination_actions["Text"] = ", ".join(combination_actions["Text"])
return combination_actions
def upsert_combination_actions(connection, combination_actions):
upsert_combination(connection, combination_actions)
for combination_action in combination_actions["Actions"]:
combination_action["CombinationId"] = combination_actions["Id"]
db_combination_action = get_combination_action(connection, combination_action)
if db_combination_action == None:
insert_combination_action(connection, combination_action)
#endregion
#region general
def get_file_content(file):
with open(file, "r", encoding="UTF-8") as f:
return f.read()
#endregion
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--database", default=DB_FILE)
parser.add_argument("--create", action="store_true")
parser.add_argument("--import-csv", action="store_true")
parser.add_argument("-f", "--force", action="store_true")
args = parser.parse_args()
args.database = os.path.join(DB_FOLDER, args.database)
if args.create: # TODO: replace with --script [array]
if os.path.isfile(args.database):
if not args.force:
print(f"database {args.database} already exists")
quit()
os.remove(args.database)
connection = create_connection(args.database)
with connection:
# TODO: simply run all numbered files in init folder
for sql_script_file in [DB_SCHEMA]: #, "actiontypes.sql", "actions.sql", "combinations.sql", "combinationactions.sql"]:
sql_script = get_file_content(os.path.join(DB_FOLDER, sql_script_file))
execute_script(connection, sql_script)
if args.import_csv:
actions = {}
with open(os.path.join(CSV_FOLDER, CSV_ACTIONS), encoding="UTF-8") as csv_file:
actions_reader = csv.DictReader(csv_file, delimiter=",", quotechar="\"")
connection = create_connection(args.database)
with connection:
for action in actions_reader:
upsert_action(connection, action)
actions[action["Symbol"]] = action
connection.commit()
with open(os.path.join(CSV_FOLDER, CSV_COMBINATIONS), encoding="UTF-8") as csv_file:
combinations_reader = csv.DictReader(csv_file, delimiter=",", quotechar="\"")
connection = create_connection(args.database)
with connection:
for combination in combinations_reader:
combination_actions = convert_combination(combination, actions)
upsert_combination_actions(connection, combination_actions)
connection.commit()