Repository navigation
Expand file tree
/
Copy pathtransaction.c
More file actions
897 lines (746 loc) · 28.2 KB
/
Copy pathtransaction.c
File metadata and controls
897 lines (746 loc) · 28.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
// transaction.c
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include "database.h"
#ifdef _WIN32
// Windows 下没有 strcasecmp 和 strncasecmp
// 需要映射到微软特有的 _stricmp 和 _strnicmp
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#define strdup _strdup
#endif
// ==================== 事务文件定义 ====================
#define TRANS_FILE_ACTIVE "system_transactions.dat"
#define TRANS_FILE_LOCKS "system_locks.dat"
#define TRANS_FILE_LOGS "system_transaction_logs.dat"
// DDL 专用锁拥有者 ID(用于在非事务上下文持有锁,如 ALTER TABLE)
#define DDL_LOCK_OWNER_ID (-999)
// ==================== 全局变量 ====================
int CURRENT_TRANSACTION_ID = 0; // 当前活动事务ID,0表示无活动事务
Transaction* currentTransaction = NULL; // 当前事务指针
// ==================== 辅助函数 ====================
// 不区分大小写的字符串查找函数
static char* stristr(const char* haystack, const char* needle) {
if (!haystack || !needle || !*needle) return NULL;
const char* p1 = haystack;
const char* p2 = needle;
const char* r = *p2 == 0 ? haystack : 0;
while (*p1 != 0 && *p2 != 0) {
if (tolower((unsigned char)*p1) == tolower((unsigned char)*p2)) {
if (r == 0) r = p1;
p2++;
} else {
p2 = needle;
if (r != 0) {
p1 = r + 1;
r = 0;
continue;
}
}
p1++;
}
return (*p2 == 0) ? (char*)r : NULL;
}
// 生成新的事务ID
static int generate_transaction_id() {
static int nextId = 1;
return nextId++;
}
// 直接修改数据文件中记录的有效性标记
static int dat_modify_record_validity(long recordOffset, int isValid) {
if (recordOffset == INVALID_OFFSET) {
return 0;
}
FILE* fp = fopen(DB_FILE_DATA, "rb+");
if (!fp) {
return 0;
}
fseek(fp, recordOffset, SEEK_SET);
RecordHeader rh;
if (fread(&rh, sizeof(RecordHeader), 1, fp) != 1) {
fclose(fp);
return 0;
}
// 修改有效性标记
rh.bValid = isValid ? 1 : 0;
fseek(fp, recordOffset, SEEK_SET);
fwrite(&rh, sizeof(RecordHeader), 1, fp);
fclose(fp);
return 1;
}
// 在指定偏移量处恢复记录数据
static int dat_restore_record_at_offset(long recordOffset, void* data, int size) {
if (recordOffset == INVALID_OFFSET || !data || size <= 0) {
return 0;
}
FILE* fp = fopen(DB_FILE_DATA, "rb+");
if (!fp) {
return 0;
}
// 跳过RecordHeader
fseek(fp, recordOffset + sizeof(RecordHeader), SEEK_SET);
fwrite(data, size, 1, fp);
// 设置记录为有效
fseek(fp, recordOffset, SEEK_SET);
RecordHeader rh;
rh.bValid = 1;
fwrite(&rh, sizeof(RecordHeader), 1, fp);
fclose(fp);
return 1;
}
// 初始化事务系统文件
int init_transaction_system() {
FILE* fp;
// 检查并创建事务文件
fp = fopen(TRANS_FILE_ACTIVE, "rb");
if (!fp) {
fp = fopen(TRANS_FILE_ACTIVE, "wb");
if (fp) fclose(fp);
} else {
fclose(fp);
}
// 检查并创建锁文件
fp = fopen(TRANS_FILE_LOCKS, "rb");
if (!fp) {
fp = fopen(TRANS_FILE_LOCKS, "wb");
if (fp) fclose(fp);
} else {
fclose(fp);
}
// 检查并创建日志文件
fp = fopen(TRANS_FILE_LOGS, "rb");
if (!fp) {
fp = fopen(TRANS_FILE_LOGS, "wb");
if (fp) fclose(fp);
} else {
fclose(fp);
}
// 初始化当前事务状态
CURRENT_TRANSACTION_ID = 0;
currentTransaction = NULL;
return 1;
}
// ==================== 事务解析器 ====================
// 解析 BEGIN TRANSACTION 语句
void parse_begin_statement(const char* sql, TransactionCommand* cmd) {
if (!sql || !cmd) return;
cmd->commandType = 10; // BEGIN TRANSACTION
memset(&cmd->transData.beginStmt, 0, sizeof(cmd->transData.beginStmt));
}
// 解析 COMMIT 语句
void parse_commit_statement(const char* sql, TransactionCommand* cmd) {
if (!sql || !cmd) return;
cmd->commandType = 11; // COMMIT
memset(&cmd->transData.commitStmt, 0, sizeof(cmd->transData.commitStmt));
}
// 解析 ROLLBACK 语句
void parse_rollback_statement(const char* sql, TransactionCommand* cmd) {
if (!sql || !cmd) return;
cmd->commandType = 12; // ROLLBACK
memset(&cmd->transData.rollbackStmt, 0, sizeof(cmd->transData.rollbackStmt));
}
// 解析 LOCK TABLE 语句
void parse_lock_statement(const char* sql, TransactionCommand* cmd) {
if (!sql || !cmd) return;
cmd->commandType = 13; // LOCK TABLE
// 跳过 "LOCK TABLE " (11个字符)
const char* ptr = sql + 11;
// 跳过空格
while (*ptr && isspace(*ptr)) ptr++;
// 提取表名
char tableName[TABLE_NAME_LEN] = {0};
int i = 0;
while (*ptr && !isspace(*ptr) && i < TABLE_NAME_LEN - 1) {
tableName[i++] = *ptr++;
}
tableName[i] = '\0';
// 跳过空格
while (*ptr && isspace(*ptr)) ptr++;
// 检查锁类型
LockType lockType = LOCK_SHARED;
if (strncasecmp(ptr, "SHARE", 5) == 0) {
lockType = LOCK_SHARED;
} else if (strncasecmp(ptr, "EXCLUSIVE", 9) == 0) {
lockType = LOCK_EXCLUS;
}
// 填充命令结构
strncpy(cmd->transData.lockStmt.tableName, tableName, TABLE_NAME_LEN - 1);
cmd->transData.lockStmt.tableName[TABLE_NAME_LEN - 1] = '\0';
cmd->transData.lockStmt.lockType = lockType;
}
// 事务解析器主函数
TransactionCommand* transaction_parser_main(const char* input) {
if (!input) return NULL;
// 去除前后空格
char* trimmed = strdup(input);
char* start = trimmed;
while (*start && isspace(*start)) start++;
char* end = start + strlen(start) - 1;
while (end > start && isspace(*end)) end--;
*(end + 1) = '\0';
if (strlen(start) == 0) {
free(trimmed);
return NULL;
}
// 转换为大写以便比较
char* upper = strdup(start);
for (int i = 0; upper[i]; i++) {
upper[i] = toupper(upper[i]);
}
// 创建命令结构
TransactionCommand* cmd = (TransactionCommand*)malloc(sizeof(TransactionCommand));
if (!cmd) {
free(trimmed);
free(upper);
return NULL;
}
memset(cmd, 0, sizeof(TransactionCommand));
// 根据命令类型调用相应的解析函数
if (strstr(upper, "BEGIN") == upper || strstr(upper, "START TRANSACTION") == upper) {
parse_begin_statement(start, cmd);
} else if (strstr(upper, "COMMIT") == upper) {
parse_commit_statement(start, cmd);
} else if (strstr(upper, "ROLLBACK") == upper) {
parse_rollback_statement(start, cmd);
} else if (strstr(upper, "LOCK TABLE") == upper) {
parse_lock_statement(start, cmd);
} else {
// 未知命令
free(cmd);
cmd = NULL;
}
free(trimmed);
free(upper);
return cmd;
}
// 获取当前事务ID
int get_current_transaction_id() {
return CURRENT_TRANSACTION_ID;
}
// 检查是否在事务中
int is_in_transaction() {
return CURRENT_TRANSACTION_ID != 0;
}
// ==================== 事务管理 ====================
// 开始事务
int cmd_begin_transaction() {
if (CURRENT_TRANSACTION_ID != 0) {
printf("Error: There is already an active transaction (ID: %d). Please commit or rollback the current transaction first.\n", CURRENT_TRANSACTION_ID);
return 0;
}
// 创建新事务
currentTransaction = (Transaction*)malloc(sizeof(Transaction));
if (!currentTransaction) {
printf("Error: Memory allocation failed.\n");
return 0;
}
CURRENT_TRANSACTION_ID = generate_transaction_id();
currentTransaction->transactionId = CURRENT_TRANSACTION_ID;
currentTransaction->state = TRANS_ACTIVE;
strncpy(currentTransaction->userName, CURRENT_USER, TABLE_NAME_LEN - 1);
currentTransaction->userName[TABLE_NAME_LEN - 1] = '\0';
currentTransaction->startTime = time(NULL);
currentTransaction->endTime = 0;
currentTransaction->logEntryCount = 0;
currentTransaction->logEntries = NULL;
printf("Success: Transaction started (ID: %d, User: %s)\n", CURRENT_TRANSACTION_ID, CURRENT_USER);
return 1;
}
// 提交事务
int cmd_commit_transaction() {
if (CURRENT_TRANSACTION_ID == 0) {
printf("Error: No active transaction.\n");
return 0;
}
if (!currentTransaction) {
printf("Error: Transaction data corrupted.\n");
CURRENT_TRANSACTION_ID = 0;
return 0;
}
// 更新事务状态
currentTransaction->state = TRANS_COMMITTED;
currentTransaction->endTime = time(NULL);
// 释放所有锁
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "rb");
if (lockFile) {
// 读取所有锁,过滤掉当前事务的锁
Lock* locks = NULL;
int lockCount = 0;
int capacity = 10;
locks = (Lock*)malloc(sizeof(Lock) * capacity);
Lock lock;
while (fread(&lock, sizeof(Lock), 1, lockFile) == 1) {
if (lock.transactionId != CURRENT_TRANSACTION_ID) {
if (lockCount >= capacity) {
capacity *= 2;
locks = (Lock*)realloc(locks, sizeof(Lock) * capacity);
}
locks[lockCount++] = lock;
}
}
fclose(lockFile);
// 写回文件(排除当前事务的锁)
lockFile = fopen(TRANS_FILE_LOCKS, "wb");
if (lockFile) {
for (int i = 0; i < lockCount; i++) {
fwrite(&locks[i], sizeof(Lock), 1, lockFile);
}
fclose(lockFile);
}
free(locks);
}
// 保存事务记录
FILE* transFile = fopen(TRANS_FILE_ACTIVE, "ab");
if (transFile) {
fwrite(currentTransaction, sizeof(Transaction), 1, transFile);
fclose(transFile);
}
// 清理事务日志
if (currentTransaction->logEntries) {
for (int i = 0; i < currentTransaction->logEntryCount; i++) {
TransactionLogEntry* entry = currentTransaction->logEntries[i];
if (entry->oldData) free(entry->oldData);
if (entry->newData) free(entry->newData);
free(entry);
}
free(currentTransaction->logEntries);
}
printf("Success: Transaction committed (ID: %d, Duration: %ld seconds)\n",
CURRENT_TRANSACTION_ID,
currentTransaction->endTime - currentTransaction->startTime);
free(currentTransaction);
currentTransaction = NULL;
CURRENT_TRANSACTION_ID = 0;
return 1;
}
// 回滚事务
int cmd_rollback_transaction() {
if (CURRENT_TRANSACTION_ID == 0) {
printf("Error: No active transaction.\n");
return 0;
}
if (!currentTransaction) {
printf("Error: Transaction data corrupted.\n");
CURRENT_TRANSACTION_ID = 0;
return 0;
}
printf("Rolling back transaction (ID: %d)...\n", CURRENT_TRANSACTION_ID);
printf("Total log entries to rollback: %d\n", currentTransaction->logEntryCount);
// 回滚所有操作(逆序执行)
for (int i = currentTransaction->logEntryCount - 1; i >= 0; i--) {
TransactionLogEntry* entry = currentTransaction->logEntries[i];
printf(" Processing log entry %d: Type=%d, Table=%s, Offset=%ld, DataSize=%d\n",
i, entry->entryType, entry->tableName, entry->recordOffset, entry->dataSize);
switch (entry->entryType) {
case LOG_INSERT:
// 回滚插入:将记录标记为无效
printf(" Rolling back INSERT: Table %s, Offset %ld\n", entry->tableName, entry->recordOffset);
if (entry->recordOffset != INVALID_OFFSET) {
// 直接修改记录的有效性标记为0(无效)
if (dat_modify_record_validity(entry->recordOffset, 0)) {
printf(" Success: Insert rolled back (record marked as invalid)\n");
} else {
printf(" Warning: Failed to mark record as invalid during rollback\n");
}
} else {
printf(" Error: Invalid record offset for rollback\n");
}
break;
case LOG_DELETE:
// 回滚删除:在原来的位置恢复记录
printf(" Rolling back DELETE: Table %s, Offset %ld\n", entry->tableName, entry->recordOffset);
if (entry->oldData && entry->recordOffset != INVALID_OFFSET && entry->dataSize > 0) {
// 在原来的偏移量处恢复记录数据
if (dat_restore_record_at_offset(entry->recordOffset, entry->oldData, entry->dataSize)) {
printf(" Success: Delete rolled back (record restored at original offset)\n");
} else {
printf(" Warning: Failed to restore record during rollback\n");
}
} else {
printf(" Error: No old data or invalid offset for rollback (oldData=%p, offset=%ld, dataSize=%d)\n",
entry->oldData, entry->recordOffset, entry->dataSize);
}
break;
case LOG_UPDATE:
// 回滚更新:恢复原始数据
printf(" Rolling back UPDATE: Table %s, Offset %ld\n", entry->tableName, entry->recordOffset);
if (entry->oldData && entry->recordOffset != -1 && entry->dataSize > 0) {
// 计算记录大小
TableMeta table;
if (dbf_get_schema(entry->tableName, &table)) {
printf(" Table schema loaded: %d fields\n", table.iFieldCount);
int recordSize = 0;
for (int j = 0; j < table.iFieldCount; j++) {
recordSize += table.fields[j].iSize;
}
// 确保数据大小匹配
if (recordSize != entry->dataSize) {
printf(" Warning: Record size mismatch (expected %d, got %d)\n", recordSize, entry->dataSize);
recordSize = entry->dataSize; // 使用日志中记录的大小
}
printf(" Attempting to overwrite record at offset %ld with %d bytes\n",
entry->recordOffset, recordSize);
// 调用底层覆盖函数恢复原始数据
if (dat_overwrite_record(entry->recordOffset, entry->oldData, recordSize)) {
printf(" Success: Update rolled back (data restored)\n");
} else {
printf(" Warning: Failed to restore data during rollback\n");
}
} else {
printf(" Error: Could not get table schema for %s\n", entry->tableName);
}
} else {
printf(" Error: No old data or invalid offset for rollback (oldData=%p, offset=%ld, dataSize=%d)\n",
entry->oldData, entry->recordOffset, entry->dataSize);
}
break;
}
}
// 更新事务状态
currentTransaction->state = TRANS_ROLLEDBACK;
currentTransaction->endTime = time(NULL);
// 释放所有锁
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "rb");
if (lockFile) {
// 读取所有锁,过滤掉当前事务的锁
Lock* locks = NULL;
int lockCount = 0;
int capacity = 10;
locks = (Lock*)malloc(sizeof(Lock) * capacity);
Lock lock;
while (fread(&lock, sizeof(Lock), 1, lockFile) == 1) {
if (lock.transactionId != CURRENT_TRANSACTION_ID) {
if (lockCount >= capacity) {
capacity *= 2;
locks = (Lock*)realloc(locks, sizeof(Lock) * capacity);
}
locks[lockCount++] = lock;
}
}
fclose(lockFile);
// 写回文件(排除当前事务的锁)
lockFile = fopen(TRANS_FILE_LOCKS, "wb");
if (lockFile) {
for (int i = 0; i < lockCount; i++) {
fwrite(&locks[i], sizeof(Lock), 1, lockFile);
}
fclose(lockFile);
}
free(locks);
}
// 保存事务记录
FILE* transFile = fopen(TRANS_FILE_ACTIVE, "ab");
if (transFile) {
fwrite(currentTransaction, sizeof(Transaction), 1, transFile);
fclose(transFile);
}
// 清理事务日志
if (currentTransaction->logEntries) {
for (int i = 0; i < currentTransaction->logEntryCount; i++) {
TransactionLogEntry* entry = currentTransaction->logEntries[i];
if (entry->oldData) free(entry->oldData);
if (entry->newData) free(entry->newData);
free(entry);
}
free(currentTransaction->logEntries);
}
printf("Success: Transaction rolled back (ID: %d)\n", CURRENT_TRANSACTION_ID);
free(currentTransaction);
currentTransaction = NULL;
CURRENT_TRANSACTION_ID = 0;
return 1;
}
// ==================== 锁管理 ====================
// 检查锁冲突
int check_lock_conflict(const char* tableName, long recordOffset, LockType requestedLock) {
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "rb");
if (!lockFile) {
return 0; // 没有锁文件,无冲突
}
Lock lock;
int hasConflict = 0;
while (fread(&lock, sizeof(Lock), 1, lockFile) == 1) {
// 检查是否是同一张表
if (strcmp(lock.tableName, tableName) != 0) {
continue;
}
// 检查是否是同一记录或表级锁
if (lock.recordOffset == -1 || recordOffset == -1 || lock.recordOffset == recordOffset) {
// 锁冲突规则:
// 1. 排他锁与任何锁都冲突
// 2. 共享锁只与排他锁冲突
if (requestedLock == LOCK_EXCLUS) {
// 请求排他锁:与任何现有锁都冲突
hasConflict = 1;
break;
} else if (requestedLock == LOCK_SHARED && lock.lockType == LOCK_EXCLUS) {
// 请求共享锁:只与现有排他锁冲突
hasConflict = 1;
break;
}
}
}
fclose(lockFile);
return hasConflict;
}
// 获取锁(事务上下文,保持原行为)
int acquire_lock(const char* tableName, long recordOffset, LockType lockType) {
if (CURRENT_TRANSACTION_ID == 0) {
printf("Error: No active transaction, cannot acquire lock.\n");
return 0;
}
// 检查锁冲突
if (check_lock_conflict(tableName, recordOffset, lockType)) {
printf("Error: Lock conflict. Table %s is already locked by another transaction.\n", tableName);
return 0;
}
// 创建锁
Lock lock;
memset(&lock, 0, sizeof(Lock));
strncpy(lock.tableName, tableName, TABLE_NAME_LEN - 1);
lock.tableName[TABLE_NAME_LEN - 1] = '\0';
lock.recordOffset = recordOffset;
lock.lockType = lockType;
lock.transactionId = CURRENT_TRANSACTION_ID;
strncpy(lock.userName, CURRENT_USER, TABLE_NAME_LEN - 1);
lock.userName[TABLE_NAME_LEN - 1] = '\0';
// 保存锁
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "ab");
if (!lockFile) {
printf("Error: Cannot open lock file.\n");
return 0;
}
fwrite(&lock, sizeof(Lock), 1, lockFile);
fclose(lockFile);
printf("Success: Acquired %s lock (Table: %s, Record offset: %ld, Transaction ID: %d)\n",
lockType == LOCK_SHARED ? "shared" : "exclusive",
tableName, recordOffset, CURRENT_TRANSACTION_ID);
return 1;
}
// 释放锁(事务上下文,保持原行为)
int release_lock(const char* tableName, long recordOffset) {
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "rb");
if (!lockFile) {
return 0; // 没有锁文件
}
// 读取所有锁,排除要释放的锁
Lock* locks = NULL;
int lockCount = 0;
int capacity = 10;
locks = (Lock*)malloc(sizeof(Lock) * capacity);
Lock lock;
int found = 0;
while (fread(&lock, sizeof(Lock), 1, lockFile) == 1) {
if (strcmp(lock.tableName, tableName) == 0 &&
lock.recordOffset == recordOffset &&
lock.transactionId == CURRENT_TRANSACTION_ID) {
found = 1;
continue; // 跳过这个锁
}
if (lockCount >= capacity) {
capacity *= 2;
locks = (Lock*)realloc(locks, sizeof(Lock) * capacity);
}
locks[lockCount++] = lock;
}
fclose(lockFile);
if (!found) {
free(locks);
return 0; // 没有找到要释放的锁
}
// 写回文件
lockFile = fopen(TRANS_FILE_LOCKS, "wb");
if (!lockFile) {
free(locks);
return 0;
}
for (int i = 0; i < lockCount; i++) {
fwrite(&locks[i], sizeof(Lock), 1, lockFile);
}
fclose(lockFile);
free(locks);
printf("Success: Released lock (Table: %s, Record offset: %ld, Transaction ID: %d)\n",
tableName, recordOffset, CURRENT_TRANSACTION_ID);
return 1;
}
// =========== 新增:支持指定 ownerId 的加/释放锁(用于 DDL,不依赖事务) ===========
// 获取锁(指定 ownerId,不要求当前处于事务内)
static int acquire_lock_with_owner(const char* tableName, long recordOffset, LockType lockType, int ownerId) {
// 检查锁冲突(与现有任何锁冲突规则相同)
if (check_lock_conflict(tableName, recordOffset, lockType)) {
printf("Error: Lock conflict. Table %s is already locked by another transaction or DDL.\n", tableName);
return 0;
}
Lock lock;
memset(&lock, 0, sizeof(Lock));
strncpy(lock.tableName, tableName, TABLE_NAME_LEN - 1);
lock.tableName[TABLE_NAME_LEN - 1] = '\0';
lock.recordOffset = recordOffset;
lock.lockType = lockType;
lock.transactionId = ownerId; // 关键:使用 ownerId(例如 DDL_LOCK_OWNER_ID)
// 记录用户名以便诊断;对于 DDL 可写 CURRENT_USER 或特殊标识
strncpy(lock.userName, CURRENT_USER, TABLE_NAME_LEN - 1);
lock.userName[TABLE_NAME_LEN - 1] = '\0';
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "ab");
if (!lockFile) {
printf("Error: Cannot open lock file.\n");
return 0;
}
fwrite(&lock, sizeof(Lock), 1, lockFile);
fclose(lockFile);
printf("Success: Acquired %s lock (Table: %s, Record offset: %ld, Owner ID: %d)\n",
lockType == LOCK_SHARED ? "shared" : "exclusive",
tableName, recordOffset, ownerId);
return 1;
}
// 释放锁(指定 ownerId,不要求当前处于事务内)
static int release_lock_with_owner(const char* tableName, long recordOffset, int ownerId) {
FILE* lockFile = fopen(TRANS_FILE_LOCKS, "rb");
if (!lockFile) return 0;
Lock* locks = NULL;
int lockCount = 0, cap = 10;
locks = (Lock*)malloc(sizeof(Lock) * cap);
Lock lock;
int found = 0;
while (fread(&lock, sizeof(Lock), 1, lockFile) == 1) {
if (strcmp(lock.tableName, tableName) == 0 &&
lock.recordOffset == recordOffset &&
lock.transactionId == ownerId) {
found = 1;
continue; // 跳过
}
if (lockCount >= cap) {
cap *= 2;
locks = (Lock*)realloc(locks, sizeof(Lock) * cap);
}
locks[lockCount++] = lock;
}
fclose(lockFile);
if (!found) {
free(locks);
return 0;
}
lockFile = fopen(TRANS_FILE_LOCKS, "wb");
if (!lockFile) {
free(locks);
return 0;
}
for (int i = 0; i < lockCount; i++) {
fwrite(&locks[i], sizeof(Lock), 1, lockFile);
}
fclose(lockFile);
free(locks);
printf("Success: Released lock (Table: %s, Record offset: %ld, Owner ID: %d)\n",
tableName, recordOffset, ownerId);
return 1;
}
// 锁表(兼容事务与非事务:非事务走 DDL owner)
int cmd_lock_table(const char* tableName, LockType lockType) {
// 检查表是否存在
if (!dbf_check_exists(tableName)) {
printf("Error: Table %s does not exist.\n", tableName);
return 0;
}
if (CURRENT_TRANSACTION_ID != 0) {
// 原逻辑:事务内加锁
return acquire_lock(tableName, -1, lockType);
} else {
// DDL/非事务加锁:使用 DDL_LOCK_OWNER_ID
return acquire_lock_with_owner(tableName, -1, lockType, DDL_LOCK_OWNER_ID);
}
}
// 解锁表(兼容事务与非事务)
int cmd_unlock_table(const char* tableName) {
if (CURRENT_TRANSACTION_ID != 0) {
return release_lock(tableName, -1);
} else {
return release_lock_with_owner(tableName, -1, DDL_LOCK_OWNER_ID);
}
}
// ==================== 事务日志 ====================
// 记录事务操作
int log_transaction_operation(LogEntryType entryType, const char* tableName,
long recordOffset, void* oldData, void* newData, int dataSize) {
if (CURRENT_TRANSACTION_ID == 0) {
// 不在事务中,不记录日志
return 1;
}
if (!currentTransaction) {
printf("Error: Transaction data corrupted.\n");
return 0;
}
// 创建日志条目
TransactionLogEntry* entry = (TransactionLogEntry*)malloc(sizeof(TransactionLogEntry));
if (!entry) {
printf("Error: Memory allocation failed.\n");
return 0;
}
memset(entry, 0, sizeof(TransactionLogEntry));
entry->entryType = entryType;
entry->transactionId = CURRENT_TRANSACTION_ID;
strncpy(entry->tableName, tableName, TABLE_NAME_LEN - 1);
entry->tableName[TABLE_NAME_LEN - 1] = '\0';
entry->recordOffset = recordOffset;
entry->dataSize = dataSize;
// 复制旧数据
if (oldData && dataSize > 0) {
entry->oldData = malloc(dataSize);
if (!entry->oldData) {
printf("Error: Memory allocation failed.\n");
free(entry);
return 0;
}
memcpy(entry->oldData, oldData, dataSize);
} else {
entry->oldData = NULL;
}
// 复制新数据
if (newData && dataSize > 0) {
entry->newData = malloc(dataSize);
if (!entry->newData) {
printf("Error: Memory allocation failed.\n");
if (entry->oldData) free(entry->oldData);
free(entry);
return 0;
}
memcpy(entry->newData, newData, dataSize);
} else {
entry->newData = NULL;
}
// 添加到事务日志数组
int newCount = currentTransaction->logEntryCount + 1;
TransactionLogEntry** newEntries = (TransactionLogEntry**)realloc(
currentTransaction->logEntries,
sizeof(TransactionLogEntry*) * newCount
);
if (!newEntries) {
printf("Error: Memory allocation failed.\n");
if (entry->oldData) free(entry->oldData);
if (entry->newData) free(entry->newData);
free(entry);
return 0;
}
currentTransaction->logEntries = newEntries;
currentTransaction->logEntries[currentTransaction->logEntryCount] = entry;
currentTransaction->logEntryCount = newCount;
// 同时保存到文件
FILE* logFile = fopen(TRANS_FILE_LOGS, "ab");
if (logFile) {
// 写入日志条目头
fwrite(entry, sizeof(TransactionLogEntry), 1, logFile);
// 写入数据
if (entry->oldData && dataSize > 0) {
fwrite(entry->oldData, dataSize, 1, logFile);
}
if (entry->newData && dataSize > 0) {
fwrite(entry->newData, dataSize, 1, logFile);
}
fclose(logFile);
}
return 1;
}