reifydb_engine/table_virtual/factory.rs
1// Copyright (c) reifydb.com 2025
2// This file is licensed under the AGPL-3.0-or-later, see license.md file
3
4use std::sync::Arc;
5
6use reifydb_core::interface::TableVirtualDef;
7
8use super::TableVirtual;
9
10/// Factory for creating virtual table instances.
11///
12/// Implementations must be thread-safe and create fresh instances on each call.
13/// The factory pattern allows virtual tables to be registered once and instantiated
14/// on-demand for each query execution.
15///
16/// # Example
17///
18/// ```ignore
19/// struct MyTableFactory {
20/// definition: Arc<TableVirtualDef>,
21/// }
22///
23/// impl VirtualTableFactory for MyTableFactory {
24/// fn create_boxed(&self) -> Box<dyn TableVirtual<'static> + Send + Sync> {
25/// Box::new(MyVirtualTable::new(self.definition.clone()))
26/// }
27///
28/// fn definition(&self) -> Arc<TableVirtualDef> {
29/// self.definition.clone()
30/// }
31/// }
32/// ```
33pub trait VirtualTableFactory: Send + Sync + 'static {
34 /// Create a new virtual table instance.
35 ///
36 /// Each call should return a fresh instance ready to process a new query.
37 /// The returned instance must implement `TableVirtual<'a>` for all lifetimes.
38 fn create_boxed(&self) -> Box<dyn TableVirtual<'static> + Send + Sync>;
39
40 /// Get the table definition (schema).
41 ///
42 /// Returns the metadata including column names, types, and constraints.
43 fn definition(&self) -> Arc<TableVirtualDef>;
44}
45
46/// Extends the lifetime of a boxed virtual table.
47///
48/// # Safety
49///
50/// This is safe because all virtual table implementations are required to be `'static`
51/// (they don't borrow any data). The `'a` lifetime in `TableVirtual<'a>` only constrains
52/// method arguments and return values, not the struct itself.
53#[inline]
54pub(crate) fn extend_virtual_table_lifetime<'a>(
55 vtable: Box<dyn TableVirtual<'static> + Send + Sync>,
56) -> Box<dyn TableVirtual<'a>> {
57 // SAFETY: The concrete type implementing TableVirtual is 'static,
58 // so it can safely be used with any lifetime 'a.
59 unsafe { std::mem::transmute(vtable) }
60}