-
Notifications
You must be signed in to change notification settings - Fork 0
/
vehicles.py
221 lines (170 loc) · 6.58 KB
/
vehicles.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
import os
import pymongo
import configparser
from bson.objectid import ObjectId
# Convert Dictionaries to MySQL
class MySqlConverter():
def __init__(self):
self.ve_cols = ['vehicle_id', 'engine_id']
self.ee_cols = ['engine_id', 'ecu_id']
self.vehicles = []
self.engines = []
self.ecus = []
self.vehicle_engines = []
self.engine_ecus = []
def add_vehicles(self, vehicles):
self.vehicles = vehicles
def add_engines(self, engines):
self.engines = engines
def add_ecus(self, ecus):
self.ecus = ecus
def add_vehicle_engines(self, vehicle_engines):
self.vehicle_engines = vehicle_engines
def add_engine_ecus(self, engine_ecus):
self.engine_ecus = engine_ecus
def generate_sql_for(self, name):
if name != 'all':
items = getattr(self, name)
generate_sql(name, name, items)
else:
generate_sql('vehicles', 'Vehicles', self.vehicles)
generate_sql('engines', 'Engines', self.engines)
generate_sql('ecu', 'ECUs', self.ecus)
generate_sql_relationship('VehicleEngine', 'VehicleEngine', self.vehicle_engines)
generate_sql_relationship('EngineEcu', 'EngineEcu', self.engine_ecus)
def generate_sql_vehicle_engine(self):
generate_sql_relationship('VehicleEngine', 'VehicleEngine', self.vehicle_engines)
def generate_sql_engine_ecu(self):
print(self.engine_ecus)
generate_sql_relationship('EngineEcu', 'EngineEcu', self.engine_ecus)
def generate_sql(tablename, filename, items):
dir_path = 'sql' + os.sep
try:
file = open(dir_path + filename + '.sql', 'w')
except PermissionError:
print("access denied in creating file!")
return False
except IOError:
print("could not create file!")
return False
# sql columns
sample_item = next(iter(items or []), None)
keys = ['`%s`' % k for k in sample_item.keys()]
header = list()
header.append("INSERT INTO `%s` (`id`, " % tablename)
header.append(", ".join(keys))
header.append(") VALUES")
file.write("".join(header))
file.write("\n")
for idx, item in enumerate(items):
sql = list()
last = len(items) - 1
values = ['\'%s\'' % v for v in item.values()]
primary_index = str(idx + 1) + ', '
sql.append("(")
sql.append(primary_index)
sql.append(", ".join(values))
if idx == last:
sql.append(")")
else:
sql.append("),")
file.write("".join(sql))
if not idx == last:
file.write("\n")
file.write(";")
file.close()
def generate_sql_relationship(tablename, filename, items):
dir_path = 'sql' + os.sep
try:
file = open(dir_path + filename + '.sql', 'w')
except PermissionError:
print("access denied in creating file!")
return False
except IOError:
print("could not create file!")
return False
# sql columns
sample_item = next(iter(items or []), None)
keys = ['`%s`' % k for k in sample_item.keys()]
header = list()
header.append("INSERT INTO `%s` (`id`, " % tablename)
header.append(", ".join(keys))
header.append(") VALUES")
file.write("".join(header))
file.write("\n")
for idx, item in enumerate(items):
sql = list()
last = len(items) - 1
values = ['\'%s\'' % str(v + 1) for v in item.values()]
primary_index = str(idx + 1) + ', '
sql.append("(")
sql.append(primary_index)
sql.append(", ".join(values))
if idx == last:
sql.append(")")
else:
sql.append("),")
file.write("".join(sql))
if not idx == last:
file.write("\n")
file.write(";")
file.close()
# Transfer Data to MongoDB
class bettermongo():
def __init__(self, vehicles, engines, ecus, vehicle_engines, engine_ecus):
self.parsed_vehicles = vehicles
self.vehicles = list()
self.parsed_engines = engines
self.engines = list()
self.parsed_ecus = ecus
self.ecus = ecus
self.parsed_vehicle_engines = vehicle_engines
self.parsed_engine_ecus = engine_ecus
self.read_config()
self.create_mongo()
def read_config(self):
config = configparser.ConfigParser()
config.read('config.ini')
if config['Mongo']:
self.mongo_host = config['Mongo']['Host']
self.mongo_port = config['Mongo']['Port']
self.mongo_db = config['Mongo']['Database']
self.mongo_username = config['Mongo']['Username']
self.mongo_password = config['Mongo']['Password']
def create_mongo(self):
connection_string = 'mongodb://' + self.mongo_username + ':' + self.mongo_password + '@' + self.mongo_host + ':' + self.mongo_port + '/' + self.mongo_db
self.mongoclient = pymongo.MongoClient(connection_string)
self.db = self.mongoclient[self.mongo_db]
def unify_engines_ecus(self):
for engine in self.parsed_engines:
engine['ecus'] = list()
self.engines.append(engine)
for p_engine in self.parsed_engine_ecus:
if p_engine['engine_id'] is not None and p_engine['ecu_id'] is not None:
engine = self.engines[int(p_engine['engine_id'])]
ecu = self.parsed_ecus[int(p_engine['ecu_id'])]
if ecu not in engine['ecus']:
ecu['_id'] = ObjectId()
engine['ecus'].append(ecu)
def unify_vehicle_engines(self):
for vehicle in self.parsed_vehicles:
vehicle['engines'] = list()
self.vehicles.append(vehicle)
for p_vehicle_engine in self.parsed_vehicle_engines:
if p_vehicle_engine['vehicle_id'] is not None and p_vehicle_engine['engine_id'] is not None:
vehicle = self.vehicles[int(p_vehicle_engine['vehicle_id'])]
engine = self.engines[int(p_vehicle_engine['engine_id'])]
if engine not in vehicle['engines']:
engine['_id'] = ObjectId()
vehicle['engines'].append(engine)
def print_items(self, items):
for item in items:
print(item)
print("\n")
def add_mongo(self):
print('Adding to MongoDB:')
self.unify_engines_ecus()
self.unify_vehicle_engines()
self.print_items(self.vehicles)
result = self.db.vehicles.insert_many(self.vehicles)
print(result)