glaredb_core 25.6.2

Core functionality for GlareDB
Documentation
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
pub mod builtin;
pub mod execute;
pub mod scan;

use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;

use execute::TableExecuteFunction;
use glaredb_error::{DbError, Result};
use scan::{ScanContext, TableScanFunction};

use super::Signature;
use crate::arrays::batch::Batch;
use crate::arrays::field::ColumnSchema;
use crate::execution::operators::{ExecutionProperties, PollExecute, PollFinalize, PollPull};
use crate::expr::Expression;
use crate::statistics::value::StatisticsValue;
use crate::storage::projections::Projections;
use crate::storage::scan_filter::PhysicalScanFilter;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableFunctionInput {
    pub positional: Vec<Expression>,
    pub named: HashMap<String, Expression>,
}

impl TableFunctionInput {
    pub fn all_unnamed<E>(exprs: impl IntoIterator<Item = E>) -> Self
    where
        E: Into<Expression>,
    {
        TableFunctionInput {
            positional: exprs.into_iter().map(|e| e.into()).collect(),
            named: HashMap::new(),
        }
    }
}

// TODO: Chunky (152)
//
// Should we just arc all of it?
#[derive(Debug, Clone)]
pub struct RawTableFunctionBindState {
    pub state: Arc<dyn Any + Sync + Send>,
    pub input: TableFunctionInput,
    pub data_schema: ColumnSchema,
    pub meta_schema: Option<ColumnSchema>,
    pub cardinality: StatisticsValue<usize>,
}

#[derive(Debug)]
pub struct TableFunctionBindState<S> {
    /// Any state needed for the function.
    pub state: S,
    /// Inputs the to function.
    pub input: TableFunctionInput,
    /// Output schema of the function. This should be the schema of the "file"
    /// or returned table.
    pub data_schema: ColumnSchema,
    /// Output schema of the metadata, if available.
    ///
    /// This should be the column schema for metadata columns, e.g. columns
    /// provided by a multi file scan.
    pub meta_schema: Option<ColumnSchema>,
    /// Output cardinality.
    pub cardinality: StatisticsValue<usize>,
}

#[derive(Debug, Clone)]
pub struct PlannedTableFunction {
    pub(crate) name: &'static str,
    pub(crate) raw: &'static RawTableFunction,
    pub(crate) bind_state: RawTableFunctionBindState,
}

/// Assumes that a function with same inputs and return type is using the same
/// function implementation.
impl PartialEq for PlannedTableFunction {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.bind_state.data_schema == other.bind_state.data_schema
            && self.bind_state.meta_schema == other.bind_state.meta_schema
            && self.bind_state.input == other.bind_state.input
    }
}

impl Eq for PlannedTableFunction {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableFunctionType {
    Scan,
    Execute,
}

#[derive(Debug, Clone)]
pub struct AnyTableOperatorState(Arc<dyn Any + Sync + Send>);

#[derive(Debug)]
pub struct AnyTablePartitionState(Box<dyn Any + Sync + Send>);

#[derive(Debug, Clone, Copy)]
pub struct RawTableFunction {
    function: *const (),
    signature: &'static Signature,
    vtable: &'static RawTableFunctionVTable,
    function_type: TableFunctionType,
}

unsafe impl Send for RawTableFunction {}
unsafe impl Sync for RawTableFunction {}

impl RawTableFunction {
    pub const fn new_execute<F>(sig: &'static Signature, function: &'static F) -> Self
    where
        F: TableExecuteFunction,
    {
        let function = (function as *const F).cast();
        RawTableFunction {
            function,
            signature: sig,
            vtable: TableExecuteVTable::<F>::VTABLE,
            function_type: TableExecuteVTable::<F>::FUNCTION_TYPE,
        }
    }

    pub const fn new_scan<F>(sig: &'static Signature, function: &'static F) -> Self
    where
        F: TableScanFunction,
    {
        let function = (function as *const F).cast();
        RawTableFunction {
            function,
            signature: sig,
            vtable: TableScanVTable::<F>::VTABLE,
            function_type: TableScanVTable::<F>::FUNCTION_TYPE,
        }
    }

    pub async fn call_scan_bind(
        &self,
        scan_context: ScanContext<'_>,
        input: TableFunctionInput,
    ) -> Result<RawTableFunctionBindState> {
        // SAFETY: The pointer we pass to the bind fn is the pointer we get from
        // the static reference we use to construct this object.
        let fut = unsafe { (self.vtable.scan_bind_fn)(self.function, scan_context, input)? };
        fut.await
    }

    pub fn call_execute_bind(
        &self,
        input: TableFunctionInput,
    ) -> Result<RawTableFunctionBindState> {
        unsafe { (self.vtable.execute_bind_fn)(self.function, input) }
    }

    pub fn call_create_pull_operator_state(
        &self,
        bind_state: &RawTableFunctionBindState,
        projections: Projections,
        filters: &[PhysicalScanFilter],
        props: ExecutionProperties,
    ) -> Result<AnyTableOperatorState> {
        unsafe {
            (self.vtable.create_pull_operator_state_fn)(
                bind_state.state.as_ref(),
                projections,
                filters,
                props,
            )
        }
    }

