Repository navigation
Expand file tree
/
Copy pathquery.c
More file actions
817 lines (706 loc) · 28.5 KB
/
Copy pathquery.c
File metadata and controls
817 lines (706 loc) · 28.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
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
// query.c
#include "database.h"
#include <ctype.h>
#include <math.h>
#ifdef _WIN32
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#endif
// 模块级全局:当 evaluate 过程中遇到语义错误(如引用不存在列)时置为1
static int g_eval_error = 0;
// ==================== 字符串辅助工具 ====================
// 去除首尾空格
static char* trim_ref(char* s) {
if (!s) return NULL;
while (*s && isspace((unsigned char)*s)) s++;
if (*s == 0) return s;
char* end = s + strlen(s) - 1;
while (end > s && isspace((unsigned char)*end)) *end-- = '\0';
return s;
}
// 去除字符串的单引号 'Alice' -> Alice
static void strip_quotes(char* val) {
char* s = trim_ref(val);
int len = strlen(s);
if (len >= 2 && (s[0] == '\'' || s[0] == '\"') && s[len - 1] == s[0]) {
s[len - 1] = '\0';
memmove(val, s + 1, len - 1); // 向前移动覆盖
}
}
// 不区分大小写的包含查找 (stristr)
static char* stristr_local(const char* haystack, const char* needle) {
if (!haystack || !needle) return NULL;
if (!*needle) return (char*)haystack;
for (; *haystack; ++haystack) {
if (toupper((unsigned char)*haystack) == toupper((unsigned char)*needle)) {
const char* h = haystack;
const char* n = needle;
while (*h && *n && toupper((unsigned char)*h) == toupper((unsigned char)*n)) {
h++; n++;
}
if (!*n) return (char*)haystack;
}
}
return NULL;
}
// ==================== 辅助:Schema 查找(最小改动) ====================
// 在 schema 中查找列索引(不考虑字段是否在某条记录上有数据)
// 返回列索引(>=0)或 -1(不存在)
static int find_field_index(TableMeta* table, const char* colName) {
if (!table || !colName || !*colName) return -1;
for (int i = 0; i < table->iFieldCount; i++) {
char* fName = table->fields[i].sFieldName;
if (strcasecmp(fName, colName) == 0) return i;
// 支持短名匹配:表名.col -> col
if (!strchr(colName, '.')) {
char* dot = strchr(fName, '.');
if (dot && strcasecmp(dot + 1, colName) == 0) return i;
}
}
return -1;
}
// ==================== 核心评估逻辑 ====================
// 获取某列在记录中的指针和类型信息
// 返回 1 找到并且字段在该记录中可读,0 未找到或该记录没有该列
static int get_col_data(void* recordData, int recordSize, TableMeta* table, const char* colName,
void** outPtr, char* outType, int* outSize) {
int offset = 0;
for (int i = 0; i < table->iFieldCount; i++) {
TableMode* f = &table->fields[i];
// 跳过被 DROP 标记的列
if (f->bValidFlag == 0) {
// 仍然累加 offset(因为在旧记录中该列可能占位),
// 但若表设计 ADD COLUMN 时旧记录 shorter,offset 语义需慎重。
offset += f->iSize;
continue;
}
// 1. 尝试完全匹配 (例如 "aab.id" == "aab.id")
int match = (strcasecmp(f->sFieldName, colName) == 0);
// 2. 尝试短名匹配 (例如 "aab.id" 匹配 "id")
//前提:用户输入的 colName 不包含点,且表中字段包含点
if (!match && !strchr(colName, '.')) {
char* dot = strchr(f->sFieldName, '.');
if (dot) {
// 比较点号后面的部分
if (strcasecmp(dot + 1, colName) == 0) {
match = 1;
}
}
}
if (match) {
// 边界检查:确保该记录包含完整字段数据
if (offset + f->iSize > recordSize) {
// 该条记录并没有该列的数据(旧记录短),视为不存在/NULL
return 0;
}
*outPtr = (char*)recordData + offset;
strcpy(outType, f->sType);
*outSize = f->iSize;
return 1; // 找到并可访问
}
offset += f->iSize;
}
return 0;
}
// 简单的通配符匹配 (仅支持 %在前、%在后、%在两端)
// pattern: "A%", "%A", "%A%", "A"
static int check_like_pattern(const char* value, const char* pattern) {
int pLen = strlen(pattern);
if (pLen == 0) return 0;
int startsWithWild = (pattern[0] == '%');
int endsWithWild = (pattern[pLen - 1] == '%');
char cleanPattern[256];
strcpy(cleanPattern, pattern);
if (endsWithWild) cleanPattern[strlen(cleanPattern) - 1] = '\0';
if (startsWithWild) memmove(cleanPattern, cleanPattern + 1, strlen(cleanPattern));
// %abc% -> 包含
if (startsWithWild && endsWithWild) {
return stristr_local(value, cleanPattern) != NULL;
}
// %abc -> 结尾是
else if (startsWithWild) {
int vLen = strlen(value);
int cLen = strlen(cleanPattern);
if (vLen < cLen) return 0;
return strcasecmp(value + vLen - cLen, cleanPattern) == 0;
}
// abc% -> 开头是
else if (endsWithWild) {
return strncasecmp(value, cleanPattern, strlen(cleanPattern)) == 0;
}
// abc -> 完全匹配
else {
return strcasecmp(value, cleanPattern) == 0;
}
}
/**
* 解析单个原子条件
* 支持: col > val (立即数)
* 支持: col1 = col2 (列连接)
* 支持: LIKE, BETWEEN
*
* 说明:在访问列前先检查 schema(find_field_index),若列不存在或已被 drop,
* 会打印错误并设置 g_eval_error=1。这样上层可以检测到语义错误并中止查询。
*/
static int eval_simple_expr(void* recordData, int recordSize, TableMeta* table, char* expr) {
char* e = trim_ref(expr);
if (!e || strlen(e) == 0) return 1;
// --- A. 处理 BETWEEN ... AND ... ---
char* betweenPtr = stristr_local(e, " BETWEEN ");
if (betweenPtr) {
*betweenPtr = '\0';
char* colName = trim_ref(e);
char* rest = betweenPtr + 9;
char* andPtr = stristr_local(rest, " AND ");
if (!andPtr) return 0;
*andPtr = '\0';
char* val1Str = trim_ref(rest);
char* val2Str = trim_ref(andPtr + 5);
// schema 检查:列存在且有效吗?
int idx = find_field_index(table, colName);
if (idx < 0) {
printf("Error: column '%s' not found.\n", colName);
g_eval_error = 1;
return 0;
}
if (table->fields[idx].bValidFlag == 0) {
printf("Error: column '%s' is dropped/invalid.\n", colName);
g_eval_error = 1;
return 0;
}
void* dataPtr; char type[10]; int size;
if (!get_col_data(recordData, recordSize, table, colName, &dataPtr, type, &size)) return 0;
if (strcmp(type, "int") == 0) {
int val = *(int*)dataPtr;
return (val >= atoi(val1Str) && val <= atoi(val2Str));
}
else if (strcmp(type, "float") == 0) {
float val = *(float*)dataPtr;
return (val >= atof(val1Str) && val <= atof(val2Str));
}
return 0;
}
// --- B. 处理 LIKE ---
char* likePtr = stristr_local(e, " LIKE ");
if (likePtr) {
*likePtr = '\0';
char* colName = trim_ref(e);
char* pattern = trim_ref(likePtr + 6);
strip_quotes(pattern);
int idx = find_field_index(table, colName);
if (idx < 0) {
printf("Error: column '%s' not found.\n", colName);
g_eval_error = 1;
return 0;
}
if (table->fields[idx].bValidFlag == 0) {
printf("Error: column '%s' is dropped/invalid.\n", colName);
g_eval_error = 1;
return 0;
}
void* dataPtr; char type[10]; int size;
if (!get_col_data(recordData, recordSize, table, colName, &dataPtr, type, &size)) return 0;
if (strncmp(type, "char", 4) == 0) {
return check_like_pattern((char*)dataPtr, pattern);
}
return 0;
}
// --- C. 处理常规比较符 (>=, <=, !=, <>, >, <, =) ---
char* op = NULL;
int opType = 0; // 1:>=, 2:<=, 3:!=, 4:>, 5:<, 6:=
if ((op = strstr(e, ">="))) opType = 1;
else if ((op = strstr(e, "<="))) opType = 2;
else if ((op = strstr(e, "!=")) || (op = strstr(e, "<>"))) opType = 3;
else if ((op = strstr(e, ">"))) opType = 4;
else if ((op = strstr(e, "<"))) opType = 5;
else if ((op = strstr(e, "="))) opType = 6;
if (opType != 0) {
*op = '\0'; // 将操作符位置截断
char* colName = trim_ref(e);
char* rightStr = trim_ref(op + (opType <= 3 ? 2 : 1)); // 跳过操作符
// schema 检查:左列
int lhsIdx = find_field_index(table, colName);
if (lhsIdx < 0) {
printf("Error: column '%s' not found.\n", colName);
g_eval_error = 1;
return 0;
}
if (table->fields[lhsIdx].bValidFlag == 0) {
printf("Error: column '%s' is dropped/invalid.\n", colName);
g_eval_error = 1;
return 0;
}
void* lhsPtr; char lhsType[10]; int lhsSize;
if (!get_col_data(recordData, recordSize, table, colName, &lhsPtr, lhsType, &lhsSize)) {
return 0; // 左值在该记录上不存在(旧记录短),视为 NULL -> 比较为假
}
// --- 关键增强:判断右值是“立即数”还是“列名” ---
int isRightCol = 0;
void* rhsPtr = NULL;
char rhsType[10] = { 0 };
int rhsSize = 0;
char literalBuf[256]; // 用于存储去除引号后的立即数
if (rightStr[0] != '\'' && rightStr[0] != '\"' && !isdigit((unsigned char)rightStr[0]) && rightStr[0] != '-') {
// 右侧被解析为列名:先查 schema
int rIdx = find_field_index(table, rightStr);
if (rIdx < 0) {
printf("Error: column '%s' not found.\n", rightStr);
g_eval_error = 1;
return 0;
}
if (table->fields[rIdx].bValidFlag == 0) {
printf("Error: column '%s' is dropped/invalid.\n", rightStr);
g_eval_error = 1;
return 0;
}
// 右列在这条记录上可能不存在(旧记录短),此时视为 NULL -> 比较为假
if (!get_col_data(recordData, recordSize, table, rightStr, &rhsPtr, rhsType, &rhsSize)) {
return 0;
}
isRightCol = 1;
}
else {
strcpy(literalBuf, rightStr);
strip_quotes(literalBuf);
}
// --- 执行比较 ---
if (strcmp(lhsType, "int") == 0) {
int lVal = *(int*)lhsPtr;
int rVal = 0;
if (isRightCol) {
if (strcmp(rhsType, "int") == 0) rVal = *(int*)rhsPtr;
else if (strcmp(rhsType, "float") == 0) rVal = (int)(*(float*)rhsPtr);
else rVal = 0; // 不支持 char 转 int
}
else {
rVal = atoi(literalBuf);
}
switch (opType) {
case 1: return lVal >= rVal;
case 2: return lVal <= rVal;
case 3: return lVal != rVal;
case 4: return lVal > rVal;
case 5: return lVal < rVal;
case 6: return lVal == rVal;
}
}
// 2. FLOAT 类型比较
else if (strcmp(lhsType, "float") == 0) {
float lVal = *(float*)lhsPtr;
float rVal = 0.0f;
if (isRightCol) {
if (strcmp(rhsType, "float") == 0) rVal = *(float*)rhsPtr;
else if (strcmp(rhsType, "int") == 0) rVal = (float)(*(int*)rhsPtr);
}
else {
rVal = atof(literalBuf);
}
float diff = lVal - rVal;
switch (opType) {
case 1: return lVal >= rVal;
case 2: return lVal <= rVal;
case 3: return fabs(diff) > 0.000001;
case 4: return lVal > rVal;
case 5: return lVal < rVal;
case 6: return fabs(diff) < 0.000001;
}
}
// 3. CHAR 类型比较
else if (strncmp(lhsType, "char", 4) == 0) {
char* lVal = (char*)lhsPtr;
char* rVal = isRightCol ? (char*)rhsPtr : literalBuf;
// 如果右边不是 char,无法比较
if (isRightCol && strncmp(rhsType, "char", 4) != 0) return 0;
int cmp = strcmp(lVal, rVal); // 区分大小写
switch (opType) {
case 1: return cmp >= 0;
case 2: return cmp <= 0;
case 3: return cmp != 0;
case 4: return cmp > 0;
case 5: return cmp < 0;
case 6: return cmp == 0;
}
}
}
return 0;
}
// 对外接口:评估复杂条件 (支持 AND)
// 增加 recordSize 参数
int evaluate_condition(void* recordData, TableMeta* table, const char* condition, int recordSize) {
if (!condition || strlen(condition) == 0) return 1;
// 每次评估前清零模块错误标志(由调用方在开始过滤前也会清零以保险)
// 但这里也清零以确保单独调用正确
g_eval_error = 0;
// 复制一份条件字符串用于分割 (strtok会破坏原串)
char* condCopy = strdup(condition);
char* cursor = condCopy;
int result = 1; // 默认为真,AND 逻辑遇到假则变假
char* ptr = condCopy;
char* end = ptr + strlen(ptr);
char* logicAndPos = NULL;
// 迭代寻找 " AND "
char* searchStart = condCopy;
while ((logicAndPos = stristr_local(searchStart, " AND ")) != NULL) {
// 检查这个 AND 是否属于 BETWEEN
// 简单判断:从当前子句开始到这个 AND 之间,是否有 BETWEEN
char temp = *logicAndPos;
*logicAndPos = '\0'; // 暂时截断
char* hasBetween = stristr_local(searchStart, " BETWEEN ");
*logicAndPos = temp; // 恢复
if (hasBetween) {
searchStart = logicAndPos + 5; // 跳过这个 AND 继续找下一个
continue; // 这是一个非常粗糙的假设,假设 BETWEEN 的 AND 不会被当作分割符
// 实际上这很难通过简单 split 实现。
}
else {
// 找到了真正的逻辑 AND
*logicAndPos = '\0'; // 截断第一部分
// 评估左边
if (!eval_simple_expr(recordData, recordSize, table, ptr)) {
if (g_eval_error) { result = 0; break; } // 遇到语义错误也跳出,上层会检测 g_eval_error
result = 0; break;
}
// 指针移到右边继续
ptr = logicAndPos + 5;
searchStart = ptr;
}
}
// 评估最后剩余的部分 (或者如果没找到 AND,就是整个字符串)
if (result) {
if (!eval_simple_expr(recordData, recordSize, table, ptr)) {
if (g_eval_error) { result = 0; } // 语义错误,置0(上层通过 g_eval_error 检查)
else result = 0;
}
}
free(condCopy);
return result;
}
// ==================== 查询入口 ====================
// 辅助:解析简单的 PK 等值查询用于索引加速
static int parse_simple_pk_condition(TableMeta* table, const char* condition, void* outKeyBuf) {
if (!condition) return 0;
if (strstr(condition, " AND ") || strstr(condition, " OR ") ||
strstr(condition, " LIKE ") || strchr(condition, '>')) {
return 0;
}
TableMode* pkField = NULL;
for (int i = 0; i < table->iFieldCount; i++) {
if (table->fields[i].bKey) {
pkField = &table->fields[i];
break;
}
}
if (!pkField) return 0;
char col[64], val[64];
char* eq = strchr(condition, '=');
if (!eq) return 0;
int idx = (int)(eq - condition);
if (idx >= 63) return 0;
strncpy(col, condition, idx); col[idx] = 0;
strcpy(val, eq + 1);
char* trimCol = trim_ref(col);
int match = (strcasecmp(trimCol, pkField->sFieldName) == 0);
if (!match && !strchr(trimCol, '.')) {
char* dot = strchr(pkField->sFieldName, '.');
if (dot && strcasecmp(dot + 1, trimCol) == 0) match = 1;
}
if (match) {
char* v = trim_ref(val);
strip_quotes(v);
// 根据类型写入 buffer
if (strcmp(pkField->sType, "int") == 0) {
int iv = atoi(v);
memcpy(outKeyBuf, &iv, 4);
}
else if (strcmp(pkField->sType, "float") == 0) {
float fv = atof(v);
memcpy(outKeyBuf, &fv, 4);
}
else {
// char
memset(outKeyBuf, 0, MAX_KEY_LEN); // clean buffer
strncpy((char*)outKeyBuf, v, pkField->iSize - 1);
}
return 1;
}
return 0;
}
ResultSet* query_select_where(const char* tableName, const char* whereCondition) {
// 权限检查:需要SELECT权限
if (!check_permission(CURRENT_USER, tableName, PERM_SELECT)) {
printf("Error: User %s does not have SELECT permission.\n", CURRENT_USER);
return NULL;
}
TableMeta table;
if (!dbf_get_schema(tableName, &table)) return NULL;
ResultSet* rs = (ResultSet*)malloc(sizeof(ResultSet));
rs->meta = table;
rs->records = (void**)malloc(sizeof(void*) * MAX_RECORDS);
rs->recordSizes = (int*)malloc(sizeof(int) * MAX_RECORDS);
rs->recordCount = 0;
int recordSize = 0;
for (int i = 0; i < table.iFieldCount; i++) recordSize += table.fields[i].iSize;
// 修复:使用 Key Buffer
unsigned char keyBuf[MAX_KEY_LEN] = { 0 };
// 1. 尝试使用 B+ 树索引
if (whereCondition && parse_simple_pk_condition(&table, whereCondition, keyBuf)) {
void* buffer = malloc(recordSize);
int storedSize = 0;
// 传递 keyBuf 地址,而不是 int 值
if (dat_search_record(tableName, keyBuf, buffer, recordSize, &storedSize)) {
rs->records[0] = buffer;
rs->recordSizes[0] = storedSize > 0 ? storedSize : recordSize;
rs->recordCount = 1;
}
else {
free(buffer);
rs->recordCount = 0;
}
}
// 2. 全表扫描
else {
dat_scan_all(&table, rs);
if (whereCondition) {
// 在过滤前清零语义错误标志
g_eval_error = 0;
int w = 0;
for (int i = 0; i < rs->recordCount; i++) {
int ok = evaluate_condition(rs->records[i], &table, whereCondition, rs->recordSizes[i]);
if (g_eval_error) {
// 语义错误(例如引用不存在列),清理并返回错误
for (int k = 0; k < rs->recordCount; k++) if (rs->records[k]) free(rs->records[k]);
free(rs->records);
free(rs->recordSizes);
free(rs);
return NULL;
}
if (ok) {
rs->records[w] = rs->records[i];
rs->recordSizes[w] = rs->recordSizes[i];
w++;
}
else {
free(rs->records[i]);
}
}
rs->recordCount = w;
}
}
return rs;
}
ResultSet* query_project_columns(ResultSet* inputRs, char** selectColumns, int columnCount) {
if (!inputRs || !selectColumns || columnCount == 0) return inputRs;
TableMeta* oldMeta = &inputRs->meta;
TableMeta newMeta;
memset(&newMeta, 0, sizeof(TableMeta));
strcpy(newMeta.sTableName, oldMeta->sTableName);
newMeta.iFieldCount = 0;
int fieldIndices[MAX_FIELDS];
int newRecordSize = 0;
for (int i = 0; i < columnCount; i++) {
char* colName = selectColumns[i];
int found = 0;
for (int k = 0; k < oldMeta->iFieldCount; k++) {
char* fName = oldMeta->fields[k].sFieldName;
int match = (strcasecmp(fName, colName) == 0); // 完全匹配
if (!match && !strchr(colName, '.')) {
char* dot = strchr(fName, '.');
if (dot && strcasecmp(dot + 1, colName) == 0) {
match = 1;
}
}
if (match) {
// 跳过已经被 DROP 的列
if (oldMeta->fields[k].bValidFlag == 0) {
// 忽略,不加入投影
found = 1; // 标记为已找到但忽略
break;
}
newMeta.fields[newMeta.iFieldCount] = oldMeta->fields[k];
fieldIndices[newMeta.iFieldCount] = k;
newRecordSize += oldMeta->fields[k].iSize;
newMeta.iFieldCount++;
found = 1;
break;
}
}
if (!found) printf("Error: Column '%s' does not exist.\n", colName);
}
if (newMeta.iFieldCount == 0) return inputRs;
ResultSet* newRs = (ResultSet*)malloc(sizeof(ResultSet));
newRs->meta = newMeta;
newRs->recordCount = inputRs->recordCount;
newRs->records = (void**)malloc(sizeof(void*) * MAX_RECORDS);
newRs->recordSizes = (int*)malloc(sizeof(int) * MAX_RECORDS);
for (int r = 0; r < inputRs->recordCount; r++) {
char* oldData = (char*)inputRs->records[r];
int oldSize = inputRs->recordSizes[r];
char* newData = (char*)malloc(newRecordSize);
int currentWriteOffset = 0;
for (int f = 0; f < newMeta.iFieldCount; f++) {
int oldFieldIndex = fieldIndices[f];
int oldOffset = 0;
for (int k = 0; k < oldFieldIndex; k++) oldOffset += oldMeta->fields[k].iSize;
int size = oldMeta->fields[oldFieldIndex].iSize;
// 边界容错:若旧记录没有该字段的数据,则填0
if (oldOffset + size <= oldSize) {
memcpy(newData + currentWriteOffset, oldData + oldOffset, size);
}
else {
memset(newData + currentWriteOffset, 0, size);
}
currentWriteOffset += size;
}
newRs->records[r] = newData;
newRs->recordSizes[r] = newRecordSize;
free(oldData);
}
free(inputRs->records);
free(inputRs->recordSizes);
free(inputRs);
return newRs;
}
// ==================== 4. 多表连接逻辑 ====================
// 新增辅助函数:将结果集的所有字段重命名为 "Alias.Column"
static void apply_table_alias(ResultSet* rs, const char* alias) {
if (!rs || !alias) return;
// 更新表名元数据为别名
strncpy(rs->meta.sTableName, alias, TABLE_NAME_LEN - 1);
// 更新所有字段名
for (int i = 0; i < rs->meta.iFieldCount; i++) {
char oldName[FIELD_NAME_LEN];
strcpy(oldName, rs->meta.fields[i].sFieldName);
char newName[64];
// 格式化为 "Alias.Col"
sprintf(newName, "%s.%s", alias, oldName);
// 截断写入
strncpy(rs->meta.fields[i].sFieldName, newName, FIELD_NAME_LEN - 1);
rs->meta.fields[i].sFieldName[FIELD_NAME_LEN - 1] = '\0';
}
}
// 修改后的笛卡尔积:不再自动重命名,而是直接合并字段
// 因为字段已经在外部被 apply_table_alias 处理过了
static ResultSet* do_cartesian_product(ResultSet* rs1, ResultSet* rs2) {
if (!rs1 || !rs2) return NULL;
ResultSet* newRs = (ResultSet*)malloc(sizeof(ResultSet));
// 1. 合并元数据
strcpy(newRs->meta.sTableName, "JoinTable");
newRs->meta.iFieldCount = rs1->meta.iFieldCount + rs2->meta.iFieldCount;
if (newRs->meta.iFieldCount > MAX_FIELDS) {
printf("Error: Field count after JOIN exceeds system limit (%d).\n", MAX_FIELDS);
newRs->meta.iFieldCount = MAX_FIELDS;
}
// 直接复制字段定义 (此时字段名已经是 "Alias.Col" 格式)
int offset = 0;
for (int i = 0; i < rs1->meta.iFieldCount && offset < MAX_FIELDS; i++) {
newRs->meta.fields[offset++] = rs1->meta.fields[i];
}
for (int i = 0; i < rs2->meta.iFieldCount && offset < MAX_FIELDS; i++) {
newRs->meta.fields[offset++] = rs2->meta.fields[i];
}
// 修正实际数量
newRs->meta.iFieldCount = offset;
// 计算大小
int size1 = 0;
for (int i = 0; i < rs1->meta.iFieldCount; i++) size1 += rs1->meta.fields[i].iSize;
int size2 = 0;
for (int i = 0; i < rs2->meta.iFieldCount; i++) size2 += rs2->meta.fields[i].iSize;
int newSize = size1 + size2;
// 2. 生成数据
long long estimatedRows = (long long)rs1->recordCount * rs2->recordCount;
if (estimatedRows > MAX_RECORDS) {
printf("Warning: JOIN result set too large (%lld), truncating to %d.\n", estimatedRows, MAX_RECORDS);
newRs->recordCount = MAX_RECORDS;
}
else {
newRs->recordCount = (int)estimatedRows;
}
newRs->records = (void**)malloc(sizeof(void*) * MAX_RECORDS);
newRs->recordSizes = (int*)malloc(sizeof(int) * MAX_RECORDS);
int writeIdx = 0;
for (int i = 0; i < rs1->recordCount; i++) {
for (int j = 0; j < rs2->recordCount; j++) {
if (writeIdx >= newRs->recordCount) break;
char* newData = (char*)malloc(newSize);
if (rs1->records[i]) memcpy(newData, rs1->records[i], size1);
else memset(newData, 0, size1);
if (rs2->records[j]) memcpy(newData + size1, rs2->records[j], size2);
else memset(newData + size1, 0, size2);
newRs->records[writeIdx] = newData;
newRs->recordSizes[writeIdx] = newSize;
writeIdx++;
}
}
newRs->recordCount = writeIdx;
// 释放原结果集
for (int i = 0; i < rs1->recordCount; i++) if (rs1->records[i]) free(rs1->records[i]);
free(rs1->records); free(rs1->recordSizes); free(rs1);
for (int i = 0; i < rs2->recordCount; i++) if (rs2->records[i]) free(rs2->records[i]);
free(rs2->records); free(rs2->recordSizes); free(rs2);
return newRs;
}
// 多表查询入口 (已在上面实现 WHERE 过滤时检查 g_eval_error)
ResultSet* query_multitable(char tableNames[MAX_TABLES_IN_JOIN][TABLE_NAME_LEN],
char aliases[MAX_TABLES_IN_JOIN][TABLE_NAME_LEN], // 新增参数
int tableCount,
const char* whereCondition)
{
if (tableCount == 0) return NULL;
// 权限检查:对每个表都需要SELECT权限
for (int i = 0; i < tableCount; i++) {
if (!check_permission(CURRENT_USER, tableNames[i], PERM_SELECT)) {
printf("Error: User %s does not have SELECT permission on table %s.\n", CURRENT_USER, tableNames[i]);
return NULL;
}
}
// 1. 加载第一张表
ResultSet* finalRs = (ResultSet*)malloc(sizeof(ResultSet));
finalRs->records = NULL; finalRs->recordSizes = NULL; // 安全初始化
if (!dbf_get_schema(tableNames[0], &finalRs->meta)) {
printf("Error: Table %s does not exist.\n", tableNames[0]);
if (finalRs->records) free(finalRs->records); free(finalRs);
return NULL;
}
dat_scan_all(&finalRs->meta, finalRs);
// 应用别名
apply_table_alias(finalRs, aliases[0]);
// 2. 依次 Join 后续表
for (int i = 1; i < tableCount; i++) {
ResultSet* nextRs = (ResultSet*)malloc(sizeof(ResultSet));
nextRs->records = NULL; nextRs->recordSizes = NULL; // 安全初始化
if (!dbf_get_schema(tableNames[i], &nextRs->meta)) {
printf("Error: Table %s does not exist.\n", tableNames[i]);
// 清理
for (int k = 0; k < finalRs->recordCount; k++) free(finalRs->records[k]);
free(finalRs->records); free(finalRs->recordSizes); free(finalRs);
if (nextRs->records) free(nextRs->records); if (nextRs->recordSizes) free(nextRs->recordSizes); free(nextRs);
return NULL;
}
dat_scan_all(&nextRs->meta, nextRs);
apply_table_alias(nextRs, aliases[i]);
finalRs = do_cartesian_product(finalRs, nextRs);
}
// 3. 执行 WHERE 过滤(过滤前清零语义错误标志)
if (whereCondition) {
g_eval_error = 0;
int writeIdx = 0;
for (int i = 0; i < finalRs->recordCount; i++) {
int ok = evaluate_condition(finalRs->records[i], &finalRs->meta, whereCondition, finalRs->recordSizes[i]);
if (g_eval_error) {
for (int k = 0; k < finalRs->recordCount; k++) if (finalRs->records[k]) free(finalRs->records[k]);
free(finalRs->records); free(finalRs->recordSizes); free(finalRs);
return NULL;
}
if (ok) {
finalRs->records[writeIdx] = finalRs->records[i];
finalRs->recordSizes[writeIdx] = finalRs->recordSizes[i];
writeIdx++;
}
else {
free(finalRs->records[i]);
}
}
finalRs->recordCount = writeIdx;
}
return finalRs;
}