-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsql_uploader.py
More file actions
executable file
·468 lines (396 loc) · 17.2 KB
/
sql_uploader.py
File metadata and controls
executable file
·468 lines (396 loc) · 17.2 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SQL uploader module
Responsible for uploading vibration data to SQL server (MySQL/MariaDB), supporting dynamic table creation and batch insertion.
"""
import time
import os
import csv
from datetime import datetime
from typing import List, Optional, Dict
import threading
from loguru import logger
try:
import pymysql
PYMySQL_AVAILABLE = True
except:
logger.warning("[sql_uploader] pymysql not installed, SQL uploader will not work")
PYMySQL_AVAILABLE = False
class SQLUploader:
"""
SQL uploader class, supports dynamic table creation and batch insertion
Handles uploading vibration data to MySQL/MariaDB database with automatic
table creation, batch inserts, and connection management.
"""
def __init__(self, channels: int, label: str, sql_config: Dict[str, str]):
"""
Initialize SQL uploader
Args:
channels: Number of data channels (typically 3: X, Y, Z)
label: Data label/identifier
sql_config: Database configuration dictionary
"""
self.channels = channels
self.label = label
self.sql_config = sql_config
self.connection: Optional[object] = None
self.cursor: Optional[object] = None
self.upload_lock = threading.Lock()
self.is_connected = False
self.current_table_name = None
logger.debug(
f"[sql_uploader] Initialized - Channels: {channels}, Label: {label}, Host: {sql_config.get('host')}"
)
def _get_connection(self):
"""
Get database connection (using pymysql)
Returns:
Database connection object
Raises:
ImportError: If pymysql is not installed
Exception: If connection fails
"""
if not PYMySQL_AVAILABLE:
raise ImportError("pymysql not installed, SQL uploader will not work")
host = self.sql_config.get("host", "localhost")
port = int(self.sql_config.get("port", 3306))
database = self.sql_config.get("database", "daq-prowavedaq-data")
logger.debug(f"[sql_uploader] Connecting to database: {host}:{port}/{database}")
try:
conn = pymysql.connect(
host=host,
port=port,
user=self.sql_config.get("user", "raspberrypi"),
password=self.sql_config.get("password", "Raspberry@Pi"),
database=database,
charset="utf8mb4",
autocommit=False,
)
logger.debug(f"[sql_uploader] Database connection established")
return conn
except Exception as e:
logger.error(f"[sql_uploader] SQL connection failed: {e}")
raise
def _sanitize_table_name(self, table_name: str) -> str:
"""Clean table name, ensure it conforms to SQL naming conventions"""
import re
sanitized = re.sub(r"[^a-zA-Z0-9_]", "_", table_name)
if sanitized and sanitized[0].isdigit():
sanitized = "t_" + sanitized
if not sanitized:
sanitized = "vibration_data"
return sanitized
def create_table(self, table_name: str) -> bool:
"""
Create new table (table name corresponds to CSV file name)
Args:
table_name: Name for the table (will be sanitized)
Returns:
True if table created successfully, False otherwise
"""
logger.debug(f"[sql_uploader] Creating table for: {table_name}")
try:
sanitized_table_name = self._sanitize_table_name(table_name)
logger.trace(f"[sql_uploader] Sanitized table name: {sanitized_table_name}")
if not self.connection:
if not self._reconnect():
logger.error(
"[sql_uploader] Failed to create SQL table: connection failed"
)
return False
try:
self.connection.ping(reconnect=True)
except:
if not self._reconnect():
logger.error(
"[sql_uploader] Failed to create SQL table: connection failed"
)
return False
if not self.cursor:
self.cursor = self.connection.cursor()
# timestamp with 6 decimal places
create_table_sql = f"""
CREATE TABLE IF NOT EXISTS `{sanitized_table_name}` (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
timestamp DATETIME(6) NOT NULL,
label VARCHAR(255) NOT NULL,
channel_1 DOUBLE NOT NULL,
channel_2 DOUBLE NOT NULL,
channel_3 DOUBLE NOT NULL,
INDEX idx_timestamp (timestamp),
INDEX idx_label (label)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
self.cursor.execute(create_table_sql)
self.connection.commit()
self.current_table_name = sanitized_table_name
self.is_connected = True
logger.info(
f"[sql_uploader] SQL table created: {sanitized_table_name} (corresponding CSV: {table_name})"
)
return True
except Exception as e:
logger.error(f"[sql_uploader] Failed to create SQL table: {e}")
self.is_connected = False
return False
def _reconnect(self) -> bool:
"""
Reconnect to SQL server
Returns:
True if reconnection successful, False otherwise
"""
logger.debug("[sql_uploader] Attempting to reconnect to SQL server")
try:
if self.connection:
try:
self.connection.close()
logger.trace("[sql_uploader] Closed old connection")
except:
pass
self.connection = self._get_connection()
self.cursor = self.connection.cursor()
self.is_connected = True
logger.info("[sql_uploader] SQL connection reestablished")
return True
except Exception as e:
logger.error(f"[sql_uploader] Failed to reconnect to SQL server: {e}")
self.is_connected = False
return False
def add_data_block(self, data: List[float]) -> bool:
"""
Add data block to SQL server using batch insert
Args:
data: Data array (should be multiple of channels)
Returns:
True if insert successful, False otherwise
"""
if not data or not self.is_connected:
logger.trace(
f"[sql_uploader] Skipping insert - data: {len(data) if data else 0}, connected: {self.is_connected}"
)
return False
logger.trace(f"[sql_uploader] Adding {len(data)} data points to SQL server")
# Use thread lock to ensure multi-thread safety
with self.upload_lock:
max_retries = 3 # Maximum 3 retries
retry_count = 0
while retry_count < max_retries:
try:
if not self.connection:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
logger.error(
f"[sql_uploader] Failed to add data block: connection failed, retry count: {retry_count}"
)
continue
try:
self.connection.ping(reconnect=True)
except:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
logger.error(
f"[sql_uploader] Failed to add data block: connection failed, retry count: {retry_count}"
)
continue
if not self.current_table_name:
logger.error(
"[sql_uploader] SQL table name not set, cannot insert data. Please call create_table() to create table"
)
return False
insert_sql = f"""
INSERT INTO `{self.current_table_name}` (timestamp, label, channel_1, channel_2, channel_3)
VALUES (%s, %s, %s, %s, %s)
"""
timestamp = datetime.now()
rows_to_insert = []
for i in range(0, len(data), self.channels):
row_data = [
timestamp,
self.label,
data[i] if i < len(data) else 0.0,
data[i + 1] if i + 1 < len(data) else 0.0,
data[i + 2] if i + 2 < len(data) else 0.0,
]
rows_to_insert.append(tuple(row_data))
if rows_to_insert:
if not self.cursor:
self.cursor = self.connection.cursor()
# Batch insert for performance
self.cursor.executemany(insert_sql, rows_to_insert)
self.connection.commit()
logger.trace(
f"[sql_uploader] Successfully inserted {len(rows_to_insert)} rows"
)
return True
except Exception as e:
logger.error(
f"[sql_uploader] Failed to insert data (attempt {retry_count + 1}/{max_retries}): {e}"
)
try:
if self.connection:
self.connection.rollback()
except:
pass
self.is_connected = False
retry_count += 1
if retry_count < max_retries:
time.sleep(0.1 * retry_count)
if not self._reconnect():
continue
else:
logger.error(
f"[sql_uploader] Failed to insert data after {max_retries} attempts, giving up"
)
return False
return False
def upload_from_csv_file(
self, csv_file_path: str, table_name: Optional[str] = None
) -> bool:
"""
Read data from CSV file and upload to SQL server
Args:
csv_file_path: Path to CSV file
table_name: Optional table name (if not provided, inferred from filename)
Returns:
True if upload successful, False otherwise
"""
logger.debug(f"[sql_uploader] Uploading CSV file: {csv_file_path}")
if not os.path.exists(csv_file_path):
logger.error(f"[sql_uploader] CSV file not found: {csv_file_path}")
return False
# If table name is not specified, infer it from the CSV file name
if not table_name:
filename = os.path.basename(csv_file_path)
table_name = os.path.splitext(filename)[0]
logger.trace(
f"[sql_uploader] Inferred table name from filename: {table_name}"
)
# Clean table name
sanitized_table_name = self._sanitize_table_name(table_name)
logger.trace(
f"[sql_uploader] Using sanitized table name: {sanitized_table_name}"
)
# Ensure table exists
if sanitized_table_name != self.current_table_name:
if not self.create_table(table_name):
logger.error(
f"[sql_uploader] Failed to create SQL table: {sanitized_table_name}"
)
return False
# Read CSV file
try:
rows_to_insert = []
with open(csv_file_path, "r", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader) # Skip header row
for row in reader:
if len(row) < 4:
continue
try:
timestamp_str = row[0]
channel_1 = float(row[1])
channel_2 = float(row[2])
channel_3 = float(row[3])
# 解析時間戳記
try:
timestamp = datetime.fromisoformat(timestamp_str)
except:
timestamp = datetime.now()
rows_to_insert.append(
(timestamp, self.label, channel_1, channel_2, channel_3)
)
except (ValueError, IndexError) as e:
logger.warning(
f"[sql_uploader] Skipping invalid CSV row: {row}, error: {e}"
)
continue
if not rows_to_insert:
logger.warning(
f"[sql_uploader] CSV file has no valid data: {csv_file_path}"
)
return True # File is empty,视为成功
# Batch upload
with self.upload_lock:
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
if not self.connection:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
try:
if PYMySQL_AVAILABLE:
self.connection.ping(reconnect=True)
else:
if not self.connection.is_connected():
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
except:
if not self._reconnect():
retry_count += 1
time.sleep(0.1 * retry_count)
continue
if not self.cursor:
self.cursor = self.connection.cursor()
insert_sql = f"""
INSERT INTO `{sanitized_table_name}` (timestamp, label, channel_1, channel_2, channel_3)
VALUES (%s, %s, %s, %s, %s)
"""
# Batch insert for performance
self.cursor.executemany(insert_sql, rows_to_insert)
self.connection.commit()
logger.info(
f"[sql_uploader] Successfully uploaded {len(rows_to_insert)} rows from CSV to table: {sanitized_table_name}"
)
return True
except Exception as e:
logger.error(
f"[sql_uploader] Failed to upload CSV data (attempt {retry_count + 1}/{max_retries}): {e}"
)
try:
if self.connection:
self.connection.rollback()
except:
pass
self.is_connected = False
retry_count += 1
if retry_count < max_retries:
time.sleep(0.1 * retry_count)
if not self._reconnect():
continue
else:
logger.error(
f"[sql_uploader] Failed to upload CSV data after {max_retries} attempts"
)
return False
return False
except Exception as e:
logger.error(f"[sql_uploader] Error reading CSV file: {e}")
return False
def close(self) -> None:
"""Close SQL connection and cleanup resources"""
logger.debug("[sql_uploader] Closing SQL connection")
with self.upload_lock:
try:
if self.cursor:
self.cursor.close()
self.cursor = None
logger.trace("[sql_uploader] Cursor closed")
if self.connection:
self.connection.close()
self.connection = None
logger.trace("[sql_uploader] Connection closed")
self.is_connected = False
logger.info("[sql_uploader] SQL connection closed successfully")
except Exception as e:
logger.error(f"[sql_uploader] Error closing SQL connection: {e}")
def __del__(self):
"""Destructor"""
self.close()