    pub fn call_create_pull_partition_states(
        &self,
        op_state: &AnyTableOperatorState,
        props: ExecutionProperties,
        partitions: usize,
    ) -> Result<Vec<AnyTablePartitionState>> {
        unsafe {
            (self.vtable.create_pull_partition_states_fn)(op_state.0.as_ref(), props, partitions)
        }
    }

    pub fn call_create_execute_operator_state(
        &self,
        bind_state: &RawTableFunctionBindState,
        props: ExecutionProperties,
    ) -> Result<AnyTableOperatorState> {
        unsafe { (self.vtable.create_execute_operator_state_fn)(bind_state.state.as_ref(), props) }
    }

    pub fn call_create_execute_partition_states(
        &self,
        op_state: &AnyTableOperatorState,
        props: ExecutionProperties,
        partitions: usize,
    ) -> Result<Vec<AnyTablePartitionState>> {
        unsafe {
            (self.vtable.create_execute_partition_states_fn)(op_state.0.as_ref(), props, partitions)
        }
    }

    pub fn call_poll_execute(
        &self,
        cx: &mut Context,
        op_state: &AnyTableOperatorState,
        partition_state: &mut AnyTablePartitionState,
        input: &mut Batch,
        output: &mut Batch,
    ) -> Result<PollExecute> {
        unsafe {
            (self.vtable.poll_execute_fn)(
                cx,
                op_state.0.as_ref(),
                partition_state.0.as_mut(),
                input,
                output,
            )
        }
    }

    pub fn call_poll_pull(
        &self,
        cx: &mut Context,
        op_state: &AnyTableOperatorState,
        partition_state: &mut AnyTablePartitionState,
        output: &mut Batch,
    ) -> Result<PollPull> {
        unsafe {
            (self.vtable.poll_pull_fn)(cx, op_state.0.as_ref(), partition_state.0.as_mut(), output)
        }
    }

    pub fn call_poll_finalize_execute(
        &self,
        cx: &mut Context,
        op_state: &AnyTableOperatorState,
        partition_state: &mut AnyTablePartitionState,
    ) -> Result<PollFinalize> {
        unsafe {
            (self.vtable.poll_finalize_execute_fn)(
                cx,
                op_state.0.as_ref(),
                partition_state.0.as_mut(),
            )
        }
    }

    pub fn function_type(&self) -> TableFunctionType {
        self.function_type
    }

    pub fn signature(&self) -> &Signature {
        self.signature
    }
}

type ScanBindFut<'a> = Pin<Box<dyn Future<Output = Result<RawTableFunctionBindState>> + Send + 'a>>;

#[derive(Debug, Clone, Copy)]
pub struct RawTableFunctionVTable {
    scan_bind_fn: unsafe fn(
        function: *const (),
        scan_context: ScanContext,
        input: TableFunctionInput,
    ) -> Result<ScanBindFut>,

    execute_bind_fn: unsafe fn(
        function: *const (),
        input: TableFunctionInput,
    ) -> Result<RawTableFunctionBindState>,

    create_pull_operator_state_fn: unsafe fn(
        bind_state: &dyn Any,
        projections: Projections,
        filters: &[PhysicalScanFilter],
        props: ExecutionProperties,
    ) -> Result<AnyTableOperatorState>,

    create_pull_partition_states_fn: unsafe fn(
        op_state: &dyn Any,
        props: ExecutionProperties,
        partitions: usize,
    ) -> Result<Vec<AnyTablePartitionState>>,

    create_execute_operator_state_fn: unsafe fn(
        bind_state: &dyn Any,
        props: ExecutionProperties,
    ) -> Result<AnyTableOperatorState>,

    create_execute_partition_states_fn: unsafe fn(
        op_state: &dyn Any,
        props: ExecutionProperties,
        partitions: usize,
    ) -> Result<Vec<AnyTablePartitionState>>,

    poll_execute_fn: unsafe fn(
        cx: &mut Context,
        op_state: &dyn Any,
        partition_state: &mut dyn Any,
        input: &mut Batch,
        output: &mut Batch,
    ) -> Result<PollExecute>,

    poll_finalize_execute_fn: unsafe fn(
        cx: &mut Context,
        op_state: &dyn Any,
        partition_state: &mut dyn Any,
    ) -> Result<PollFinalize>,

