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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
| #!/usr/bin/env python3
"""
MySQL Lock Testing - Timeline Analysis Version
"""
import pymysql
import threading
import time
from datetime import datetime
from collections import defaultdict
DB_CONFIG = {
'host': 'localhost',
'user': 'haotian',
'password': 'qwe123qwe123',
'database': 'toy',
'autocommit': False
}
# Test Configuration - Modify as needed
TEST_CONFIG = {
# Session1 Configuration
'session1_operation': 'select_for_update_range', # 'insert', 'select_for_update', 'select_for_update_range'
'insert_start': -1, # Operation start ID
'insert_end': 7, # Operation end ID (exclusive)
'range_size': 2, # Range size (for select_for_update_range only)
# Session2 Test Configuration
'test_ids': [-1, 0, 1, 2, 3, 4, 5, 6, 7], # ID list to test
'lock_`timeout`': 3 # Lock wait `timeout` in seconds
}
# Global log collector
timeline_log = []
log_lock = threading.Lock()
def log_event(session, event_type, sql, result=None, error=None, duration=None):
"""Record event to timeline"""
with log_lock:
timestamp = datetime.now()
timeline_log.append({
'timestamp': timestamp,
'session': session,
'type': event_type, # 'sql', 'info', 'error'
'sql': sql,
'result': result,
'error': error,
'duration': duration
})
# Real-time progress display
time_str = timestamp.strftime("%H:%M:%S.%f")[:-3]
if event_type == 'sql':
progress_text = f"mysql> {sql}"
if duration:
progress_text += f" ({duration:.2f}s)"
elif event_type == 'error':
progress_text = f"ERROR: {error}"
if duration:
progress_text += f" ({duration:.2f}s)"
else:
progress_text = result or sql
print(f"[{time_str}] [{session}] {progress_text}")
def session1():
"""Session1: Loop operations (INSERT or SELECT FOR UPDATE)"""
conn = pymysql.connect(**DB_CONFIG)
cursor = conn.cursor()
operation_type = TEST_CONFIG['session1_operation']
log_event('S1', 'info', '', f'SESSION 1 START - {operation_type.upper()}')
# Check table status
start = time.time()
cursor.execute("SELECT * FROM example_single_pk")
results = cursor.fetchall()
duration = time.time() - start
log_event('S1', 'sql', 'SELECT * FROM example_single_pk', results, duration=duration)
# Loop operations
try:
for target_id in range(TEST_CONFIG['insert_start'], TEST_CONFIG['insert_end']):
log_event('S1', 'info', '', f'=== Round {target_id}: Testing {operation_type.upper()} ID={target_id} ===')
try:
# Start transaction
log_event('S1', 'sql', 'start transaction', 'Query OK, 0 rows affected')
cursor.execute("START TRANSACTION")
if operation_type == 'insert':
# INSERT operation
sql = f"INSERT INTO example_single_pk (id) VALUES ({target_id})"
start = time.time()
try:
cursor.execute(sql)
duration = time.time() - start
log_event('S1', 'sql', sql, 'Query OK, 1 row affected', duration=duration)
except pymysql.err.IntegrityError as e:
duration = time.time() - start
log_event('S1', 'error', sql, None, str(e), duration)
elif operation_type == 'select_for_update':
# SELECT FOR UPDATE operation
sql = f"SELECT * FROM example_single_pk WHERE id = {target_id} FOR UPDATE"
start = time.time()
try:
cursor.execute(sql)
results = cursor.fetchall()
duration = time.time() - start
log_event('S1', 'sql', sql, None)
log_event('S1', 'info', '', f'Query returned {len(results)} rows ({duration:.2f}s)')
if results:
for row in results:
formatted_row = []
for item in row:
if hasattr(item, 'strftime'):
formatted_row.append(item.strftime('%Y-%m-%d %H:%M:%S'))
else:
formatted_row.append(item)
log_event('S1', 'info', '', str(tuple(formatted_row)))
except Exception as e:
duration = time.time() - start
log_event('S1', 'error', sql, None, str(e), duration)
elif operation_type == 'select_for_update_range':
# SELECT FOR UPDATE range operation
range_size = TEST_CONFIG['range_size']
end_id = target_id + range_size
sql = f"SELECT * FROM example_single_pk WHERE id >= {target_id} AND id < {end_id} FOR UPDATE"
start = time.time()
try:
cursor.execute(sql)
results = cursor.fetchall()
duration = time.time() - start
log_event('S1', 'sql', sql, None)
log_event('S1', 'info', '', f'Range query returned {len(results)} rows ({duration:.2f}s)')
if results:
for row in results:
formatted_row = []
for item in row:
if hasattr(item, 'strftime'):
formatted_row.append(item.strftime('%Y-%m-%d %H:%M:%S'))
else:
formatted_row.append(item)
log_event('S1', 'info', '', str(tuple(formatted_row)))
except Exception as e:
duration = time.time() - start
log_event('S1', 'error', sql, None, str(e), duration)
# Notify Session2 and wait
session2_event.set()
session1_event.wait()
session1_event.clear()
# ROLLBACK
log_event('S1', 'sql', 'rollback', 'Query OK, 0 rows affected')
cursor.execute("ROLLBACK")
except Exception as e:
log_event('S1', 'error', 'transaction', None, str(e))
cursor.execute("ROLLBACK")
time.sleep(0.2)
except Exception as e:
log_event('S1', 'error', 'main_loop', None, f'Session1 main loop error: {str(e)}')
finally:
log_event('S1', 'info', '', 'SESSION 1 COMPLETE')
session2_event.set() # Final notification
conn.close()
def session2():
"""Session2: SELECT FOR UPDATE testing"""
log_event('S2', 'info', '', 'SESSION 2 START - Waiting for Session1...')
round_num = 0
total_rounds = TEST_CONFIG['insert_end'] - TEST_CONFIG['insert_start']
while round_num < total_rounds:
session2_event.wait()
session2_event.clear()
if round_num >= total_rounds:
break
log_event('S2', 'info', '', f'=== Round {round_num}: Testing SELECT & INSERT ===')
# Test all configured IDs, testing both SELECT FOR UPDATE and INSERT for each ID
for test_id in TEST_CONFIG['test_ids']:
# Test 1: SELECT FOR UPDATE
conn1 = pymysql.connect(**DB_CONFIG)
cursor1 = conn1.cursor()
try:
cursor1.execute(f"SET innodb_lock_wait_`timeout` = {TEST_CONFIG['lock_`timeout`']}")
cursor1.execute("START TRANSACTION")
# SELECT FOR UPDATE
sql = f"SELECT * FROM example_single_pk WHERE id = {test_id} FOR UPDATE"
log_event('S2', 'sql', sql, None)
start = time.time()
try:
cursor1.execute(sql)
results = cursor1.fetchall()
duration = time.time() - start
log_event('S2', 'info', '', f'SELECT returned {len(results)} rows ({duration:.2f}s)')
if results:
for row in results:
formatted_row = []
for item in row:
if hasattr(item, 'strftime'):
formatted_row.append(item.strftime('%Y-%m-%d %H:%M:%S'))
else:
formatted_row.append(item)
log_event('S2', 'info', '', str(tuple(formatted_row)))
except pymysql.err.OperationalError as e:
duration = time.time() - start
if "Lock wait `timeout`" in str(e):
log_event('S2', 'error', '', result=None, error=f'SELECT `timeout` ({duration:.2f}s)', duration=duration)
else:
log_event('S2', 'error', '', result=None, error=f'SELECT error: {str(e)}', duration=duration)
cursor1.execute("ROLLBACK")
except Exception as e:
log_event('S2', 'error', 'connection', None, f'SELECT connection error: {str(e)}')
finally:
conn1.close()
# Test 2: INSERT
conn2 = pymysql.connect(**DB_CONFIG)
cursor2 = conn2.cursor()
try:
cursor2.execute(f"SET innodb_lock_wait_`timeout` = {TEST_CONFIG['lock_`timeout`']}")
cursor2.execute("START TRANSACTION")
# INSERT
sql = f"INSERT INTO example_single_pk (id) VALUES ({test_id})"
log_event('S2', 'sql', sql, None)
start = time.time()
try:
cursor2.execute(sql)
duration = time.time() - start
log_event('S2', 'info', '', f'INSERT success ({duration:.2f}s)')
except pymysql.err.OperationalError as e:
duration = time.time() - start
if "Lock wait `timeout`" in str(e):
log_event('S2', 'error', '', result=None, error=f'INSERT `timeout` ({duration:.2f}s)', duration=duration)
else:
log_event('S2', 'error', '', result=None, error=f'INSERT error: {str(e)}', duration=duration)
except pymysql.err.IntegrityError as e:
duration = time.time() - start
log_event('S2', 'error', '', result=None, error=f'INSERT duplicate ({duration:.2f}s)', duration=duration)
cursor2.execute("ROLLBACK")
except Exception as e:
log_event('S2', 'error', 'connection', None, f'INSERT connection error: {str(e)}')
finally:
conn2.close()
round_num += 1
session1_event.set()
log_event('S2', 'info', '', 'SESSION 2 COMPLETE')
def print_round_analysis(round_num):
"""Print single round analysis"""
print(f"\n{'='*80}")
print(f"Round {round_num} Analysis")
print(f"{'='*80}")
# Find events for this round
round_events = []
for event in timeline_log:
if (event['session'] == 'S1' and f'Round {round_num}:' in str(event.get('result', ''))) or \
(event['session'] == 'S2' and f'Round {round_num}:' in str(event.get('result', ''))):
round_start_time = event['timestamp']
break
else:
return
# Collect all events for this round
for event in timeline_log:
relative_time = (event['timestamp'] - round_start_time).total_seconds()
if 0 <= relative_time <= 20: # Assume max 20 seconds per round
round_events.append((relative_time, event))
# Display by time columns
operation_type = TEST_CONFIG['session1_operation'].upper()
if operation_type == 'SELECT_FOR_UPDATE_RANGE':
range_size = TEST_CONFIG['range_size']
s1_header = f"SESSION 1 (RANGE+{range_size})"
else:
s1_header = f"SESSION 1 ({operation_type})"
print(f"{'Time':>6} | {s1_header:^35} | {'SESSION 2 (SELECT & INSERT)':^35}")
print("-" * 80)
grouped = defaultdict(list)
for rel_time, event in round_events:
time_bucket = round(rel_time, 1)
grouped[time_bucket].append(event)
for time_bucket in sorted(grouped.keys()):
events = grouped[time_bucket]
s1_events = [e for e in events if e['session'] == 'S1']
s2_events = [e for e in events if e['session'] == 'S2']
max_events = max(len(s1_events), len(s2_events))
for i in range(max_events):
s1_text = ""
s2_text = ""
if i < len(s1_events):
e = s1_events[i]
if e['type'] == 'sql':
s1_text = f"mysql> {e['sql']}"
if e.get('duration'):
s1_text += f" ({e['duration']:.2f}s)"
elif e['type'] == 'info':
s1_text = e['result'] or e['sql']
if i < len(s2_events):
e = s2_events[i]
if e['type'] == 'sql':
s2_text = f"mysql> {e['sql']}"
elif e['type'] == 'info':
if 'Query returned' in str(e['result']):
s2_text = e['result']
elif e['result'] and '(' in str(e['result']):
s2_text = e['result']
elif e['type'] == 'error':
s2_text = f"ERROR: {e['error']}"
time_str = f"{time_bucket:6.1f}" if i == 0 else ""
s1_text = s1_text[:33]
s2_text = s2_text[:33]
print(f"{time_str:>6} | {s1_text:<35} | {s2_text:<35}")
print("=" * 80)
def print_timeline_analysis():
"""Analyze and print timeline"""
# Print analysis for each round first
total_rounds = TEST_CONFIG['insert_end'] - TEST_CONFIG['insert_start']
for round_num in range(total_rounds):
print_round_analysis(round_num)
print(f"\n{'='*150}")
print("Complete Timeline Analysis")
print("="*150)
if not timeline_log:
print("No events recorded")
return
# Group by time, find simultaneous events
grouped_events = defaultdict(list)
base_time = timeline_log[0]['timestamp']
for event in timeline_log:
# Calculate relative time (seconds)
relative_time = (event['timestamp'] - base_time).total_seconds()
# Group by 0.1 second intervals
time_bucket = round(relative_time, 1)
grouped_events[time_bucket].append(event)
# Print column format
print(f"{'Time':>6} | {'SESSION 1 (LEFT)':^70} | {'SESSION 2 (RIGHT)':^70}")
print("-" * 150)
for time_bucket in sorted(grouped_events.keys()):
events = grouped_events[time_bucket]
s1_events = [e for e in events if e['session'] == 'S1']
s2_events = [e for e in events if e['session'] == 'S2']
max_events = max(len(s1_events), len(s2_events))
for i in range(max_events):
s1_text = ""
s2_text = ""
if i < len(s1_events):
e = s1_events[i]
if e['type'] == 'sql':
s1_text = f"mysql> {e['sql']}"
if e['result'] and isinstance(e['result'], str):
s1_text += f"\n{e['result']}"
elif e['result'] and hasattr(e['result'], '__iter__'):
if len(e['result']) == 0:
s1_text += f"\nEmpty set"
else:
# 显示所有数据,格式化datetime
for row in e['result']:
formatted_row = []
for item in row:
if hasattr(item, 'strftime'): # datetime对象
formatted_row.append(item.strftime('%Y-%m-%d %H:%M:%S'))
else:
formatted_row.append(item)
s1_text += f"\n{tuple(formatted_row)}"
s1_text += f"\n{len(e['result'])} rows"
if e['duration']:
s1_text += f" ({e['duration']:.2f}s)"
elif e['type'] == 'error':
s1_text = f"ERROR: {e['error']}"
if e['duration']:
s1_text += f" ({e['duration']:.2f}s)"
else: # info
s1_text = e['result'] or e['sql']
if i < len(s2_events):
e = s2_events[i]
if e['type'] == 'sql':
s2_text = f"mysql> {e['sql']}"
if e['result'] and isinstance(e['result'], str):
s2_text += f"\n{e['result']}"
elif e['result'] and hasattr(e['result'], '__iter__'):
if len(e['result']) == 0:
s2_text += f"\nEmpty set"
else:
# 显示所有数据,格式化datetime
for row in e['result']:
formatted_row = []
for item in row:
if hasattr(item, 'strftime'): # datetime对象
formatted_row.append(item.strftime('%Y-%m-%d %H:%M:%S'))
else:
formatted_row.append(item)
s2_text += f"\n{tuple(formatted_row)}"
s2_text += f"\n{len(e['result'])} rows"
if e['duration']:
s2_text += f" ({e['duration']:.2f}s)"
elif e['type'] == 'error':
s2_text = f"ERROR: {e['error']}"
if e['duration']:
s2_text += f" ({e['duration']:.2f}s)"
else: # info
s2_text = e['result'] or e['sql']
# Handle multi-line text
s1_lines = s1_text.split('\n') if s1_text else ['']
s2_lines = s2_text.split('\n') if s2_text else ['']
max_lines = max(len(s1_lines), len(s2_lines))
for j in range(max_lines):
time_str = f"{time_bucket:6.1f}" if i == 0 and j == 0 else ""
s1_line = s1_lines[j] if j < len(s1_lines) else ""
s2_line = s2_lines[j] if j < len(s2_lines) else ""
# Increase display width, reduce truncation
s1_line = s1_line[:80] if s1_line.startswith('mysql>') else s1_line[:70]
s2_line = s2_line[:80] if s2_line.startswith('mysql>') else s2_line[:70]
print(f"{time_str:>6} | {s1_line:<70} | {s2_line:<70}")
print("=" * 150)
# Event objects
session1_event = threading.Event()
session2_event = threading.Event()
if __name__ == "__main__":
operation_type = TEST_CONFIG['session1_operation'].upper()
print("MySQL Lock Test - Timeline Collection Mode")
print(f"Session1: {operation_type} operations")
print(f"Session2: SELECT FOR UPDATE & INSERT tests")
print("Collecting all events with timestamps...")
t1 = threading.Thread(target=session1)
t2 = threading.Thread(target=session2)
t2.start()
time.sleep(0.1)
t1.start()
t1.join()
t2.join()
print_timeline_analysis()
print("\nAnalysis Complete!")
|