-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdatabase.rs
More file actions
657 lines (589 loc) · 21.8 KB
/
database.rs
File metadata and controls
657 lines (589 loc) · 21.8 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
use crate::background::{self, BackgroundWorkers};
use log::{debug, warn};
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tempfile::TempDir;
use crate::buffer::{BufferManager, BUFFER_POOL_SIZE};
use crate::catalog::{load_catalog_data, registry::TableRegistry, TableStatistics};
use crate::config::{background_config, IndexVacuumConfig, MvccVacuumConfig, WalConfig};
use crate::error::{QuillSQLError, QuillSQLResult};
use crate::execution::physical_plan::PhysicalPlan;
use crate::optimizer::LogicalOptimizer;
use crate::plan::logical_plan::{LogicalPlan, TransactionScope};
use crate::plan::PhysicalPlanner;
use crate::recovery::{ControlFileManager, RecoveryManager, WalManager};
use crate::session::SessionContext;
use crate::utils::{
table_ref::TableReference,
util::{pretty_format_logical_plan, pretty_format_physical_plan},
};
use crate::{
buffer::INVALID_PAGE_ID,
catalog::Catalog,
execution::ExecutionEngine,
plan::{LogicalPlanner, PlannerContext},
recovery::wal::{WalHeadDebug, WalSegmentDebug},
storage::{
disk_manager::DiskManager, disk_scheduler::DiskScheduler, tuple::Tuple,
DefaultStorageEngine, StorageEngine,
},
transaction::{
CommandId, IsolationLevel, LockDebugSnapshot, TransactionManager, TxnDebugSnapshot,
},
};
use sqlparser::ast::TransactionAccessMode;
#[derive(Debug, Default, Clone)]
pub struct WalOptions {
pub directory: Option<PathBuf>,
pub segment_size: Option<u64>,
pub sync_on_flush: Option<bool>,
pub persist_control_file_on_flush: Option<bool>,
pub writer_interval_ms: Option<Option<u64>>,
pub buffer_capacity: Option<usize>,
pub flush_coalesce_bytes: Option<usize>,
pub synchronous_commit: Option<bool>,
pub checkpoint_interval_ms: Option<Option<u64>>,
pub retain_segments: Option<usize>,
}
#[derive(Debug, Clone, Default)]
pub struct DatabaseOptions {
pub wal: WalOptions,
pub default_isolation_level: Option<IsolationLevel>,
}
enum DatabaseLocation {
OnDisk(String),
Temporary,
}
fn bootstrap_storage(
location: DatabaseLocation,
wal_options: &WalOptions,
) -> QuillSQLResult<(Arc<DiskManager>, WalConfig, Option<TempDir>)> {
match location {
DatabaseLocation::OnDisk(path) => {
let disk_manager = Arc::new(DiskManager::try_new(path.as_str())?);
let wal_config = wal_config_for_path(path.as_str(), wal_options);
Ok((disk_manager, wal_config, None))
}
DatabaseLocation::Temporary => {
let temp_dir = TempDir::new()?;
let temp_path = temp_dir.path().join("test.db");
let temp_str = temp_path
.to_str()
.ok_or_else(|| QuillSQLError::Internal("Invalid temp path".to_string()))?;
let disk_manager = Arc::new(DiskManager::try_new(temp_str)?);
let wal_config = wal_config_for_temp(temp_dir.path(), wal_options);
Ok((disk_manager, wal_config, Some(temp_dir)))
}
}
}
pub struct Database {
_temp_dir: Option<TempDir>,
pub(crate) buffer_pool: Arc<BufferManager>,
pub(crate) catalog: Catalog,
background_workers: BackgroundWorkers,
pub(crate) wal_manager: Arc<WalManager>,
pub(crate) transaction_manager: Arc<TransactionManager>,
default_isolation: IsolationLevel,
storage_engine: Arc<dyn StorageEngine>,
_table_registry: Arc<TableRegistry>,
debug_trace: Arc<Mutex<Option<DebugTrace>>>,
}
struct PreparedStatement {
optimized_logical_plan: LogicalPlan,
physical_plan: PhysicalPlan,
}
#[derive(Debug, Clone, Serialize)]
pub struct DebugTrace {
pub logical_plan: String,
pub physical_plan: String,
pub rows: usize,
pub duration_ms: u128,
pub logical_tree: DebugPlanNode,
pub physical_tree: DebugPlanNode,
}
#[derive(Debug, Clone, Serialize)]
pub struct BufferDebugStats {
pub capacity: usize,
pub free_frames: usize,
pub pinned_frames: usize,
pub dirty_frames: usize,
pub dirty_page_table: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct WalSegmentsDebug {
pub segments: Vec<WalSegmentDebug>,
}
#[derive(Debug, Clone, Serialize)]
pub struct DebugPlanNode {
pub op: String,
pub children: Vec<DebugPlanNode>,
}
#[derive(Debug, Clone, Serialize)]
pub struct DebugPlanSnapshot {
pub logical: DebugPlanNode,
pub physical: DebugPlanNode,
}
#[derive(Debug, Clone, Serialize)]
pub struct MvccVersionSample {
pub table: String,
pub rid: String,
pub insert_txn: u64,
pub delete_txn: u64,
pub visible: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct MvccVersionsDebug {
pub samples: Vec<MvccVersionSample>,
pub note: String,
}
impl DebugPlanNode {
pub fn from_physical(plan: &PhysicalPlan) -> Self {
Self {
op: plan.display_name(),
children: plan
.inputs()
.iter()
.map(|child| Self::from_physical(child))
.collect(),
}
}
pub fn from_logical(plan: &LogicalPlan) -> Self {
Self {
op: plan.to_string(),
children: plan
.inputs()
.iter()
.map(|child| Self::from_logical(child))
.collect(),
}
}
}
impl Database {
pub fn new_on_disk(db_path: &str) -> QuillSQLResult<Self> {
Self::new_on_disk_with_options(db_path, DatabaseOptions::default())
}
pub fn new_on_disk_with_options(
db_path: &str,
options: DatabaseOptions,
) -> QuillSQLResult<Self> {
Self::new_with_location(DatabaseLocation::OnDisk(db_path.to_string()), options)
}
pub fn new_temp() -> QuillSQLResult<Self> {
Self::new_temp_with_options(DatabaseOptions::default())
}
pub fn new_temp_with_options(options: DatabaseOptions) -> QuillSQLResult<Self> {
Self::new_with_location(DatabaseLocation::Temporary, options)
}
fn new_with_location(
location: DatabaseLocation,
options: DatabaseOptions,
) -> QuillSQLResult<Self> {
let (disk_manager, wal_config, temp_dir) = bootstrap_storage(location, &options.wal)?;
let disk_scheduler = Arc::new(DiskScheduler::new(disk_manager.clone()));
let buffer_pool = Arc::new(BufferManager::new(BUFFER_POOL_SIZE, disk_scheduler.clone()));
let synchronous_commit = wal_config.synchronous_commit;
let (control_file, wal_init) =
ControlFileManager::load_or_init(&wal_config.directory, wal_config.segment_size)?;
let control_file = Arc::new(control_file);
let wal_manager = Arc::new(WalManager::new_with_scheduler(
wal_config.clone(),
Some(wal_init),
Some(control_file.clone()),
disk_scheduler.clone(),
)?);
let transaction_manager = Arc::new(TransactionManager::new(
wal_manager.clone(),
synchronous_commit,
));
let worker_cfg = background_config(
&wal_config,
IndexVacuumConfig::default(),
MvccVacuumConfig::default(),
);
let mut background_workers = BackgroundWorkers::new();
if let Some(interval) = worker_cfg.wal_writer_interval {
if let Some(handle) = wal_manager.start_background_flush(interval)? {
background_workers.register(background::wal_writer_worker(handle, interval));
}
}
buffer_pool.set_wal_manager(wal_manager.clone());
let table_registry = Arc::new(TableRegistry::new());
let catalog = Catalog::new(
buffer_pool.clone(),
disk_manager.clone(),
table_registry.clone(),
);
let storage_engine: Arc<dyn StorageEngine> = Arc::new(DefaultStorageEngine::default());
let recovery_summary = RecoveryManager::new(wal_manager.clone(), disk_scheduler.clone())
.with_buffer_pool(buffer_pool.clone())
.replay()?;
if recovery_summary.redo_count > 0 {
debug!(
"Recovery replayed {} record(s) starting at LSN {}",
recovery_summary.redo_count, recovery_summary.start_lsn
);
}
if !recovery_summary.loser_transactions.is_empty() {
warn!(
"{} transaction(s) require undo after recovery: {:?}",
recovery_summary.loser_transactions.len(),
recovery_summary.loser_transactions
);
}
let wal_for_workers: Arc<dyn background::CheckpointWal> = wal_manager.clone();
let buffer_for_workers: Arc<dyn background::BufferMaintenance> = buffer_pool.clone();
let txn_for_workers: Arc<dyn background::TxnSnapshotOps> = transaction_manager.clone();
background_workers.register_opt(background::spawn_checkpoint_worker(
wal_for_workers.clone(),
buffer_for_workers.clone(),
txn_for_workers.clone(),
worker_cfg.checkpoint_interval,
));
background_workers.register_opt(background::spawn_bg_writer(
buffer_for_workers.clone(),
worker_cfg.bg_writer_interval,
));
let mvcc_interval = if worker_cfg.mvcc_vacuum.interval_ms == 0 {
None
} else {
Some(Duration::from_millis(worker_cfg.mvcc_vacuum.interval_ms))
};
background_workers.register_opt(background::spawn_mvcc_vacuum_worker(
txn_for_workers,
mvcc_interval,
worker_cfg.mvcc_vacuum.batch_limit,
table_registry.clone(),
));
let mut db = Self {
_temp_dir: temp_dir,
buffer_pool,
catalog,
background_workers,
wal_manager,
transaction_manager,
default_isolation: options
.default_isolation_level
.unwrap_or(IsolationLevel::ReadUncommitted),
storage_engine,
_table_registry: table_registry,
debug_trace: Arc::new(Mutex::new(None)),
};
load_catalog_data(&mut db)?;
Ok(db)
}
pub fn run(&mut self, sql: &str) -> QuillSQLResult<Vec<Tuple>> {
let mut session = SessionContext::new(self.default_isolation);
self.run_with_session(&mut session, sql)
}
pub fn run_with_session(
&mut self,
session: &mut SessionContext,
sql: &str,
) -> QuillSQLResult<Vec<Tuple>> {
let start = Instant::now();
let PreparedStatement {
optimized_logical_plan,
physical_plan,
} = self.plan_statement(sql)?;
let logical_plan_str = pretty_format_logical_plan(&optimized_logical_plan);
let physical_plan_str = pretty_format_physical_plan(&physical_plan);
let logical_tree = DebugPlanNode::from_logical(&optimized_logical_plan);
let physical_tree = DebugPlanNode::from_physical(&physical_plan);
if let Some(result) = self.execute_transaction_control(session, &optimized_logical_plan)? {
return Ok(result);
}
let result = self.execute_physical_plan(session, physical_plan)?;
let elapsed = start.elapsed().as_millis();
let rows = result.len();
if let Ok(mut guard) = self.debug_trace.lock() {
*guard = Some(DebugTrace {
logical_plan: logical_plan_str,
physical_plan: physical_plan_str,
logical_tree,
physical_tree,
rows,
duration_ms: elapsed,
});
}
Ok(result)
}
pub fn default_isolation(&self) -> IsolationLevel {
self.default_isolation
}
pub fn create_logical_plan(&mut self, sql: &str) -> QuillSQLResult<LogicalPlan> {
// sql -> ast
let stmts = crate::sql::parser::parse_sql(sql)?;
if stmts.len() != 1 {
return Err(QuillSQLError::NotSupport(
"only support one sql statement".to_string(),
));
}
let stmt = &stmts[0];
let mut planner = LogicalPlanner {
context: PlannerContext {
catalog: &self.catalog,
},
};
// ast -> logical plan
planner.plan(stmt)
}
pub fn analyze_table(&mut self, table_ref: &TableReference) -> QuillSQLResult<TableStatistics> {
self.catalog.analyze_table(table_ref)
}
pub fn flush(&self) -> QuillSQLResult<()> {
let target = self.wal_manager.max_assigned_lsn();
let _ = self.wal_manager.flush_until(target)?;
self.wal_manager.persist_control_file()?;
self.buffer_pool.flush_all_pages()
}
pub fn debug_last_trace(&self) -> Option<DebugTrace> {
self.debug_trace.lock().ok().and_then(|guard| guard.clone())
}
pub fn debug_wal_head(&self) -> WalHeadDebug {
self.wal_manager.debug_head()
}
pub fn debug_wal_segments(&self) -> QuillSQLResult<WalSegmentsDebug> {
Ok(WalSegmentsDebug {
segments: self.wal_manager.debug_segments()?,
})
}
pub fn debug_wal_peek(
&self,
limit: usize,
) -> QuillSQLResult<Vec<crate::recovery::wal::WalPeekDebug>> {
self.wal_manager.debug_peek(limit)
}
pub fn debug_lock_snapshot(&self) -> LockDebugSnapshot {
self.transaction_manager.lock_manager_arc().debug_snapshot()
}
pub fn debug_buffer_stats(&self) -> BufferDebugStats {
let frames = self.buffer_pool.frame_meta_snapshot();
let free_frames = frames
.iter()
.filter(|meta| meta.page_id == INVALID_PAGE_ID)
.count();
let pinned_frames = frames.iter().filter(|meta| meta.pin_count > 0).count();
let dirty_frames = frames.iter().filter(|meta| meta.is_dirty).count();
let dirty_page_table = self.buffer_pool.dirty_page_table_snapshot().len();
BufferDebugStats {
capacity: frames.len(),
free_frames,
pinned_frames,
dirty_frames,
dirty_page_table,
}
}
pub fn debug_txn_snapshot(&self) -> TxnDebugSnapshot {
self.transaction_manager.debug_snapshot()
}
pub fn debug_mvcc_versions(&self) -> QuillSQLResult<MvccVersionsDebug> {
let mut samples = Vec::new();
let max_samples = 20usize;
let snapshot = self
.transaction_manager
.snapshot(self.transaction_manager.next_txn_id_hint());
for (table_ref, heap) in self._table_registry.iter_tables() {
let mut current = heap.get_first_rid()?;
while let Some(rid) = current {
if samples.len() >= max_samples {
break;
}
let meta = heap.tuple_meta(rid)?;
let visible = snapshot.is_visible(&meta, 0 as CommandId, |tid| {
self.transaction_manager.transaction_status(tid)
});
samples.push(MvccVersionSample {
table: table_ref.to_string(),
rid: rid.to_string(),
insert_txn: meta.insert_txn_id,
delete_txn: meta.delete_txn_id,
visible,
});
current = heap.get_next_rid(rid)?;
}
if samples.len() >= max_samples {
break;
}
}
Ok(MvccVersionsDebug {
samples,
note: format!("sampled up to {} tuples", max_samples),
})
}
pub fn debug_last_plan(&self) -> Option<DebugPlanSnapshot> {
self.debug_trace
.lock()
.ok()
.and_then(|opt| opt.clone())
.map(|trace| DebugPlanSnapshot {
logical: trace.logical_tree,
physical: trace.physical_tree,
})
}
pub fn table_statistics(
&self,
table_ref: &TableReference,
) -> Option<&crate::catalog::TableStatistics> {
self.catalog.table_statistics(table_ref)
}
pub fn transaction_manager(&self) -> Arc<TransactionManager> {
self.transaction_manager.clone()
}
fn plan_statement(&mut self, sql: &str) -> QuillSQLResult<PreparedStatement> {
let logical_plan = self.create_logical_plan(sql)?;
debug!(
"Logical Plan: \n{}",
pretty_format_logical_plan(&logical_plan)
);
let optimized_logical_plan = self.optimize_logical_plan(&logical_plan)?;
debug!(
"Optimized Logical Plan: \n{}",
pretty_format_logical_plan(&optimized_logical_plan)
);
let physical_plan = self.build_physical_plan(&optimized_logical_plan);
debug!(
"Physical Plan: \n{}",
pretty_format_physical_plan(&physical_plan)
);
Ok(PreparedStatement {
optimized_logical_plan,
physical_plan,
})
}
fn optimize_logical_plan(&self, logical_plan: &LogicalPlan) -> QuillSQLResult<LogicalPlan> {
LogicalOptimizer::new().optimize(logical_plan)
}
fn build_physical_plan(&self, logical_plan: &LogicalPlan) -> PhysicalPlan {
let physical_planner = PhysicalPlanner::new();
physical_planner.create_physical_plan(logical_plan.clone())
}
fn execute_transaction_control(
&self,
session: &mut SessionContext,
plan: &LogicalPlan,
) -> QuillSQLResult<Option<Vec<Tuple>>> {
match plan {
LogicalPlan::BeginTransaction(modes) => {
if session.has_active_transaction() {
return Err(QuillSQLError::Execution(
"transaction already active".to_string(),
));
}
let txn = self.transaction_manager.begin(
modes.unwrap_effective_isolation(session.default_isolation()),
modes
.access_mode
.unwrap_or(TransactionAccessMode::ReadWrite),
)?;
session.set_active_transaction(txn)?;
Ok(Some(vec![]))
}
LogicalPlan::CommitTransaction => {
let txn_ref = session
.active_txn_mut()
.ok_or_else(|| QuillSQLError::Execution("no active transaction".to_string()))?;
self.transaction_manager.commit(txn_ref)?;
session.clear_active_transaction();
Ok(Some(vec![]))
}
LogicalPlan::RollbackTransaction => {
let txn_ref = session
.active_txn_mut()
.ok_or_else(|| QuillSQLError::Execution("no active transaction".to_string()))?;
self.transaction_manager.abort(txn_ref)?;
session.clear_active_transaction();
Ok(Some(vec![]))
}
LogicalPlan::SetTransaction { scope, modes } => {
match scope {
TransactionScope::Session => session.apply_session_modes(modes),
TransactionScope::Transaction => session.apply_transaction_modes(modes),
}
Ok(Some(vec![]))
}
_ => Ok(None),
}
}
fn execute_physical_plan(
&mut self,
session: &mut SessionContext,
physical_plan: PhysicalPlan,
) -> QuillSQLResult<Vec<Tuple>> {
let needs_cleanup = !session.has_active_transaction();
let autocommit = session.autocommit();
let result = {
let txn = session.ensure_active_transaction(&self.transaction_manager)?;
let context = crate::execution::ExecutionContext::new(
&mut self.catalog,
txn,
self.transaction_manager.clone(),
self.storage_engine.clone(),
);
let mut engine = ExecutionEngine { context };
engine.execute(Arc::new(physical_plan))?
};
if autocommit && needs_cleanup {
if let Some(txn) = session.active_txn_mut() {
self.transaction_manager.commit(txn)?;
}
session.clear_active_transaction();
}
Ok(result)
}
}
impl Drop for Database {
fn drop(&mut self) {
self.background_workers.shutdown_all();
}
}
fn wal_config_for_path(db_path: &str, overrides: &WalOptions) -> WalConfig {
build_wal_config(wal_directory_from_path(db_path), overrides)
}
fn wal_directory_from_path(db_path: &str) -> PathBuf {
let mut base = PathBuf::from(db_path);
base.set_extension("wal");
if base.extension().is_none() {
PathBuf::from(format!("{}.wal", db_path))
} else {
base
}
}
fn wal_config_for_temp(temp_root: &Path, overrides: &WalOptions) -> WalConfig {
build_wal_config(temp_root.join("wal"), overrides)
}
fn build_wal_config(default_directory: PathBuf, overrides: &WalOptions) -> WalConfig {
let mut config = WalConfig {
directory: overrides.directory.clone().unwrap_or(default_directory),
..WalConfig::default()
};
if let Some(size) = overrides.segment_size {
config.segment_size = size;
}
if let Some(sync) = overrides.sync_on_flush {
config.sync_on_flush = sync;
}
if let Some(flag) = overrides.persist_control_file_on_flush {
config.persist_control_file_on_flush = flag;
}
if let Some(interval) = overrides.writer_interval_ms {
config.writer_interval_ms = interval;
}
if let Some(capacity) = overrides.buffer_capacity {
config.buffer_capacity = capacity;
}
if let Some(bytes) = overrides.flush_coalesce_bytes {
config.flush_coalesce_bytes = bytes;
}
if let Some(sync_commit) = overrides.synchronous_commit {
config.synchronous_commit = sync_commit;
}
if let Some(interval) = overrides.checkpoint_interval_ms {
config.checkpoint_interval_ms = interval;
}
if let Some(retain) = overrides.retain_segments {
config.retain_segments = retain.max(1);
}
config
}