-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_executor.cpp
More file actions
1862 lines (1631 loc) · 75.3 KB
/
query_executor.cpp
File metadata and controls
1862 lines (1631 loc) · 75.3 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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file query_executor.cpp
* @brief High-level query executor implementation
*/
#include "executor/query_executor.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "catalog/catalog.hpp"
#include "common/cluster_manager.hpp"
#include "common/hll.hpp"
#include "common/value.hpp"
#include "distributed/raft_group.hpp"
#include "distributed/raft_manager.hpp"
#include "distributed/shard_manager.hpp"
#include "executor/operator.hpp"
#include "executor/types.hpp"
#include "executor/vectorized_operator.hpp"
#include "network/rpc_message.hpp"
#include "optimizer/row_estimator.hpp"
#include "parser/expression.hpp"
#include "parser/lexer.hpp"
#include "parser/parser.hpp"
#include "parser/statement.hpp"
#include "parser/token.hpp"
#include "recovery/log_manager.hpp"
#include "recovery/log_record.hpp"
#include "storage/btree_index.hpp"
#include "storage/buffer_pool_manager.hpp"
#include "storage/heap_table.hpp"
#include "transaction/lock_manager.hpp"
#include "transaction/transaction.hpp"
#include "transaction/transaction_manager.hpp"
namespace cloudsql::executor {
// Threshold for cost-based Volcano/Vectorized chooser.
// Heuristic: Vectorized operators outperform Volcano-style tuple-at-a-time
// above ~10k rows for analytical scan workloads. Tunable per workload.
static constexpr uint64_t kVectorizedRowThreshold = 10000;
// Define static members for statement cache
std::unordered_map<std::string, std::shared_ptr<parser::Statement>> QueryExecutor::statement_cache_;
std::mutex QueryExecutor::cache_mutex_;
namespace {
enum class IndexOp { Insert, Remove };
/**
* @brief Helper to perform index writes and check for success
*/
bool apply_index_write(storage::BTreeIndex& index, const common::Value& key,
const storage::HeapTable::TupleId& rid, IndexOp op, std::string& error_msg) {
bool success = false;
if (op == IndexOp::Insert) {
success = index.insert(key, rid);
} else {
success = index.remove(key, rid);
}
if (!success) {
error_msg = "Index operation failed for key: " + key.to_string();
return false;
}
return true;
}
} // namespace
void ShardStateMachine::apply(const raft::LogEntry& entry) {
if (entry.data.empty()) return;
// Binary format for Shard DML:
// [Type:1] (1:Insert, 2:Delete, 3:Update)
// [TableLen:4][TableName]
// [Payload...]
uint8_t type = entry.data[0];
size_t offset = 1;
uint32_t table_len = 0;
if (offset + 4 > entry.data.size()) return;
std::memcpy(&table_len, entry.data.data() + offset, 4);
offset += 4;
if (offset + table_len > entry.data.size()) return;
std::string table_name(reinterpret_cast<const char*>(entry.data.data() + offset), table_len);
offset += table_len;
auto table_meta_opt = catalog_.get_table_by_name(table_name);
if (!table_meta_opt.has_value()) return;
const auto* table_meta = table_meta_opt.value();
Schema schema;
for (const auto& col : table_meta->columns) {
schema.add_column(col.name, col.type);
}
storage::HeapTable table(table_name, bpm_, schema);
if (type == 1) { // INSERT
Tuple tuple =
network::Serializer::deserialize_tuple(entry.data.data(), offset, entry.data.size());
table.insert(tuple, 0);
} else if (type == 2) { // DELETE
storage::HeapTable::TupleId rid;
if (offset + 8 > entry.data.size()) return;
std::memcpy(&rid.page_num, entry.data.data() + offset, 4);
std::memcpy(&rid.slot_num, entry.data.data() + offset + 4, 4);
table.remove(rid, 0);
}
}
QueryExecutor::QueryExecutor(Catalog& catalog, storage::BufferPoolManager& bpm,
transaction::LockManager& lock_manager,
transaction::TransactionManager& transaction_manager,
recovery::LogManager* log_manager,
cluster::ClusterManager* cluster_manager)
: catalog_(catalog),
bpm_(bpm),
lock_manager_(lock_manager),
transaction_manager_(transaction_manager),
log_manager_(log_manager),
cluster_manager_(cluster_manager) {}
QueryExecutor::~QueryExecutor() {
if (current_txn_ != nullptr) {
transaction_manager_.abort(current_txn_);
}
}
std::shared_ptr<PreparedStatement> QueryExecutor::prepare(const std::string& sql) {
auto lexer = std::make_unique<parser::Lexer>(sql);
parser::Parser parser(std::move(lexer));
auto stmt = parser.parse_statement();
if (!stmt) return nullptr;
auto prepared = std::make_shared<PreparedStatement>();
prepared->stmt = std::shared_ptr<parser::Statement>(stmt.release());
prepared->sql = sql;
// Cache metadata for INSERT fast-path
if (prepared->stmt->type() == parser::StmtType::Insert) {
const auto& insert_stmt = dynamic_cast<const parser::InsertStatement&>(*prepared->stmt);
if (insert_stmt.table()) {
const std::string table_name = insert_stmt.table()->to_string();
auto table_meta_opt = catalog_.get_table_by_name(table_name);
if (table_meta_opt.has_value()) {
prepared->table_meta = table_meta_opt.value();
prepared->schema = std::make_unique<Schema>();
for (const auto& col : prepared->table_meta->columns) {
prepared->schema->add_column(col.name, col.type);
}
prepared->table =
std::make_unique<storage::HeapTable>(table_name, bpm_, *prepared->schema);
// Cache B-tree index objects
for (const auto& idx_info : prepared->table_meta->indexes) {
if (!idx_info.column_positions.empty()) {
uint16_t pos = idx_info.column_positions[0];
common::ValueType ktype = prepared->table_meta->columns[pos].type;
prepared->indexes.push_back(
std::make_unique<storage::BTreeIndex>(idx_info.name, bpm_, ktype));
}
}
}
}
}
return prepared;
}
QueryResult QueryExecutor::execute(const PreparedStatement& prepared,
const std::vector<common::Value>& params) {
// Fast-path for INSERT
if (prepared.stmt->type() == parser::StmtType::Insert && prepared.table) {
const auto start = std::chrono::high_resolution_clock::now();
QueryResult result;
current_params_ = ¶ms;
const bool is_auto_commit = (current_txn_ == nullptr);
transaction::Transaction* txn = current_txn_;
if (is_auto_commit) txn = transaction_manager_.begin();
try {
const auto& insert_stmt = dynamic_cast<const parser::InsertStatement&>(*prepared.stmt);
uint64_t rows_inserted = 0;
const uint64_t xmin = (txn != nullptr) ? txn->get_id() : 0;
for (const auto& row_exprs : insert_stmt.values()) {
std::pmr::vector<common::Value> values(&arena_);
values.reserve(row_exprs.size());
for (const auto& expr : row_exprs) {
values.push_back(expr->evaluate(nullptr, nullptr, current_params_));
}
const Tuple tuple(std::move(values));
const auto tid = prepared.table->insert(tuple, xmin);
// Index updates using cached index objects
std::string err;
size_t cached_idx_ptr = 0;
for (const auto& idx_info : prepared.table_meta->indexes) {
if (!idx_info.column_positions.empty()) {
uint16_t pos = idx_info.column_positions[0];
if (!apply_index_write(*prepared.indexes[cached_idx_ptr++], tuple.get(pos),
tid, IndexOp::Insert, err)) {
throw std::runtime_error(err);
}
}
}
if (txn != nullptr) {
txn->add_undo_log(transaction::UndoLog::Type::INSERT, prepared.table_meta->name,
tid);
if (!batch_insert_mode_) {
if (!lock_manager_.acquire_exclusive(txn, tid)) {
throw std::runtime_error("Failed to acquire exclusive lock");
}
}
}
rows_inserted++;
}
if (is_auto_commit && txn != nullptr) transaction_manager_.commit(txn);
result.set_rows_affected(rows_inserted);
} catch (const std::exception& e) {
if (is_auto_commit && txn != nullptr) transaction_manager_.abort(txn);
result.set_error(std::string("Execution error: ") + e.what());
}
current_params_ = nullptr;
const auto end = std::chrono::high_resolution_clock::now();
result.set_execution_time(
std::chrono::duration_cast<std::chrono::microseconds>(end - start).count());
arena_.reset();
return result;
}
// Fallback for other statement types
current_params_ = ¶ms;
QueryResult res = execute(*(prepared.stmt));
current_params_ = nullptr;
return res;
}
QueryResult QueryExecutor::execute(const std::string& sql) {
std::shared_ptr<parser::Statement> stmt = nullptr;
{
std::lock_guard<std::mutex> lock(cache_mutex_);
auto it = statement_cache_.find(sql);
if (it != statement_cache_.end()) {
stmt = it->second;
}
}
if (!stmt) {
auto lexer = std::make_unique<parser::Lexer>(sql);
parser::Parser parser(std::move(lexer));
auto parsed_stmt = parser.parse_statement();
if (parsed_stmt) {
stmt = std::shared_ptr<parser::Statement>(parsed_stmt.release());
std::lock_guard<std::mutex> lock(cache_mutex_);
statement_cache_[sql] = stmt;
}
}
if (!stmt) {
QueryResult res;
res.set_error("Failed to parse SQL statement");
return res;
}
return execute(*stmt);
}
QueryResult QueryExecutor::execute(const parser::Statement& stmt) {
const auto start = std::chrono::high_resolution_clock::now();
QueryResult result;
/* Handle Explicit Transaction Control */
if (stmt.type() == parser::StmtType::TransactionBegin) {
return execute_begin();
}
if (stmt.type() == parser::StmtType::TransactionCommit) {
return execute_commit();
}
if (stmt.type() == parser::StmtType::TransactionRollback) {
return execute_rollback();
}
/* Auto-commit mode if no current transaction */
const bool is_auto_commit = (current_txn_ == nullptr);
transaction::Transaction* txn = current_txn_;
if (is_auto_commit &&
(stmt.type() == parser::StmtType::Select || stmt.type() == parser::StmtType::Insert ||
stmt.type() == parser::StmtType::Update || stmt.type() == parser::StmtType::Delete)) {
txn = transaction_manager_.begin();
}
try {
if (stmt.type() == parser::StmtType::Select) {
result = execute_select(dynamic_cast<const parser::SelectStatement&>(stmt), txn);
} else if (stmt.type() == parser::StmtType::CreateTable) {
result = execute_create_table(dynamic_cast<const parser::CreateTableStatement&>(stmt));
} else if (stmt.type() == parser::StmtType::CreateIndex) {
result = execute_create_index(dynamic_cast<const parser::CreateIndexStatement&>(stmt));
} else if (stmt.type() == parser::StmtType::DropTable) {
result = execute_drop_table(dynamic_cast<const parser::DropTableStatement&>(stmt));
} else if (stmt.type() == parser::StmtType::DropIndex) {
result = execute_drop_index(dynamic_cast<const parser::DropIndexStatement&>(stmt));
} else if (stmt.type() == parser::StmtType::Insert) {
result = execute_insert(dynamic_cast<const parser::InsertStatement&>(stmt), txn);
} else if (stmt.type() == parser::StmtType::Delete) {
result = execute_delete(dynamic_cast<const parser::DeleteStatement&>(stmt), txn);
} else if (stmt.type() == parser::StmtType::Update) {
result = execute_update(dynamic_cast<const parser::UpdateStatement&>(stmt), txn);
} else if (stmt.type() == parser::StmtType::TransactionBegin) {
result = execute_begin();
} else if (stmt.type() == parser::StmtType::TransactionCommit) {
result = execute_commit();
} else if (stmt.type() == parser::StmtType::TransactionRollback) {
result = execute_rollback();
} else if (stmt.type() == parser::StmtType::Analyze) {
result = execute_analyze(dynamic_cast<const parser::AnalyzeStatement&>(stmt));
} else {
result.set_error("Unsupported statement type");
}
/* Auto-commit success */
if (is_auto_commit && txn != nullptr) {
transaction_manager_.commit(txn);
}
} catch (const std::exception& e) {
if (is_auto_commit && txn != nullptr) {
transaction_manager_.abort(txn);
}
result.set_error(std::string("Execution error: ") + e.what());
} catch (...) {
if (is_auto_commit && txn != nullptr) {
transaction_manager_.abort(txn);
}
result.set_error("Unknown execution error");
}
const auto end = std::chrono::high_resolution_clock::now();
const auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
result.set_execution_time(static_cast<uint64_t>(duration.count()));
// Reset arena for the next query to reclaim zero-allocation memory
arena_.reset();
return result;
}
QueryResult QueryExecutor::execute_begin() {
QueryResult res;
if (current_txn_ != nullptr) {
res.set_error("Transaction already in progress");
return res;
}
current_txn_ = transaction_manager_.begin();
return res;
}
QueryResult QueryExecutor::execute_commit() {
QueryResult res;
if (current_txn_ == nullptr) {
res.set_error("No transaction in progress");
return res;
}
transaction_manager_.commit(current_txn_);
current_txn_ = nullptr;
return res;
}
QueryResult QueryExecutor::execute_rollback() {
QueryResult res;
if (current_txn_ == nullptr) {
res.set_error("No transaction in progress");
return res;
}
transaction_manager_.abort(current_txn_);
current_txn_ = nullptr;
return res;
}
QueryResult QueryExecutor::execute_select(const parser::SelectStatement& stmt,
transaction::Transaction* txn) {
QueryResult result;
/* Build execution plan */
std::unique_ptr<Operator> root;
std::unique_ptr<VectorizedOperator> vec_root;
bool has_sort_or_limit = !stmt.order_by().empty() || stmt.has_limit() || stmt.has_offset();
// Cost-based Volcano/Vectorized chooser using row estimates
bool use_vectorized = false;
if (parallel_ && storage_manager_ && !has_sort_or_limit) {
// Extract table name from FROM clause (only for simple column refs)
// Fall through to Volcano for JOINs, subqueries, and aliased tables
const auto* from_expr = stmt.from();
if (from_expr != nullptr && from_expr->type() == parser::ExprType::Column) {
std::string table_name = from_expr->to_string();
auto table_meta_opt = catalog_.get_table_by_name(table_name);
if (table_meta_opt.has_value()) {
const auto* table_meta = table_meta_opt.value();
// Start with scan estimate as baseline; filter selectivity will override if
// eligible
uint64_t estimated_rows = optimizer::RowEstimator::estimate_scan_rows(*table_meta);
// Use filter selectivity when WHERE clause is simple and stats available
if (stmt.where() && stmt.where()->type() == parser::ExprType::Binary) {
const auto* bin_expr = dynamic_cast<const parser::BinaryExpr*>(stmt.where());
if (bin_expr != nullptr) {
std::string col_name;
common::Value pred_val;
bool eligible = false;
// col OP constant (e.g., id > 5000 or status = 'active')
if (bin_expr->left().type() == parser::ExprType::Column &&
bin_expr->right().type() == parser::ExprType::Constant) {
col_name = bin_expr->left().to_string();
pred_val =
bin_expr->right().evaluate(nullptr, nullptr, current_params_);
eligible = true;
} else if (bin_expr->right().type() == parser::ExprType::Column &&
bin_expr->left().type() == parser::ExprType::Constant) {
col_name = bin_expr->right().to_string();
pred_val = bin_expr->left().evaluate(nullptr, nullptr, current_params_);
eligible = true;
}
if (eligible) {
estimated_rows = optimizer::RowEstimator::estimate_filter_rows(
*table_meta, col_name, pred_val);
}
}
}
// Use Vectorized for large scans (>10k rows — heuristic crossover point)
use_vectorized = estimated_rows > kVectorizedRowThreshold;
}
}
}
if (use_vectorized) {
vec_root = build_vectorized_plan(stmt, txn, has_sort_or_limit);
root = std::move(vec_root);
} else {
root = build_plan(stmt, txn);
}
if (!root) {
result.set_error("Failed to build execution plan (check table existence and FROM clause)");
return result;
}
/* Initialize and open operators */
root->set_memory_resource(&arena_);
root->set_params(current_params_);
if (!root->init() || !root->open()) {
result.set_error(root->error().empty() ? "Failed to open execution plan" : root->error());
return result;
}
/* Set result schema */
result.set_schema(root->output_schema());
if (use_vectorized) {
/* Vectorized batch iteration */
auto batch = VectorBatch::create(root->output_schema());
auto* vec_op = dynamic_cast<VectorizedOperator*>(root.get());
assert(vec_op && "root must be a VectorizedOperator when use_vectorized is true");
while (true) {
bool has_more = false;
try {
has_more = vec_op->next_batch(*batch);
} catch (const std::out_of_range& e) {
result.set_error(std::string("vector access error in next_batch: ") + e.what() +
" batch_cols=" + std::to_string(batch->column_count()) +
" batch_rows=" + std::to_string(batch->row_count()));
break;
} catch (const std::exception& e) {
result.set_error(std::string("next_batch error: ") + e.what());
break;
} catch (...) {
result.set_error("next_batch error: unknown exception type");
break;
}
if (!has_more) break;
for (size_t r = 0; r < batch->row_count(); ++r) {
Tuple tuple;
for (size_t c = 0; c < batch->column_count(); ++c) {
tuple.set(c, batch->get_column(c).get(r));
}
result.add_row(Tuple(tuple.values(), nullptr));
}
}
} else {
/* Pull tuples (Volcano model) */
Tuple tuple;
while (root->next(tuple)) {
// MUST deep-copy tuple to default allocator (heap) so it outlives the arena reset
result.add_row(Tuple(tuple.values(), nullptr));
}
}
root->close();
return result;
}
QueryResult QueryExecutor::execute_create_table(const parser::CreateTableStatement& stmt) {
QueryResult result;
/* Convert parser columns to catalog columns */
std::vector<ColumnInfo> catalog_cols;
uint16_t pos = 0;
for (const auto& col : stmt.columns()) {
common::ValueType type = common::ValueType::TYPE_TEXT;
if (col.type_ == "INT" || col.type_ == "INTEGER") {
type = common::ValueType::TYPE_INT32;
} else if (col.type_ == "BIGINT") {
type = common::ValueType::TYPE_INT64;
} else if (col.type_ == "FLOAT" || col.type_ == "DOUBLE") {
type = common::ValueType::TYPE_FLOAT64;
} else if (col.type_ == "BOOLEAN" || col.type_ == "BOOL") {
type = common::ValueType::TYPE_BOOL;
}
catalog_cols.emplace_back(col.name_, type, pos++);
}
/* Update catalog */
oid_t table_id = 0;
if (is_local_only_) {
table_id = catalog_.create_table_local(stmt.table_name(), std::move(catalog_cols));
} else {
table_id = catalog_.create_table(stmt.table_name(), std::move(catalog_cols));
}
if (table_id == 0) {
result.set_error("Failed to create table in catalog");
return result;
}
/* Create physical file */
auto table_info_opt = catalog_.get_table(table_id);
if (!table_info_opt.has_value()) {
result.set_error("Failed to retrieve table info from catalog");
return result;
}
const auto* table_info = table_info_opt.value();
storage::HeapTable table(table_info->name, bpm_, executor::Schema());
if (!table.create()) {
static_cast<void>(catalog_.drop_table(table_id));
result.set_error("Failed to create table file");
return result;
}
result.set_rows_affected(1);
return result;
}
QueryResult QueryExecutor::execute_create_index(const parser::CreateIndexStatement& stmt) {
QueryResult result;
/* Reject composite indexes */
if (stmt.columns().size() != 1) {
result.set_error("Composite indexes not supported");
return result;
}
auto table_meta_opt = catalog_.get_table_by_name(stmt.table_name());
if (!table_meta_opt.has_value()) {
result.set_error("Table not found: " + stmt.table_name());
return result;
}
const auto* table_meta = table_meta_opt.value();
std::vector<uint16_t> col_positions;
common::ValueType key_type = common::ValueType::TYPE_NULL;
const auto& col_name = stmt.columns()[0];
bool found = false;
for (const auto& col : table_meta->columns) {
if (col.name == col_name) {
col_positions.push_back(col.position);
key_type = col.type;
found = true;
break;
}
}
if (!found) {
result.set_error("Column not found: " + col_name);
return result;
}
/* Update Catalog */
const oid_t index_id = catalog_.create_index(stmt.index_name(), table_meta->table_id,
col_positions, IndexType::BTree, stmt.unique());
if (index_id == 0) {
result.set_error("Failed to create index in catalog");
return result;
}
/* Create Physical Index File */
storage::BTreeIndex index(stmt.index_name(), bpm_, key_type);
if (!index.create()) {
static_cast<void>(catalog_.drop_index(index_id));
result.set_error("Failed to create index file");
return result;
}
/* Populate Index with existing data (Backfill) */
Schema schema;
for (const auto& col : table_meta->columns) {
schema.add_column(col.name, col.type);
}
storage::HeapTable table(stmt.table_name(), bpm_, schema);
auto iter = table.scan();
storage::HeapTable::TupleMeta meta;
std::string err;
while (iter.next_meta(meta)) {
if (meta.xmax == 0) {
/* Extract key from tuple */
const common::Value& key = meta.tuple.get(col_positions[0]);
if (!apply_index_write(index, key, iter.current_id(), IndexOp::Insert, err)) {
static_cast<void>(index.drop());
static_cast<void>(catalog_.drop_index(index_id));
result.set_error(err);
return result;
}
}
}
result.set_rows_affected(1);
return result;
}
QueryResult QueryExecutor::execute_insert(const parser::InsertStatement& stmt,
transaction::Transaction* txn) {
QueryResult result;
if (!stmt.table()) {
result.set_error("Target table not specified");
return result;
}
const std::string table_name = stmt.table()->to_string();
auto table_meta_opt = catalog_.get_table_by_name(table_name);
if (!table_meta_opt.has_value()) {
result.set_error("Table not found: " + table_name);
return result;
}
const auto* table_meta = table_meta_opt.value();
/* Construct Schema */
Schema schema;
for (const auto& col : table_meta->columns) {
schema.add_column(col.name, col.type);
}
storage::HeapTable table(table_name, bpm_, schema);
uint64_t rows_inserted = 0;
const uint64_t xmin = (txn != nullptr) ? txn->get_id() : 0;
for (const auto& row_exprs : stmt.values()) {
// Zero-allocation vector construction via Arena
std::pmr::vector<common::Value> values(&arena_);
values.reserve(row_exprs.size());
for (const auto& expr : row_exprs) {
// Include bound parameters in expression evaluation
values.push_back(expr->evaluate(nullptr, nullptr, current_params_));
}
const Tuple tuple(std::move(values));
// Distributed Routing: Skip if is_local_only_
if (!is_local_only_ && cluster_manager_ != nullptr && !table_meta->shards.empty()) {
uint32_t shard_id = 0;
if (!tuple.empty()) {
shard_id = cluster::ShardManager::compute_shard(
tuple.get(0), static_cast<uint32_t>(table_meta->shards.size()));
}
auto shard_info_opt = cluster::ShardManager::get_target_node(*table_meta, shard_id);
if (shard_info_opt.has_value()) {
const auto& shard_info = shard_info_opt.value();
network::RpcClient client(shard_info.node_address, shard_info.port);
if (client.connect()) {
network::ExecuteFragmentArgs args;
args.context_id = context_id_;
// Optimization: Only forward the current row
args.sql = "INSERT INTO " + table_name + " VALUES " + tuple.to_string() + ";";
std::vector<uint8_t> resp;
if (!client.call(network::RpcType::ExecuteFragment, args.serialize(), resp)) {
result.set_error("Failed to forward INSERT to data node " +
shard_info.node_address);
return result;
}
auto reply = network::QueryResultsReply::deserialize(resp);
if (!reply.success) {
result.set_error("Remote INSERT failed: " + reply.error_msg);
return result;
}
rows_inserted++;
continue;
}
}
}
const auto tid = table.insert(tuple, xmin);
/* Update Indexes */
std::string err;
for (const auto& idx_info : table_meta->indexes) {
if (!idx_info.column_positions.empty()) {
uint16_t pos = idx_info.column_positions[0];
common::ValueType ktype = table_meta->columns[pos].type;
storage::BTreeIndex index(idx_info.name, bpm_, ktype);
if (!apply_index_write(index, tuple.get(pos), tid, IndexOp::Insert, err)) {
throw std::runtime_error(err);
}
}
}
/* Log INSERT */
if (log_manager_ != nullptr && txn != nullptr) {
recovery::LogRecord log(txn->get_id(), txn->get_prev_lsn(),
recovery::LogRecordType::INSERT, table_name, tid, tuple);
const auto lsn = log_manager_->append_log_record(log);
txn->set_prev_lsn(lsn);
}
/* Record undo log and Acquire Exclusive Lock if in transaction */
if (txn != nullptr) {
txn->add_undo_log(transaction::UndoLog::Type::INSERT, table_name, tid);
if (!lock_manager_.acquire_exclusive(txn, tid)) {
throw std::runtime_error("Failed to acquire exclusive lock");
}
}
rows_inserted++;
}
result.set_rows_affected(rows_inserted);
return result;
}
QueryResult QueryExecutor::execute_delete(const parser::DeleteStatement& stmt,
transaction::Transaction* txn) {
QueryResult result;
const std::string table_name = stmt.table()->to_string();
auto table_meta_opt = catalog_.get_table_by_name(table_name);
if (!table_meta_opt.has_value()) {
result.set_error("Table not found: " + table_name);
return result;
}
const auto* table_meta = table_meta_opt.value();
Schema schema;
for (const auto& col : table_meta->columns) {
schema.add_column(col.name, col.type);
}
storage::HeapTable table(table_name, bpm_, schema);
const uint64_t xmax = (txn != nullptr) ? txn->get_id() : 0;
uint64_t rows_deleted = 0;
/* Phase 1: Collect RIDs to avoid Halloween Problem */
std::vector<storage::HeapTable::TupleId> target_rids;
auto iter = table.scan();
storage::HeapTable::TupleMeta meta;
while (iter.next_meta(meta)) {
bool match = true;
if (stmt.where()) {
// Support parameters in DELETE WHERE
match = stmt.where()->evaluate(&meta.tuple, &schema, current_params_).as_bool();
}
if (match && meta.xmax == 0) {
target_rids.push_back(iter.current_id());
}
}
/* Phase 2: Apply Deletions */
for (const auto& rid : target_rids) {
// POC: Replication Logic
if (cluster_manager_ != nullptr && cluster_manager_->get_raft_manager() != nullptr) {
auto shard_group = cluster_manager_->get_raft_manager()->get_group(1);
if (shard_group && shard_group->is_leader()) {
std::vector<uint8_t> cmd;
cmd.push_back(2); // Type 2: DELETE
uint32_t tlen = static_cast<uint32_t>(table_name.size());
size_t off = cmd.size();
cmd.resize(off + 4 + tlen + 8);
std::memcpy(cmd.data() + off, &tlen, 4);
std::memcpy(cmd.data() + off + 4, table_name.data(), tlen);
std::memcpy(cmd.data() + off + 4 + tlen, &rid.page_num, 4);
std::memcpy(cmd.data() + off + 4 + tlen + 4, &rid.slot_num, 4);
if (!shard_group->replicate(cmd)) {
result.set_error("Replication failed for shard 1");
return result;
}
}
}
/* Retrieve old tuple for logging and index maintenance (unconditional) */
Tuple old_tuple;
if (!table.get(rid, old_tuple)) {
result.set_error("Failed to retrieve tuple for deletion maintenance: " +
rid.to_string());
return result;
}
if (table.remove(rid, xmax)) {
/* Update Indexes */
std::string err;
if (!old_tuple.empty()) {
for (const auto& idx_info : table_meta->indexes) {
if (!idx_info.column_positions.empty()) {
uint16_t pos = idx_info.column_positions[0];
common::ValueType ktype = table_meta->columns[pos].type;
storage::BTreeIndex index(idx_info.name, bpm_, ktype);
if (!apply_index_write(index, old_tuple.get(pos), rid, IndexOp::Remove,
err)) {
throw std::runtime_error(err);
}
}
}
}
/* Log DELETE */
if (log_manager_ != nullptr && txn != nullptr) {
recovery::LogRecord log(txn->get_id(), txn->get_prev_lsn(),
recovery::LogRecordType::MARK_DELETE, table_name, rid,
old_tuple);
const auto lsn = log_manager_->append_log_record(log);
txn->set_prev_lsn(lsn);
}
if (txn != nullptr) {
txn->add_undo_log(transaction::UndoLog::Type::DELETE, table_name, rid);
}
rows_deleted++;
}
}
result.set_rows_affected(rows_deleted);
return result;
}
QueryResult QueryExecutor::execute_update(const parser::UpdateStatement& stmt,
transaction::Transaction* txn) {
QueryResult result;
const std::string table_name = stmt.table()->to_string();
auto table_meta_opt = catalog_.get_table_by_name(table_name);
if (!table_meta_opt.has_value()) {
result.set_error("Table not found: " + table_name);
return result;
}
const auto* table_meta = table_meta_opt.value();
Schema schema;
for (const auto& col : table_meta->columns) {
schema.add_column(col.name, col.type);
}
storage::HeapTable table(table_name, bpm_, schema);
const uint64_t txn_id = (txn != nullptr) ? txn->get_id() : 0;
uint64_t rows_updated = 0;
/* Phase 1: Collect RIDs and compute new values to avoid Halloween Problem */
struct UpdateOp {
storage::HeapTable::TupleId rid;
Tuple old_tuple;
Tuple new_tuple;
};
std::vector<UpdateOp> updates;
auto iter = table.scan();
storage::HeapTable::TupleMeta meta;
while (iter.next_meta(meta)) {
bool match = true;
if (stmt.where()) {
match = stmt.where()->evaluate(&meta.tuple, &schema, current_params_).as_bool();
}
if (match && meta.xmax == 0) {
/* Compute new tuple values */
Tuple new_tuple = meta.tuple;
for (const auto& [col_expr, val_expr] : stmt.set_clauses()) {
const std::string col_name = col_expr->to_string();
const size_t idx = schema.find_column(col_name);
if (idx != static_cast<size_t>(-1)) {
new_tuple.set(idx, val_expr->evaluate(&meta.tuple, &schema, current_params_));
}
}
updates.push_back({iter.current_id(), meta.tuple, std::move(new_tuple)});
}
}
/* Phase 2: Apply Updates */
for (const auto& op : updates) {
if (table.remove(op.rid, txn_id)) {
/* Update Indexes - Remove old, Insert new */
std::string err;
for (const auto& idx_info : table_meta->indexes) {
if (!idx_info.column_positions.empty()) {
uint16_t pos = idx_info.column_positions[0];
common::ValueType ktype = table_meta->columns[pos].type;
storage::BTreeIndex index(idx_info.name, bpm_, ktype);
if (!apply_index_write(index, op.old_tuple.get(pos), op.rid, IndexOp::Remove,
err)) {
throw std::runtime_error(err);
}
}
}
/* Log DELETE part of update */
if (log_manager_ != nullptr && txn != nullptr) {
recovery::LogRecord log(txn->get_id(), txn->get_prev_lsn(),
recovery::LogRecordType::MARK_DELETE, table_name, op.rid,
op.old_tuple);
const auto lsn = log_manager_->append_log_record(log);
txn->set_prev_lsn(lsn);
}
const auto new_tid = table.insert(op.new_tuple, txn_id);
/* Update Indexes - Insert new */
for (const auto& idx_info : table_meta->indexes) {
if (!idx_info.column_positions.empty()) {
uint16_t pos = idx_info.column_positions[0];
common::ValueType ktype = table_meta->columns[pos].type;
storage::BTreeIndex index(idx_info.name, bpm_, ktype);
if (!apply_index_write(index, op.new_tuple.get(pos), new_tid, IndexOp::Insert,
err)) {
throw std::runtime_error(err);
}
}
}
/* Log INSERT part of update */
if (log_manager_ != nullptr && txn != nullptr) {
recovery::LogRecord log(txn->get_id(), txn->get_prev_lsn(),
recovery::LogRecordType::INSERT, table_name, new_tid,
op.new_tuple);
const auto lsn = log_manager_->append_log_record(log);
txn->set_prev_lsn(lsn);
}
if (txn != nullptr) {
txn->add_undo_log(transaction::UndoLog::Type::UPDATE, table_name, new_tid, op.rid);
}
rows_updated++;
}
}
result.set_rows_affected(rows_updated);
return result;
}
QueryResult QueryExecutor::execute_analyze(const parser::AnalyzeStatement& stmt) {
QueryResult result;
auto table_meta_opt = catalog_.get_table_by_name(stmt.table_name());
if (!table_meta_opt.has_value()) {
result.set_error("Table not found: " + stmt.table_name());
return result;
}
const auto* table_meta = table_meta_opt.value();
Schema schema;
for (const auto& col : table_meta->columns) {
schema.add_column(col.name, col.type);
}
storage::HeapTable table(stmt.table_name(), bpm_, schema);
// Collect per-column stats by scanning the table (single pass)
std::vector<ColumnInfo> col_stats(table_meta->columns.size());
std::vector<common::HyperLogLog> ndv_estimators(table_meta->columns.size());