Repository navigation
Expand file tree
/
Copy pathmanager.c
More file actions
717 lines (594 loc) · 23.5 KB
/
Copy pathmanager.c
File metadata and controls
717 lines (594 loc) · 23.5 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
// manager.c
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include "database.h"
#ifdef _WIN32
// Windows 下没有 strcasecmp 和 strncasecmp
// 需要映射到微软特有的 _stricmp 和 _strnicmp
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#endif
#ifndef CMD_ALTER
#define CMD_ALTER 14
#endif
// 你自己统一一下 alterType 的常量值(必须与 parser 输出一致)
#ifndef ALTER_ADD
#define ALTER_ADD 1
#define ALTER_DROP 2
#define ALTER_RENAME 3
#endif
// 当前用户(简化实现,实际应该从登录系统获取)
char CURRENT_USER[TABLE_NAME_LEN] = "admin";
// 辅助宏:释放 ResultSet 资源
#define FREE_RESULT_SET(rs) do { \
if (rs) { \
if (rs->records) { \
for (int k = 0; k < rs->recordCount; k++) { \
if (rs->records[k]) free(rs->records[k]); \
} \
free(rs->records); \
} \
free(rs); \
} \
} while(0)
// ==================== 新增:备份/恢复的 Manager 接口实现 ====================
// 备份:将当前数据库文件复制到指定子目录(调用 storage.c 中的实现)
// 权限校验:这里示例要求调用者对 schema 文件具有 CREATE 权限(你可以根据策略调整)
int cmd_backup_database(const char* backupDir) {
if (!backupDir || backupDir[0] == '\0') {
printf("Error: backup directory not specified.\n");
return 0;
}
// 权限示例:需要 CREATE 权限(可改为 PERM_ALL 或自定义权限)
if (!check_permission(CURRENT_USER, DB_FILE_SCHEMA, PERM_CREATE)) {
printf("Error: User %s does not have backup permission.\n", CURRENT_USER);
return 0;
}
if (backup_database(backupDir)) {
printf("Success: Backup completed to '%s'.\n", backupDir);
return 1;
}
else {
printf("Error: Backup failed.\n");
return 0;
}
}
// 恢复:从备份目录恢复到当前目录(会覆盖)
// 权限校验:恢复是破坏性操作,示例要求 DROP 权限(可调整)
int cmd_restore_database(const char* backupDir) {
if (!backupDir || backupDir[0] == '\0') {
printf("Error: restore directory not specified.\n");
return 0;
}
// 权限示例:需要 DROP 权限(恢复会覆盖数据,需严格权限)
if (!check_permission(CURRENT_USER, DB_FILE_SCHEMA, PERM_DROP)) {
printf("Error: User %s does not have restore permission.\n", CURRENT_USER);
return 0;
}
if (restore_database(backupDir)) {
printf("Success: Restore completed from '%s'.\n", backupDir);
return 1;
}
else {
printf("Error: Restore failed.\n");
return 0;
}
}
// ==================== 其余 manager.c 内容保持不变 ====================
// ==================== util ====================
static int find_col_index_ci(const TableMeta * m, const char* colName) {
if (!m || !colName || colName[0] == '\0') return -1;
for (int i = 0; i < m->iFieldCount; i++) {
// 如果你们用 bValidFlag 做软删除列,这里建议跳过无效列
if (m->fields[i].bValidFlag == 0) continue;
if (strcasecmp(m->fields[i].sFieldName, colName) == 0) return i;
}
return -1;
}
static int col_exists_ci(const TableMeta * m, const char* colName) {
return find_col_index_ci(m, colName) >= 0;
}
static int validate_new_field(const char* type, int size) {
// 你们的类型系统很简单:int/float/char
// 这里做最基础校验,避免 schema 写进垃圾
if (!type || type[0] == '\0') return 0;
if (strcasecmp(type, "int") == 0) {
return (size == 4 || size == 0); // 允许 parser 不填时为0
}
if (strcasecmp(type, "float") == 0) {
return (size == 4 || size == 0);
}
if (strcasecmp(type, "char") == 0) {
return (size > 0 && size <= MAX_KEY_LEN /*或你想限制的上限*/);
}
return 0;
}
// ==================== DDL 操作 ====================
// 创建表
int cmd_create_table(TableMeta* table) {
// 权限检查:需要CREATE权限
if (!check_permission(CURRENT_USER, table->sTableName, PERM_CREATE)) {
printf("Error: User %s does not have CREATE permission.\n", CURRENT_USER);
return 0;
}
// 使用专门的检查函数
if (dbf_check_exists(table->sTableName)) {
printf("Error: Table %s already exists.\n", table->sTableName);
return 0;
}
// 简单校验
int pkCount = 0;
for (int i = 0; i < table->iFieldCount; i++) {
TableMode* field = &table->fields[i];
if (strlen(field->sFieldName) == 0 || field->iSize <= 0) return 0;
field->bValidFlag = 1; // 默认有效
if (field->bKey) pkCount++;
}
if (pkCount == 0) {
// 强制要求有主键以便构建B+树 (简化版限制)
printf("Warning: No primary key defined, setting first field as primary key.\n");
table->fields[0].bKey = 1;
}
if (SaveTableToDBF(table)) {
printf("Success: Table %s created successfully.\n", table->sTableName);
return 1;
}
return 0;
}
// DDL: 删除表
int cmd_drop_table(const char* name) {
// 权限检查:需要DROP权限
if (!check_permission(CURRENT_USER, name, PERM_DROP)) {
printf("Error: User %s does not have DROP permission.\n", CURRENT_USER);
return 0;
}
// 1. 检查表是否存在
if (!dbf_check_exists(name)) {
printf("Error: Table %s does not exist.\n", name);
return 0;
}
// 2. 调用底层系统级删除
if (sys_drop_table(name)) {
printf("Success: Table %s has been deleted (Schema removed, Data invalidated, Index deleted).\n", name);
return 1;
}
else {
printf("Error: Failed to delete table %s.\n", name);
return 0;
}
}
// ==================== DML 操作 ====================
// 辅助:检查主键唯一性 (利用 B+ 树索引加速)
int check_primary_key_uniqueness(const char* tableName, TableMode* pkFieldDef, void* pkValuePtr) {
if (!tableName || !pkValuePtr) return 1; // 保守处理:无法判断则认为唯一
// 通过索引查找是否存在对应记录(比读取整条记录更轻量)
long off = dat_get_offset_by_key(tableName, pkValuePtr);
if (off != INVALID_OFFSET) {
return 0; // 已存在 -> 不唯一
}
return 1; // 不存在 -> 唯一
}
// 批量插入处理函数
// manager.c
int cmd_insert_batch(const char* tableName, char** targetCols, int targetColCount, char*** rows, int* rowCounts, int rowCount) {
// 权限检查:需要INSERT权限
if (!check_permission(CURRENT_USER, tableName, PERM_INSERT)) {
printf("Error: User %s does not have INSERT permission.\n", CURRENT_USER);
return 0;
}
TableMeta table;
if (!dbf_get_schema(tableName, &table)) {
printf("Error: Table %s does not exist.\n", tableName);
return 0;
}
int* colMap = NULL;
if (targetColCount > 0) {
colMap = (int*)malloc(sizeof(int) * targetColCount);
for (int k = 0; k < targetColCount; k++) {
colMap[k] = -1;
for (int i = 0; i < table.iFieldCount; i++) {
if (strcasecmp(targetCols[k], table.fields[i].sFieldName) == 0) {
colMap[k] = i;
break;
}
}
if (colMap[k] == -1) { free(colMap); return 0; }
}
}
int recordSize = 0;
for (int i = 0; i < table.iFieldCount; i++) recordSize += table.fields[i].iSize;
int successCount = 0;
for (int r = 0; r < rowCount; r++) {
char** currentVals = rows[r];
int currentValCount = rowCounts[r];
int expected = (targetColCount > 0) ? targetColCount : table.iFieldCount;
if (currentValCount != expected) {
printf("Error (Row %d): Column count mismatch.\n", r + 1);
continue;
}
char* recordData = (char*)calloc(1, recordSize); // 使用 calloc 初始化为0
int foundPK = 0;
// 填充数据
for (int k = 0; k < currentValCount; k++) {
int fieldIdx = (targetColCount > 0) ? colMap[k] : k;
TableMode* field = &table.fields[fieldIdx];
char* valStr = currentVals[k];
int offset = 0;
for (int f = 0; f < fieldIdx; f++) offset += table.fields[f].iSize;
if (strcmp(field->sType, "int") == 0) {
int v = atoi(valStr);
memcpy(recordData + offset, &v, sizeof(int));
}
else if (strcmp(field->sType, "float") == 0) {
float f = atof(valStr);
memcpy(recordData + offset, &f, sizeof(float));
}
else {
strncpy(recordData + offset, valStr, field->iSize - 1); // 预留\0
}
// 只要填充了主键列,就标记找到
if (field->bKey) foundPK = 1;
}
// 寻找主键定义和偏移量
TableMode* pkField = NULL;
int pkOffset = 0;
for (int i = 0; i < table.iFieldCount; i++) {
if (table.fields[i].bKey) {
pkField = &table.fields[i];
break;
}
pkOffset += table.fields[i].iSize;
}
// 兜底逻辑:如果未指定主键但表有主键(且是全字段插入),且上面循环没覆盖到
if (!foundPK && targetColCount == 0 && pkField) foundPK = 1;
if (foundPK && pkField) {
void* pkPtr = recordData + pkOffset;
// 1. 检查唯一性
if (!check_primary_key_uniqueness(tableName, pkField, pkPtr)) {
printf("Error (Row %d): Primary key conflict, skipping.\n", r + 1);
free(recordData);
continue;
}
// 2. 插入 (传入指针、类型、大小)
if (dat_insert_record(tableName, recordData, recordSize, pkPtr, pkField->sType, pkField->iSize)) {
successCount++;
// 3. 记录事务日志(如果当前在事务中)
if (is_in_transaction()) {
// 获取记录偏移量
long recordOffset = dat_get_offset_by_key(tableName, pkPtr);
if (recordOffset != -1) {
// 记录插入操作日志
log_transaction_operation(LOG_INSERT, tableName, recordOffset,
NULL, recordData, recordSize);
}
}
}
}
else {
printf("Error (Row %d): Primary key value not specified, skipping.\n", r + 1);
}
free(recordData);
}
if (colMap) free(colMap);
printf("Batch insert completed: Success %d / Total %d\n", successCount, rowCount);
return successCount;
}
int cmd_delete_record(const char* tableName, const char* whereCondition) {
// 权限检查:需要DELETE权限
if (!check_permission(CURRENT_USER, tableName, PERM_DELETE)) {
printf("Error: User %s does not have DELETE permission.\n", CURRENT_USER);
return -1;
}
// 1. 获取表结构
TableMeta table;
if (!dbf_get_schema(tableName, &table)) {
printf("Error: Table %s does not exist.\n", tableName);
return -1;
}
// 2. 查询目标记录
ResultSet* rs = query_select_where(tableName, whereCondition);
if (!rs || rs->recordCount == 0) {
FREE_RESULT_SET(rs);
return 0;
}
// 3. 定位主键信息的偏移量
int pkOffset = 0;
int pkIndex = -1;
int recordSize = 0; // 添加记录大小变量
for (int i = 0; i < table.iFieldCount; i++) {
if (table.fields[i].bKey) {
pkIndex = i;
}
recordSize += table.fields[i].iSize; // 计算记录大小
if (pkIndex == -1) pkOffset += table.fields[i].iSize;
}
// 校验:必须有主键才能执行物理删除
if (pkIndex == -1) {
printf("Error: Table %s does not have a primary key defined, cannot perform safe deletion.\n", tableName);
FREE_RESULT_SET(rs);
return 0;
}
int deletedCount = 0;
// 4. 遍历结果集进行删除
for (int i = 0; i < rs->recordCount; i++) {
void* recordData = rs->records[i];
// 获取指向主键数据的指针
void* pkPtr = (char*)recordData + pkOffset;
// 记录事务日志(如果当前在事务中)
if (is_in_transaction()) {
// 获取记录偏移量
long recordOffset = dat_get_offset_by_key(tableName, pkPtr);
if (recordOffset != -1) {
// 记录删除操作日志(在删除前记录旧数据)
log_transaction_operation(LOG_DELETE, tableName, recordOffset,
recordData, NULL, recordSize);
}
}
// 调用底层存储接口删除 (传入指针)
if (dat_delete_record(tableName, pkPtr)) {
deletedCount++;
}
else {
printf("Warning: Deletion failed (index inconsistency or file error).\n");
}
}
// 5. 释放资源
FREE_RESULT_SET(rs);
if (deletedCount >= 0) {
printf("Success: Deleted %d records.\n", deletedCount);
}
return deletedCount;
}
/**
* DML: 更新记录
* 流程:
* 1. 查询目标记录。
* 2. 在内存中创建一个新副本,修改指定字段的值。
* 3. 提取原主键,调用 dat_update_record 进行覆盖写入。
* 注意:本简易实现不支持修改主键本身(因为这需要 delete + insert)。
*/
int cmd_update_record(const char* tableName, char** setColumns, char** setValues, int setCount, const char* whereCondition) {
// 权限检查:需要UPDATE权限
if (!check_permission(CURRENT_USER, tableName, PERM_UPDATE)) {
printf("Error: User %s does not have UPDATE permission.\n", CURRENT_USER);
return 0;
}
// 1. 获取表结构
TableMeta table;
if (!dbf_get_schema(tableName, &table)) {
printf("Error: Table %s does not exist.\n", tableName);
return 0;
}
// 2. 查询目标记录
ResultSet* rs = query_select_where(tableName, whereCondition);
if (!rs) {
printf("Query error or no data.\n");
return 0;
}
if (rs->recordCount == 0) {
printf("No matching records, 0 rows affected.\n");
FREE_RESULT_SET(rs);
return 0;
}
// 3. 准备更新
int recordSize = 0;
int pkOffset = 0;
int pkIndex = -1;
char pkType[8] = { 0 };
// 计算记录大小并定位主键
for (int i = 0; i < table.iFieldCount; i++) {
if (table.fields[i].bKey) {
pkIndex = i;
strcpy(pkType, table.fields[i].sType);
}
if (pkIndex == -1) pkOffset += table.fields[i].iSize; // 累加主键之前的偏移量
recordSize += table.fields[i].iSize;
}
// 校验:必须有 INT 主键才能通过 dat_update_record 更新
/*if (pkIndex == -1 || strcmp(pkType, "int") != 0) {
printf("Error: Table does not have INT type primary key, UPDATE operation not supported.\n");
FREE_RESULT_SET(rs);
return 0;
}*/
int updatedCount = 0;
// 4. 遍历每一条待更新记录
for (int r = 0; r < rs->recordCount; r++) {
void* oldData = rs->records[r];
// 修改点:获取主键指针
void* pkPtr = (char*)oldData + pkOffset;
char* newData = (char*)malloc(recordSize);
memcpy(newData, oldData, recordSize);
int skipThisRow = 0;
// 应用 SET 修改
for (int k = 0; k < setCount; k++) {
char* colName = setColumns[k];
char* newValStr = setValues[k];
// 查找字段
int fieldOffset = 0;
TableMode* targetField = NULL;
for (int f = 0; f < table.iFieldCount; f++) {
if (strcasecmp(table.fields[f].sFieldName, colName) == 0) {
targetField = &table.fields[f];
break;
}
fieldOffset += table.fields[f].iSize;
}
if (!targetField) {
printf("Error: Column %s does not exist.\n", colName);
skipThisRow = 1; break;
}
// *** 禁止修改主键 ***
if (targetField->bKey) {
printf("Error: Cannot modify primary key value (Column: %s). Please use DELETE then INSERT.\n", colName);
skipThisRow = 1; break;
}
// 写入新值
if (strcmp(targetField->sType, "int") == 0) {
int v = atoi(newValStr);
memcpy(newData + fieldOffset, &v, sizeof(int));
}
else if (strcmp(targetField->sType, "float") == 0) {
float f = atof(newValStr);
memcpy(newData + fieldOffset, &f, sizeof(float));
}
else { // char
memset(newData + fieldOffset, 0, targetField->iSize); // 先清空
strncpy(newData + fieldOffset, newValStr, targetField->iSize - 1);
}
}
if (!skipThisRow) {
// 获取数据在文件中的偏移量
long dOffset = dat_get_offset_by_key(tableName, pkPtr);
// 记录事务日志(如果当前在事务中)
if (is_in_transaction() && dOffset != -1) {
// 记录更新操作日志(记录旧数据和新数据)
log_transaction_operation(LOG_UPDATE, tableName, dOffset,
oldData, newData, recordSize);
}
// 覆盖写入
if (dat_overwrite_record(dOffset, newData, recordSize)) {
updatedCount++;
}
}
free(newData);
}
FREE_RESULT_SET(rs);
printf("UPDATE successful: %d rows affected.\n", updatedCount);
return updatedCount;
}
int cmd_alter_table(SqlCommand* cmd) {
if (!cmd) return 0;
if (cmd->commandType != CMD_ALTER) {
printf("Error: Not an ALTER command.\n");
return 0;
}
const char* tableName = cmd->stmtData.alterStmt.tableName;
int alterType = cmd->stmtData.alterStmt.alterType;
if (!tableName || tableName[0] == '\0') {
printf("Error: ALTER TABLE requires a table name.\n");
return 0;
}
// 1) 事务中禁止 ALTER(推荐)
if (is_in_transaction()) {
printf("Error: ALTER TABLE is not allowed inside a transaction.\n");
return 0;
}
// 2) 取旧 schema
TableMeta oldMeta;
memset(&oldMeta, 0, sizeof(oldMeta));
if (!dbf_get_schema(tableName, &oldMeta)) {
printf("Error: Table '%s' does not exist.\n", tableName);
return 0;
}
// 3) 权限(可选:你们目前 ALTER 可能没定义权限位)
// if (!check_permission(CURRENT_USER, tableName, PERM_ALTER)) { ... }
// 4) 拿表级排他锁
if (!cmd_lock_table(tableName, LOCK_EXCLUS)) {
printf("Error: Failed to acquire exclusive lock on table %s\n", tableName);
return 0;
}
int ok = 0;
// 5) 构造 newMeta(先拷贝,再改)
TableMeta newMeta;
memcpy(&newMeta, &oldMeta, sizeof(TableMeta));
if (alterType == ALTER_RENAME) {
const char* oldCol = cmd->stmtData.alterStmt.columnName;
const char* newCol = cmd->stmtData.alterStmt.newColumnName;
if (!oldCol || !newCol || oldCol[0] == '\0' || newCol[0] == '\0') {
printf("Error: RENAME COLUMN requires old and new column names.\n");
goto cleanup;
}
int idx = find_col_index_ci(&newMeta, oldCol);
if (idx < 0) {
printf("Error: Column '%s' not found in table %s\n", oldCol, tableName);
goto cleanup;
}
// 新名字不能撞已存在列(允许大小写变化等价重命名:old==new)
if (col_exists_ci(&newMeta, newCol) && strcasecmp(oldCol, newCol) != 0) {
printf("Error: Column name '%s' already exists in table %s\n", newCol, tableName);
goto cleanup;
}
strncpy(newMeta.fields[idx].sFieldName, newCol, FIELD_NAME_LEN - 1);
newMeta.fields[idx].sFieldName[FIELD_NAME_LEN - 1] = '\0';
// 6) 交给 storage 落盘
if (!storage_apply_alter(tableName, &oldMeta, &newMeta, alterType)) {
printf("Error: Failed to apply ALTER RENAME on table %s\n", tableName);
goto cleanup;
}
printf("Success: Column '%s' renamed to '%s' in table %s\n", oldCol, newCol, tableName);
ok = 1;
}
else if (alterType == ALTER_DROP) {
const char* col = cmd->stmtData.alterStmt.columnName;
if (!col || col[0] == '\0') {
printf("Error: DROP COLUMN requires a column name.\n");
goto cleanup;
}
int idx = find_col_index_ci(&newMeta, col);
if (idx < 0) {
printf("Error: Column '%s' not found in table %s\n", col, tableName);
goto cleanup;
}
// 简单策略:不允许 drop 主键
if (newMeta.fields[idx].bKey) {
printf("Error: Cannot drop primary key column '%s'.\n", col);
goto cleanup;
}
newMeta.fields[idx].bValidFlag = 0; // 软删除
if (!storage_apply_alter(tableName, &oldMeta, &newMeta, alterType)) {
printf("Error: Failed to apply ALTER DROP on table %s\n", tableName);
goto cleanup;
}
printf("Success: Column '%s' logically dropped from table %s\n", col, tableName);
ok = 1;
}
else if (alterType == ALTER_ADD) {
const char* col = cmd->stmtData.alterStmt.columnName;
const char* type = cmd->stmtData.alterStmt.newType;
int size = cmd->stmtData.alterStmt.newSize;
char nullflag = cmd->stmtData.alterStmt.newNullFlag; // 语义:1=allow null?
if (!col || col[0] == '\0' || !type || type[0] == '\0') {
printf("Error: ADD COLUMN requires name and type.\n");
goto cleanup;
}
if (col_exists_ci(&newMeta, col)) {
printf("Error: Column '%s' already exists in table %s\n", col, tableName);
goto cleanup;
}
if (newMeta.iFieldCount >= MAX_FIELDS) {
printf("Error: Too many fields in table %s\n", tableName);
goto cleanup;
}
// 类型/长度校验
if (!validate_new_field(type, size)) {
printf("Error: Invalid column type/size (%s, %d)\n", type, size);
goto cleanup;
}
// 填充新字段(Phase 1:只改 schema,不迁移 dat)
TableMode* nf = &newMeta.fields[newMeta.iFieldCount];
memset(nf, 0, sizeof(TableMode));
strncpy(nf->sFieldName, col, FIELD_NAME_LEN - 1);
nf->sFieldName[FIELD_NAME_LEN - 1] = '\0';
strncpy(nf->sType, type, sizeof(nf->sType) - 1);
nf->sType[sizeof(nf->sType) - 1] = '\0';
nf->iSize = (size == 0 ? (strcasecmp(type, "char") == 0 ? 1 : 4) : size);
nf->bKey = 0;
nf->bNullFlag = (nullflag ? 1 : 0);
nf->bValidFlag = 1;
newMeta.iFieldCount++;
if (!storage_apply_alter(tableName, &oldMeta, &newMeta, alterType)) {
printf("Error: Failed to apply ALTER ADD on table %s\n", tableName);
goto cleanup;
}
printf("Success: Column '%s' added to table %s\n", col, tableName);
ok = 1;
}
else {
printf("Error: Unsupported ALTER type.\n");
}
cleanup:
// 释放锁(你如果没有 cmd_unlock_table,就封装一个调用 release_lock(tableName, -1))
cmd_unlock_table(tableName);
return ok;
}