pub struct Database {
pub durability: DurabilityLevel,
/* private fields */
}Expand description
DBX 데이터베이스 엔진
5-Tier Hybrid Storage 아키텍처를 관리하는 메인 API입니다.
§데이터 흐름
- INSERT: Delta Store (Tier 1)에 먼저 쓰기
- GET: Delta → WOS 순서로 조회 (첫 번째 hit에서 short-circuit)
- DELETE: 모든 계층에서 삭제
- flush(): Delta Store 데이터를 WOS로 이동
§예제
use dbx_core::Database;
let db = Database::open_in_memory()?;
db.insert("users", b"user:1", b"Alice")?;
let value = db.get("users", b"user:1")?;
assert_eq!(value, Some(b"Alice".to_vec()));Fields§
§durability: DurabilityLevelWAL 내구성 정책
Implementations§
Source§impl Database
impl Database
Sourcepub fn register_trigger(&self, hook: EventHook) -> DbxResult<()>
pub fn register_trigger(&self, hook: EventHook) -> DbxResult<()>
트리거 등록
§예제
use dbx_core::Database;
use dbx_core::automation::{EventHook, EventHookEventType, EventHookCondition, EventHookAction};
let db = Database::open_in_memory()?;
let hook = EventHook::new(
"audit_trigger",
EventHookEventType::AfterInsert,
"users",
EventHookCondition::Always,
EventHookAction::Custom(Box::new(|_ctx, _event| {
// 감사 로그 기록
Ok(())
})),
);
db.register_trigger(hook)?;Sourcepub fn unregister_trigger(&self, name: &str) -> DbxResult<()>
pub fn unregister_trigger(&self, name: &str) -> DbxResult<()>
트리거 등록 해제
Sourcepub fn fire_trigger(&self, event: EventHookEvent) -> DbxResult<Vec<String>>
pub fn fire_trigger(&self, event: EventHookEvent) -> DbxResult<Vec<String>>
트리거 발생
이벤트를 발생시켜 매칭되는 트리거들을 실행합니다.
Sourcepub fn fire_trigger_with_ctx(
&self,
ctx: &ExecutionContext,
event: EventHookEvent,
) -> DbxResult<Vec<String>>
pub fn fire_trigger_with_ctx( &self, ctx: &ExecutionContext, event: EventHookEvent, ) -> DbxResult<Vec<String>>
트리거 발생 (컨텍스트 지정)
Sourcepub fn list_triggers(&self) -> DbxResult<Vec<String>>
pub fn list_triggers(&self) -> DbxResult<Vec<String>>
등록된 트리거 목록
Sourcepub fn create_scheduler(&self) -> Scheduler
pub fn create_scheduler(&self) -> Scheduler
스케줄러 생성
Sourcepub fn register_scheduled_job(
&self,
scheduler: &Scheduler,
job: ScheduledJob,
) -> DbxResult<()>
pub fn register_scheduled_job( &self, scheduler: &Scheduler, job: ScheduledJob, ) -> DbxResult<()>
스케줄 작업 등록
Source§impl Database
impl Database
Sourcepub fn open_encrypted(
path: &Path,
encryption: EncryptionConfig,
) -> DbxResult<Self>
pub fn open_encrypted( path: &Path, encryption: EncryptionConfig, ) -> DbxResult<Self>
암호화된 데이터베이스를 열거나 생성합니다.
지정된 경로에 암호화된 데이터베이스를 생성하거나 기존 암호화 DB를 엽니다. WAL과 WOS 모두 암호화됩니다.
§인자
path- 데이터베이스 디렉토리 경로encryption- 암호화 설정 (패스워드 또는 raw key 기반)
§예제
use dbx_core::Database;
use dbx_core::storage::encryption::EncryptionConfig;
use std::path::Path;
let enc = EncryptionConfig::from_password("my-secret-password");
let db = Database::open_encrypted(Path::new("./data"), enc).unwrap();Sourcepub fn open_in_memory() -> DbxResult<Self>
pub fn open_in_memory() -> DbxResult<Self>
인메모리 데이터베이스를 생성합니다.
테스트 및 임시 데이터 저장용으로 사용됩니다. 영구 저장되지 않습니다.
§예제
use dbx_core::Database;
let db = Database::open_in_memory()?;
db.insert("cache", b"key1", b"value1")?;Sourcepub fn open_in_memory_encrypted(encryption: EncryptionConfig) -> DbxResult<Self>
pub fn open_in_memory_encrypted(encryption: EncryptionConfig) -> DbxResult<Self>
암호화된 인메모리 데이터베이스를 생성합니다.
테스트 및 임시 데이터 저장용으로, 메모리 상에서 value가 암호화됩니다.
§예제
use dbx_core::Database;
use dbx_core::storage::encryption::EncryptionConfig;
let enc = EncryptionConfig::from_password("secret");
let db = Database::open_in_memory_encrypted(enc)?;
db.insert("users", b"user:1", b"Alice")?;
let val = db.get("users", b"user:1")?;
assert_eq!(val, Some(b"Alice".to_vec()));Sourcepub fn open_safe(path: impl AsRef<Path>) -> DbxResult<Arc<Self>>
pub fn open_safe(path: impl AsRef<Path>) -> DbxResult<Arc<Self>>
최대 안전성 설정으로 데이터베이스를 엽니다 (Full durability).
금융, 의료 등 데이터 손실이 절대 허용되지 않는 경우 사용합니다. 모든 쓰기 작업마다 fsync를 수행하여 최대 안전성을 보장하지만, 성능은 기본 설정(Lazy)보다 느립니다.
§인자
path- 데이터베이스 파일 경로
Sourcepub fn open_fast(path: impl AsRef<Path>) -> DbxResult<Arc<Self>>
pub fn open_fast(path: impl AsRef<Path>) -> DbxResult<Arc<Self>>
최고 성능 설정으로 데이터베이스를 엽니다 (No durability).
WAL을 사용하지 않아 최고 성능을 제공하지만, 크래시 시 데이터 손실 가능성이 있습니다. 캐시, 임시 데이터, 벤치마크 등에 적합합니다.
§인자
path- 데이터베이스 파일 경로
Sourcepub fn open_with_durability(
path: impl AsRef<Path>,
durability: DurabilityLevel,
) -> DbxResult<Arc<Self>>
pub fn open_with_durability( path: impl AsRef<Path>, durability: DurabilityLevel, ) -> DbxResult<Arc<Self>>
Source§impl Database
impl Database
Sourcepub fn insert(&self, table: &str, key: &[u8], value: &[u8]) -> DbxResult<()>
pub fn insert(&self, table: &str, key: &[u8], value: &[u8]) -> DbxResult<()>
키-값 쌍을 삽입합니다.
데이터는 먼저 Delta Store (Tier 1)에 쓰여집니다. Flush 임계값을 초과하면 자동으로 WOS로 이동합니다.
§인자
table- 테이블 이름key- 키 (바이트 배열)value- 값 (바이트 배열)
Sourcepub fn insert_batch(
&self,
table: &str,
rows: Vec<(Vec<u8>, Vec<u8>)>,
) -> DbxResult<()>
pub fn insert_batch( &self, table: &str, rows: Vec<(Vec<u8>, Vec<u8>)>, ) -> DbxResult<()>
여러 키-값 쌍을 일괄 삽입합니다 (최적화됨).
Sourcepub fn insert_versioned(
&self,
table: &str,
key: &[u8],
value: Option<&[u8]>,
commit_ts: u64,
) -> DbxResult<()>
pub fn insert_versioned( &self, table: &str, key: &[u8], value: Option<&[u8]>, commit_ts: u64, ) -> DbxResult<()>
Insert a versioned key-value pair for MVCC.
Sourcepub fn get_snapshot(
&self,
table: &str,
key: &[u8],
read_ts: u64,
) -> DbxResult<Option<Option<Vec<u8>>>>
pub fn get_snapshot( &self, table: &str, key: &[u8], read_ts: u64, ) -> DbxResult<Option<Option<Vec<u8>>>>
Read a specific version of a key (Snapshot Read).
Sourcepub fn current_timestamp(&self) -> u64
pub fn current_timestamp(&self) -> u64
Get the current timestamp from the transaction manager.
Sourcepub fn allocate_commit_ts(&self) -> u64
pub fn allocate_commit_ts(&self) -> u64
Allocate a new commit timestamp for a transaction. This increments the timestamp oracle and returns a unique timestamp.
Sourcepub fn get(&self, table: &str, key: &[u8]) -> DbxResult<Option<Vec<u8>>>
pub fn get(&self, table: &str, key: &[u8]) -> DbxResult<Option<Vec<u8>>>
키로 값을 조회합니다.
성능 최적화: MVCC feature가 비활성화되면 Fast-path만 사용하여 최대 성능을 달성합니다.
Sourcepub fn range(
&self,
table: &str,
start_key: &[u8],
end_key: &[u8],
) -> DbxResult<Vec<(Vec<u8>, Vec<u8>)>>
pub fn range( &self, table: &str, start_key: &[u8], end_key: &[u8], ) -> DbxResult<Vec<(Vec<u8>, Vec<u8>)>>
테이블의 키 범위를 스캔합니다.
Sourcepub fn table_row_count(&self, table: &str) -> DbxResult<usize>
pub fn table_row_count(&self, table: &str) -> DbxResult<usize>
테이블의 행 개수를 반환합니다.
Sourcepub fn sync_columnar_cache(&self, table: &str) -> DbxResult<usize>
pub fn sync_columnar_cache(&self, table: &str) -> DbxResult<usize>
Synchronize the Columnar Cache with the latest data from Delta Store.
If the table has a schema in table_schemas, it will be synced as typed data. Otherwise, it will be synced as raw Binary data.
Sourcepub fn sync_gpu_cache_multi_tier(&self, table: &str) -> DbxResult<()>
pub fn sync_gpu_cache_multi_tier(&self, table: &str) -> DbxResult<()>
Sync data from multiple tiers (Delta and ROS) to GPU for merge operations.
Sourcepub fn sync_gpu_cache(&self, table: &str) -> DbxResult<()>
pub fn sync_gpu_cache(&self, table: &str) -> DbxResult<()>
Legacy method to sync data from Columnar Cache to GPU.
Sourcepub fn gpu_exec_with_fallback<T, F, C>(
&self,
gpu_op: F,
cpu_op: C,
) -> DbxResult<T>
pub fn gpu_exec_with_fallback<T, F, C>( &self, gpu_op: F, cpu_op: C, ) -> DbxResult<T>
Execute an operation on GPU with automatic fallback to CPU on any error.
Source§impl Database
impl Database
Sourcepub fn create_table(&self, name: &str, schema: Schema) -> DbxResult<()>
pub fn create_table(&self, name: &str, schema: Schema) -> DbxResult<()>
Create a new table with the given Arrow schema
This is a convenience wrapper around execute_sql("CREATE TABLE ...").
It automatically converts the Arrow schema to SQL DDL.
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("name", DataType::Utf8, true),
Field::new("age", DataType::Int32, true),
]);
db.create_table("users", schema)?;
assert!(db.table_exists("users"));Sourcepub fn drop_table(&self, name: &str) -> DbxResult<()>
pub fn drop_table(&self, name: &str) -> DbxResult<()>
Drop a table
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
]);
db.create_table("temp", schema)?;
db.drop_table("temp")?;
assert!(!db.table_exists("temp"));Sourcepub fn table_exists(&self, name: &str) -> bool
pub fn table_exists(&self, name: &str) -> bool
Check if a table exists
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
assert!(!db.table_exists("users"));
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
]);
db.create_table("users", schema)?;
assert!(db.table_exists("users"));Sourcepub fn get_table_schema(&self, name: &str) -> DbxResult<Schema>
pub fn get_table_schema(&self, name: &str) -> DbxResult<Schema>
Get the schema of a table
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("name", DataType::Utf8, true),
]);
db.create_table("users", schema.clone())?;
let retrieved_schema = db.get_table_schema("users")?;
assert_eq!(retrieved_schema.fields().len(), 2);Sourcepub fn list_tables(&self) -> Vec<String>
pub fn list_tables(&self) -> Vec<String>
List all tables
Sourcepub fn create_sql_index(
&self,
table: &str,
index_name: &str,
columns: Vec<String>,
) -> DbxResult<()>
pub fn create_sql_index( &self, table: &str, index_name: &str, columns: Vec<String>, ) -> DbxResult<()>
Create a SQL index on table columns
This is a convenience wrapper around execute_sql("CREATE INDEX ...").
For Hash Index (O(1) lookup), use create_index(table, column) instead.
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("email", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
assert!(db.sql_index_exists("idx_email"));Sourcepub fn drop_sql_index(&self, table: &str, index_name: &str) -> DbxResult<()>
pub fn drop_sql_index(&self, table: &str, index_name: &str) -> DbxResult<()>
Drop a SQL index
This is a convenience wrapper around execute_sql("DROP INDEX ...").
For Hash Index, use drop_index(table, column) instead.
Note: The index must have been created with create_sql_index to be tracked properly.
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("email", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
db.drop_sql_index("users", "idx_email")?;
assert!(!db.sql_index_exists("idx_email"));Sourcepub fn sql_index_exists(&self, index_name: &str) -> bool
pub fn sql_index_exists(&self, index_name: &str) -> bool
Check if a SQL index exists
For Hash Index, use has_index(table, column) instead.
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("email", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
assert!(!db.sql_index_exists("idx_email"));
db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
assert!(db.sql_index_exists("idx_email"));Sourcepub fn list_sql_indexes(&self, table: &str) -> Vec<String>
pub fn list_sql_indexes(&self, table: &str) -> Vec<String>
List all SQL indexes for a table
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("email", DataType::Utf8, true),
Field::new("name", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
db.create_sql_index("users", "idx_name", vec!["name".to_string()])?;
let indexes = db.list_sql_indexes("users");
assert!(indexes.contains(&"idx_email".to_string()));
assert!(indexes.contains(&"idx_name".to_string()));Sourcepub fn add_column(
&self,
table: &str,
column_name: &str,
data_type: &str,
) -> DbxResult<()>
pub fn add_column( &self, table: &str, column_name: &str, data_type: &str, ) -> DbxResult<()>
Add a column to an existing table
This is a convenience wrapper around execute_sql("ALTER TABLE ... ADD COLUMN ...").
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("name", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
db.add_column("users", "email", "TEXT")?;
let updated_schema = db.get_table_schema("users")?;
assert_eq!(updated_schema.fields().len(), 3);Sourcepub fn drop_column(&self, table: &str, column_name: &str) -> DbxResult<()>
pub fn drop_column(&self, table: &str, column_name: &str) -> DbxResult<()>
Drop a column from an existing table
This is a convenience wrapper around execute_sql("ALTER TABLE ... DROP COLUMN ...").
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("name", DataType::Utf8, true),
Field::new("email", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
db.drop_column("users", "email")?;
let updated_schema = db.get_table_schema("users")?;
assert_eq!(updated_schema.fields().len(), 2);Sourcepub fn rename_column(
&self,
table: &str,
old_name: &str,
new_name: &str,
) -> DbxResult<()>
pub fn rename_column( &self, table: &str, old_name: &str, new_name: &str, ) -> DbxResult<()>
Rename a column in an existing table
This is a convenience wrapper around execute_sql("ALTER TABLE ... RENAME COLUMN ...").
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("user_name", DataType::Utf8, true),
]);
db.create_table("users", schema)?;
db.rename_column("users", "user_name", "name")?;
let updated_schema = db.get_table_schema("users")?;
assert_eq!(updated_schema.field(1).name(), "name");Source§impl Database
impl Database
Source§impl Database
impl Database
Sourcepub fn query_builder(&self) -> QueryBuilder<'_>
pub fn query_builder(&self) -> QueryBuilder<'_>
Create a new QueryBuilder for building SQL queries
This method returns a QueryBuilder that allows you to construct SQL queries using a fluent API without writing raw SQL strings.
§Example
use dbx_core::Database;
use arrow::datatypes::{DataType, Field, Schema};
let db = Database::open_in_memory()?;
// Create a table first
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("name", DataType::Utf8, true),
Field::new("age", DataType::Int32, true),
]);
db.create_table("users", schema)?;
// Query using the builder
let results = db.query_builder()
.select(&["id", "name"])
.from("users")
.where_("age", ">", "18")
.order_by("name", "ASC")
.limit(10)
.execute()?;Source§impl Database
impl Database
Sourcepub fn create_table_with_builder<F>(
&self,
name: &str,
builder_fn: F,
) -> DbxResult<()>
pub fn create_table_with_builder<F>( &self, name: &str, builder_fn: F, ) -> DbxResult<()>
Create a table using SchemaBuilder
This method provides a convenient way to create tables using the fluent SchemaBuilder API without manually constructing Arrow schemas.
§Example
use dbx_core::Database;
let db = Database::open_in_memory()?;
db.create_table_with_builder("users", |builder| {
builder
.id("id")
.text("name")
.text("email")
.int32("age").nullable()
})?;
assert!(db.table_exists("users"));Source§impl Database
impl Database
Sourcepub fn register_scalar_udf<F>(
&self,
name: impl Into<String>,
signature: Signature,
func: F,
) -> DbxResult<()>
pub fn register_scalar_udf<F>( &self, name: impl Into<String>, signature: Signature, func: F, ) -> DbxResult<()>
Scalar UDF 등록
§예제
use dbx_core::Database;
use dbx_core::automation::callable::{DataType, Signature, Value};
let db = Database::open_in_memory()?;
// UDF: x * 2
db.register_scalar_udf(
"double",
Signature {
params: vec![DataType::Int],
return_type: DataType::Int,
is_variadic: false,
},
|args| {
let x = args[0].as_i64()?;
Ok(Value::Int(x * 2))
},
)?;
// UDF 호출
let result = db.call_udf("double", &[Value::Int(21)])?;
assert_eq!(result.as_i64()?, 42);Sourcepub fn call_udf(&self, name: &str, args: &[Value]) -> DbxResult<Value>
pub fn call_udf(&self, name: &str, args: &[Value]) -> DbxResult<Value>
UDF 호출
§예제
use dbx_core::Database;
use dbx_core::automation::callable::{DataType, Signature, Value};
let db = Database::open_in_memory()?;
db.register_scalar_udf(
"add",
Signature {
params: vec![DataType::Int, DataType::Int],
return_type: DataType::Int,
is_variadic: false,
},
|args| {
let x = args[0].as_i64()?;
let y = args[1].as_i64()?;
Ok(Value::Int(x + y))
},
)?;
let result = db.call_udf("add", &[Value::Int(10), Value::Int(32)])?;
assert_eq!(result.as_i64()?, 42);Source§impl Database
impl Database
Sourcepub fn is_encrypted(&self) -> bool
pub fn is_encrypted(&self) -> bool
데이터베이스가 암호화되어 있는지 확인합니다.
Sourcepub fn rotate_key(&self, new_encryption: EncryptionConfig) -> DbxResult<usize>
pub fn rotate_key(&self, new_encryption: EncryptionConfig) -> DbxResult<usize>
암호화 키를 교체합니다 (키 로테이션).
모든 저장 계층 (WOS, WAL)의 데이터를 현재 키로 복호화한 뒤 새 키로 재암호화합니다. Delta Store의 데이터는 먼저 WOS로 flush된 후 재암호화됩니다.
§전제 조건
- 데이터베이스가 암호화되어 있어야 합니다 (
is_encrypted() == true). - 키 교체 중 다른 쓰기가 발생하지 않아야 합니다.
§반환값
재암호화된 레코드 수 (WOS + WAL).
§예제
use dbx_core::Database;
use dbx_core::storage::encryption::EncryptionConfig;
use std::path::Path;
let enc = EncryptionConfig::from_password("old-password");
let db = Database::open_encrypted(Path::new("./data"), enc).unwrap();
let new_enc = EncryptionConfig::from_password("new-password");
let count = db.rotate_key(new_enc).unwrap();
println!("Re-encrypted {} records", count);Sourcepub fn gpu_manager(&self) -> Option<&GpuManager>
pub fn gpu_manager(&self) -> Option<&GpuManager>
GPU Manager에 대한 참조를 반환합니다 (있는 경우).
Sourcepub fn count(&self, table: &str) -> DbxResult<usize>
pub fn count(&self, table: &str) -> DbxResult<usize>
Get the total entry count (Delta + WOS) for a table.
Sourcepub fn table_names(&self) -> DbxResult<Vec<String>>
pub fn table_names(&self) -> DbxResult<Vec<String>>
Get all table names across all tiers.
Sourcepub fn delta_entry_count(&self) -> usize
pub fn delta_entry_count(&self) -> usize
Get the Delta Store entry count (diagnostic).
Sourcepub fn gc(&self) -> DbxResult<usize>
pub fn gc(&self) -> DbxResult<usize>
Run garbage collection to clean up old MVCC versions.
This removes versions that are no longer visible to any active transaction. Returns the number of versions deleted.
§Example
let db = Database::open_in_memory()?;
// Run GC
let deleted = db.gc()?;
println!("Deleted {} old versions", deleted);Sourcepub fn gc_estimate(&self) -> DbxResult<usize>
pub fn gc_estimate(&self) -> DbxResult<usize>
Estimate the number of versions that would be deleted by GC.
Sourcepub fn active_transaction_count(&self) -> usize
pub fn active_transaction_count(&self) -> usize
Get the number of active transactions.
Source§impl Database
impl Database
Sourcepub fn query_one<T: FromRow>(&self, sql: impl Into<String>) -> QueryOne<'_, T>
pub fn query_one<T: FromRow>(&self, sql: impl Into<String>) -> QueryOne<'_, T>
SELECT 쿼리 — 단일 행 반환 (없으면 에러)
Sourcepub fn query_optional<T: FromRow>(
&self,
sql: impl Into<String>,
) -> QueryOptional<'_, T>
pub fn query_optional<T: FromRow>( &self, sql: impl Into<String>, ) -> QueryOptional<'_, T>
SELECT 쿼리 — 단일 행 반환 (없으면 None)
Sourcepub fn query_scalar<T: FromScalar>(
&self,
sql: impl Into<String>,
) -> QueryScalar<'_, T>
pub fn query_scalar<T: FromScalar>( &self, sql: impl Into<String>, ) -> QueryScalar<'_, T>
SELECT 쿼리 — 단일 스칼라 값 반환
Source§impl Database
impl Database
Sourcepub fn register_table(&self, name: &str, batches: Vec<RecordBatch>)
pub fn register_table(&self, name: &str, batches: Vec<RecordBatch>)
Register table data for SQL queries.
Tables registered here can be queried via execute_sql().
Sourcepub fn append_batch(&self, table: &str, batch: RecordBatch)
pub fn append_batch(&self, table: &str, batch: RecordBatch)
Append a RecordBatch to an existing registered table.
Sourcepub fn execute_sql(&self, sql: &str) -> DbxResult<Vec<RecordBatch>>
pub fn execute_sql(&self, sql: &str) -> DbxResult<Vec<RecordBatch>>
Execute a SQL query and return RecordBatch results.
Full pipeline: Parse → LogicalPlan → Optimize → PhysicalPlan → Execute
§Example
let db = Database::open_in_memory()?;
// Register table data first, then:
// let batches = db.execute_sql("SELECT * FROM users WHERE age > 18")?;Source§impl Database
impl Database
Sourcepub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> DbxResult<()>
pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> DbxResult<()>
Save in-memory database to file
Only works for in-memory databases. Returns error for file-based DBs.
§Example
use dbx_core::Database;
let db = Database::open_in_memory()?;
db.execute_sql("CREATE TABLE users (id INT, name TEXT)")?;
db.execute_sql("INSERT INTO users VALUES (1, 'Alice')")?;
// Save to file
db.save_to_file("backup.json")?;Sourcepub fn load_from_file<P: AsRef<Path>>(path: P) -> DbxResult<Self>
pub fn load_from_file<P: AsRef<Path>>(path: P) -> DbxResult<Self>
Load database from file into in-memory database
Creates a new in-memory DB and loads all data from file.
§Example
use dbx_core::Database;
// Load from file
let db = Database::load_from_file("backup.json")?;
// Query data
let results = db.execute_sql("SELECT * FROM users")?;Trait Implementations§
Source§impl DatabaseCore for Database
impl DatabaseCore for Database
Source§impl DatabaseSnapshot for Database
impl DatabaseSnapshot for Database
Source§impl DatabaseSql for Database
impl DatabaseSql for Database
Source§fn execute_sql(&self, sql: &str) -> DbxResult<Vec<RecordBatch>>
fn execute_sql(&self, sql: &str) -> DbxResult<Vec<RecordBatch>>
Source§fn register_table(&self, name: &str, batches: Vec<RecordBatch>)
fn register_table(&self, name: &str, batches: Vec<RecordBatch>)
Source§fn append_batch(&self, table: &str, batch: RecordBatch) -> DbxResult<()>
fn append_batch(&self, table: &str, batch: RecordBatch) -> DbxResult<()>
Source§impl DatabaseTransaction for Database
impl DatabaseTransaction for Database
impl DatabaseQuery for Database
Auto Trait Implementations§
impl !Freeze for Database
impl !RefUnwindSafe for Database
impl Send for Database
impl Sync for Database
impl Unpin for Database
impl UnsafeUnpin for Database
impl !UnwindSafe for Database
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more