    poll_pull_fn: unsafe fn(
        cx: &mut Context,
        op_state: &dyn Any,
        partition_state: &mut dyn Any,
        output: &mut Batch,
    ) -> Result<PollPull>,
}

// TODO: Seal
pub trait TableFunctionVTable {
    const FUNCTION_TYPE: TableFunctionType;
    const VTABLE: &'static RawTableFunctionVTable;
}

struct TableExecuteVTable<F: TableExecuteFunction>(PhantomData<F>);

impl<F> TableFunctionVTable for TableExecuteVTable<F>
where
    F: TableExecuteFunction,
{
    const FUNCTION_TYPE: TableFunctionType = TableFunctionType::Execute;

    const VTABLE: &'static RawTableFunctionVTable = &RawTableFunctionVTable {
        scan_bind_fn: |_function, _db_context, _input| Err(DbError::new("Not a scan function")),
        execute_bind_fn: |function, input| {
            let function = unsafe { function.cast::<F>().as_ref().unwrap() };
            let state = function.bind(input)?;

            Ok(RawTableFunctionBindState {
                state: Arc::new(state.state),
                input: state.input,
                data_schema: state.data_schema,
                meta_schema: state.meta_schema,
                cardinality: state.cardinality,
            })
        },
        create_pull_operator_state_fn: |_bind_state, _projections, _filters, _props| {
            Err(DbError::new("Not a scan function"))
        },
        create_pull_partition_states_fn: |_bind_state, _props, _partitions| {
            Err(DbError::new("Not a scan function"))
        },
        create_execute_operator_state_fn: |bind_state, props| {
            let bind_state = bind_state
                .downcast_ref::<<F as TableExecuteFunction>::BindState>()
                .unwrap();
            let op_state = F::create_execute_operator_state(bind_state, props)?;
            Ok(AnyTableOperatorState(Arc::new(op_state)))
        },
        create_execute_partition_states_fn: |op_state, props, partitions| {
            let op_state = op_state
                .downcast_ref::<<F as TableExecuteFunction>::OperatorState>()
                .unwrap();
            let states = F::create_execute_partition_states(op_state, props, partitions)?;
            let states = states
                .into_iter()
                .map(|state| AnyTablePartitionState(Box::new(state)))
                .collect();

            Ok(states)
        },

        poll_execute_fn: |cx, op_state, partition_state, input, output| {
            let op_state = op_state
                .downcast_ref::<<F as TableExecuteFunction>::OperatorState>()
                .unwrap();
            let partition_state = partition_state
                .downcast_mut::<<F as TableExecuteFunction>::PartitionState>()
                .unwrap();
            F::poll_execute(cx, op_state, partition_state, input, output)
        },
        poll_finalize_execute_fn: |cx, op_state, partition_state| {
            let op_state = op_state
                .downcast_ref::<<F as TableExecuteFunction>::OperatorState>()
                .unwrap();
            let partition_state = partition_state
                .downcast_mut::<<F as TableExecuteFunction>::PartitionState>()
                .unwrap();
            F::poll_finalize_execute(cx, op_state, partition_state)
        },

        poll_pull_fn: |_cx, _op_state, _partition_state, _output| {
            Err(DbError::new("Not a scan functions"))
        },
    };
}

struct TableScanVTable<F: TableScanFunction>(PhantomData<F>);

impl<F> TableFunctionVTable for TableScanVTable<F>
where
    F: TableScanFunction,
{
    const FUNCTION_TYPE: TableFunctionType = TableFunctionType::Scan;

    const VTABLE: &'static RawTableFunctionVTable = &RawTableFunctionVTable {
        scan_bind_fn: |function, scan_context, input| {
            let function = unsafe { function.cast::<F>().as_ref().unwrap() };
            Ok(Box::pin(async move {
                let state = function.bind(scan_context, input).await?;

                Ok(RawTableFunctionBindState {
                    state: Arc::new(state.state),
                    input: state.input,
                    data_schema: state.data_schema,
                    meta_schema: state.meta_schema,
                    cardinality: state.cardinality,
                })
            }))
        },
        execute_bind_fn: |_function, _input| Err(DbError::new("Not an execute function")),
        create_pull_operator_state_fn: |bind_state, projections, filters, props| {
            let bind_state = bind_state
                .downcast_ref::<<F as TableScanFunction>::BindState>()
                .unwrap();
            let op_state = F::create_pull_operator_state(bind_state, projections, filters, props)?;
            Ok(AnyTableOperatorState(Arc::new(op_state)))
        },
        create_pull_partition_states_fn: |op_state, props, partitions| {
            let op_state = op_state
                .downcast_ref::<<F as TableScanFunction>::OperatorState>()
                .unwrap();
            let states = F::create_pull_partition_states(op_state, props, partitions)?;
            let states = states
                .into_iter()
                .map(|state| AnyTablePartitionState(Box::new(state)))
                .collect();

            Ok(states)
        },
        create_execute_operator_state_fn: |_bind_state, _props| {
            Err(DbError::new("Not an execute function"))
        },
        create_execute_partition_states_fn: |_op_state, _props, _partitions| {
            Err(DbError::new("Not an execute function"))
        },

        poll_execute_fn: |_cx, _op_state, _partition_state, _input, _output| {
            Err(DbError::new("Not an execute function"))
        },
        poll_finalize_execute_fn: |_cx, _op_state, _partition_state| {
            Err(DbError::new("Not an execute function"))
        },

        poll_pull_fn: |cx, op_state, partition_state, output| {
            let op_state = op_state
                .downcast_ref::<<F as TableScanFunction>::OperatorState>()
                .unwrap();
            let partition_state = partition_state
                .downcast_mut::<<F as TableScanFunction>::PartitionState>()
                .unwrap();
            F::poll_pull(cx, op_state, partition_state, output)
        },
    };
}