datafusion-server 0.21.0

Web server library for session-based queries using Arrow and other large datasets as data sources.
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// database/table_provider.ra: Table provider for external databases
// Sasaki, Naoki <nsasaki@sal.co.jp> July 27, 2024
//

use std::collections::HashMap;
use std::fmt::{Debug, Write};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::data_source::database::any_pool::DatabaseOperator;
#[cfg(feature = "mysql")]
use crate::data_source::database::dtype_mysql;
#[cfg(feature = "postgres")]
use crate::data_source::database::dtype_postgres;
use crate::data_source::database::{
    any_pool::{AnyDatabasePool, AnyDatabaseRow},
    engine_type::DatabaseEngineType,
};
use async_trait::async_trait; // TODO: Replace in the future when the Rust compiler's async trait supports object safety.
use chrono::{Datelike, Timelike};
#[cfg(feature = "mysql")]
use datafusion::arrow::array::{UInt16Builder, UInt32Builder, UInt64Builder, UInt8Builder};
use datafusion::{
    arrow::{
        array::{
            ArrayBuilder, ArrayRef, BinaryBuilder, BooleanBuilder, Date32Builder,
            Decimal128Builder, Float32Builder, Float64Builder, Int16Builder, Int32Builder,
            Int64Builder, Int8Builder, StringBuilder, Time64MicrosecondBuilder,
            TimestampMicrosecondBuilder,
        },
        datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit},
        record_batch::RecordBatch,
    },
    catalog::Session,
    datasource::{memory::MemTable, TableProvider, TableType},
    error::DataFusionError,
    execution::context::SessionContext,
    logical_expr::Expr,
    physical_plan::ExecutionPlan,
};
use futures::StreamExt;
use num_traits::ToPrimitive;

const BATCH_SIZE: usize = 1000;

#[derive(Debug)]
pub struct DatabaseTable {
    pool: AnyDatabasePool,
    schema: SchemaRef,
    table_name: String,
}

#[async_trait]
impl TableProvider for DatabaseTable {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    fn table_type(&self) -> TableType {
        TableType::Base
    }

    fn scan<'life0, 'life1, 'life2, 'life3, 'async_trait>(
        &'life0 self,
        _state: &'life1 (dyn Session + 'life1),
        projection: Option<&'life2 Vec<usize>>,
        filters: &'life3 [Expr],
        limit: Option<usize>,
    ) -> Pin<
        Box<
            dyn Future<Output = Result<Arc<dyn ExecutionPlan>, DataFusionError>>
                + Send
                + 'async_trait,
        >,
    >
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,
        'life2: 'async_trait,
        'life3: 'async_trait,
    {
        let table_name = self.table_name.clone();
        let pool = self.pool.clone();
        let schema = self.schema.clone();
        let projection = projection.cloned();
        let filters = filters.to_vec();

        Box::pin(async move {
            let mut sql = format!("SELECT * FROM {table_name}");

            if !filters.is_empty() {
                let filter_clauses: Vec<String> = filters.iter().map(Expr::to_string).collect();
                if !filter_clauses.is_empty() {
                    write!(&mut sql, " WHERE {}", filter_clauses.join(" AND "))?;
                }
            }

            let projected_fields = if let Some(projection) = projection {
                let columns: Vec<String> = projection
                    .iter()
                    .map(|index| schema.field(*index).name().clone())
                    .collect();
                sql = sql.replace('*', &columns.join(", "));
                columns
            } else {
                schema.fields().iter().map(|f| f.name().clone()).collect()
            };

            let projected_schema = Arc::new(Schema::new(
                projected_fields
                    .iter()
                    .map(|name| schema.field_with_name(name).unwrap().clone())
                    .collect::<Vec<_>>(),
            ));

            if let Some(limit) = limit {
                write!(&mut sql, " LIMIT {limit}")?;
            }

            // retrieve from external database system
            let mut stream = pool.fetch(&sql);
            let mut builders = Self::create_column_builders(&projected_schema)?;
            let mut row_count = 0;
            let mut record_batches = vec![];

            while let Some(row) = stream.next().await {
                let row = row.map_err(|e| DataFusionError::Execution(e.to_string()))?;
                row_count += 1;

                for (index, name) in projected_fields.iter().enumerate() {
                    Self::append_value_to_builder(
                        &mut builders[index],
                        schema.field_with_name(name)?,
                        schema.metadata.get(name).unwrap_or(&String::new()),
                        &row,
                    )?;
                }

                if row_count == BATCH_SIZE {
                    let arrays: Vec<ArrayRef> = builders
                        .into_iter()
                        .map(|mut builder| builder.finish())
                        .collect();

                    record_batches.push(RecordBatch::try_new(projected_schema.clone(), arrays)?);

                    builders = Self::create_column_builders(&projected_schema)?;
                    row_count = 0;
                }
            }

            if row_count > 0 {
                let arrays: Vec<ArrayRef> = builders
                    .into_iter()
                    .map(|mut builder| builder.finish())
                    .collect();

                record_batches.push(RecordBatch::try_new(projected_schema.clone(), arrays)?);
            }

            let memory_table = Arc::new(MemTable::try_new(
                projected_schema.clone(),
                vec![record_batches.clone()],
            )?);

            let ctx = SessionContext::new();
            ctx.register_table("table", memory_table)?;
            let dataframe = ctx.table("table").await?;

            dataframe.create_physical_plan().await
        })
    }
}

macro_rules! append_value {
    ($builder:expr, $field:expr, $row:expr, $type:ty, $builder_type:ty) => {{
        let builder = $builder.as_any_mut().downcast_mut::<$builder_type>();
        match builder {
            Some(builder) => {
                if let Some(value) = $row.get::<$type>($field.name()) {
                    builder.append_value(value);
                } else {
                    builder.append_null();
                }
                Ok(())
            }
            None => Err(DataFusionError::Internal(format!(
                "Failed to downcast builder for field '{}'",
                $field.name()
            ))),
        }
    }};
}

#[cfg(feature = "mysql")]
macro_rules! append_mysql_specific_value {
    ($builder:expr, $field:expr, $row:expr, $type:ty, $builder_type:ty) => {{
        let builder = $builder.as_any_mut().downcast_mut::<$builder_type>();
        match builder {
            Some(builder) => {
                if let Some(value) = $row.get_mysql::<$type>($field.name()) {
                    builder.append_value(value);
                } else {
                    builder.append_null();
                }
                Ok(())
            }
            None => Err(DataFusionError::Internal(format!(
                "Failed to downcast builder for field '{}'",
                $field.name()
            ))),
        }
    }};
}

impl DatabaseTable {
    pub async fn new(
        engine_type: &DatabaseEngineType,
        pool: AnyDatabasePool,
        database: &str,
        table_name: &str,
    ) -> Result<Self, DataFusionError> {
        log::debug!("Inspecting external database schema: database={database}, table={table_name}");

        let sql = match engine_type {
            #[cfg(feature = "postgres")]
            DatabaseEngineType::Postgres => format!(
                "SELECT column_name, data_type, numeric_precision, numeric_scale \
                FROM information_schema.columns \
                WHERE table_name='{table_name}'",
            ),
            #[cfg(feature = "mysql")]
            DatabaseEngineType::MySQL => format!(
                "SELECT column_name, data_type, column_type, numeric_precision, numeric_scale \
                FROM information_schema.columns \
                WHERE table_schema='{database}' AND table_name='{table_name}'",
            ),
        };

        log::debug!("Retrieving schema: {sql}");

        let rows = pool
            .fetch_all(&sql)
            .await
            .map_err(|e| DataFusionError::Execution(e.to_string()))?;

        log::debug!("Result schema information records: {}", rows.len());

        #[allow(clippy::type_complexity)]
        let columns: Vec<(String, String, Option<i16>, Option<i8>, bool)> = rows
            .iter()
            .map(|row| {
                (
                    row.get::<String>("column_name").unwrap_or_default(),
                    row.get::<String>("data_type").unwrap_or_default(),
                    row.get::<i16>("numeric_precision"),
                    row.get::<i8>("numeric_scale"),
                    match engine_type {
                        #[cfg(feature = "postgres")]
                        DatabaseEngineType::Postgres => true,
                        #[cfg(feature = "mysql")]
                        DatabaseEngineType::MySQL => !row
                            .get::<String>("column_type")
                            .unwrap_or_default()
                            .ends_with("unsigned"),
                    },
                )
            })
            .collect();

        // stores original dtype name
        let meta_info: HashMap<String, String> = columns
            .clone()
            .into_iter()
            .map(|(column_name, dtype, ..)| (column_name, dtype))
            .collect();

        let fields: Vec<Field> = columns
            .into_iter()
            .map(|(column_name, dtype, precision, scale, signed)| {
                let arrow_dtype = match engine_type {
                    #[cfg(feature = "postgres")]
                    DatabaseEngineType::Postgres => {
                        dtype_postgres::to_arrow_dtype(&dtype, precision, scale, signed)
                    }
                    #[cfg(feature = "mysql")]
                    DatabaseEngineType::MySQL => {
                        dtype_mysql::to_arrow_dtype(&dtype, precision, scale, signed)
                    }
                };
                Field::new(&column_name, arrow_dtype, true)
            })
            .collect();

        let schema = Arc::new(Schema::new_with_metadata(fields, meta_info));

        log::debug!("Established schema: {schema:?}");

        Ok(DatabaseTable {
            pool,
            schema,
            table_name: table_name.to_string(),
        })
    }

    fn create_column_builders(
        projected_schema: &Schema,
    ) -> Result<Vec<Box<dyn ArrayBuilder>>, DataFusionError> {
        let mut builders = vec![];

        for field in projected_schema.fields() {
            builders.push(match field.data_type() {
                DataType::Boolean => {
                    Box::new(BooleanBuilder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Int8 => {
                    Box::new(Int8Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Int16 => {
                    Box::new(Int16Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Int32 => {
                    Box::new(Int32Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Int64 => {
                    Box::new(Int64Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                #[cfg(feature = "mysql")]
                DataType::UInt8 => {
                    Box::new(UInt8Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                #[cfg(feature = "mysql")]
                DataType::UInt16 => {
                    Box::new(UInt16Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                #[cfg(feature = "mysql")]
                DataType::UInt32 => {
                    Box::new(UInt32Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                #[cfg(feature = "mysql")]
                DataType::UInt64 => {
                    Box::new(UInt64Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Float32 => {
                    Box::new(Float32Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Float64 => {
                    Box::new(Float64Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Decimal128(precision, scale) => Box::new(
                    Decimal128Builder::with_capacity(BATCH_SIZE)
                        .with_precision_and_scale(*precision, *scale)?,
                )
                    as Box<dyn ArrayBuilder>,
                DataType::Utf8 => {
                    Box::new(StringBuilder::with_capacity(BATCH_SIZE, BATCH_SIZE * 50))
                        as Box<dyn ArrayBuilder>
                }
                DataType::Binary => {
                    Box::new(BinaryBuilder::with_capacity(BATCH_SIZE, BATCH_SIZE * 256))
                        as Box<dyn ArrayBuilder>
                }
                DataType::Timestamp(TimeUnit::Microsecond, timezone) => Box::new(
                    TimestampMicrosecondBuilder::with_capacity(BATCH_SIZE)
                        .with_timezone_opt(timezone.clone()),
                )
                    as Box<dyn ArrayBuilder>,
                DataType::Date32 => {
                    Box::new(Date32Builder::with_capacity(BATCH_SIZE)) as Box<dyn ArrayBuilder>
                }
                DataType::Time64(TimeUnit::Microsecond) => {
                    Box::new(Time64MicrosecondBuilder::with_capacity(BATCH_SIZE))
                        as Box<dyn ArrayBuilder>
                }
                _ => {
                    return Err(DataFusionError::NotImplemented(format!(
                        "Unsupported data type: {:?}",
                        field.data_type()
                    )))
                }
            });
        }

        Ok(builders)
    }

    fn append_value_to_builder(
        builder: &mut Box<dyn ArrayBuilder>,
        field: &Field,
        original_dtype: &str,
        row: &AnyDatabaseRow,
    ) -> Result<(), DataFusionError> {
        match field.data_type() {
            DataType::Boolean => append_value!(builder, field, row, bool, BooleanBuilder)?,
            DataType::Int8 => append_value!(builder, field, row, i8, Int8Builder)?,
            DataType::Int16 => append_value!(builder, field, row, i16, Int16Builder)?,
            DataType::Int32 => append_value!(builder, field, row, i32, Int32Builder)?,
            DataType::Int64 => append_value!(builder, field, row, i64, Int64Builder)?,
            #[cfg(feature = "mysql")]
            DataType::UInt8 => {
                append_mysql_specific_value!(builder, field, row, u8, UInt8Builder)?;
            }
            #[cfg(feature = "mysql")]
            DataType::UInt16 => {
                append_mysql_specific_value!(builder, field, row, u16, UInt16Builder)?;
            }
            #[cfg(feature = "mysql")]
            DataType::UInt32 => {
                append_mysql_specific_value!(builder, field, row, u32, UInt32Builder)?;
            }
            #[cfg(feature = "mysql")]
            DataType::UInt64 => {
                append_mysql_specific_value!(builder, field, row, u64, UInt64Builder)?;
            }
            DataType::Float32 => append_value!(builder, field, row, f32, Float32Builder)?,
            DataType::Float64 => append_value!(builder, field, row, f64, Float64Builder)?,
            DataType::Decimal128(_precision, scale) => {
                if let Some(builder) = builder.as_any_mut().downcast_mut::<Decimal128Builder>() {
                    if let Some(value) = row.get::<sqlx::types::Decimal>(field.name()) {
                        #[allow(clippy::cast_sign_loss)]
                        let scale_factor = sqlx::types::Decimal::new(1, *scale as u32);
                        let scaled_value = (value / scale_factor).to_i128().unwrap();
                        builder.append_value(scaled_value);
                    } else {
                        builder.append_null();
                    }
                }
            }
            DataType::Utf8 => match original_dtype {
                #[cfg(feature = "postgres")]
                "uuid" => {
                    if let Some(builder) = builder.as_any_mut().downcast_mut::<StringBuilder>() {
                        if let Some(uuid) = row.get::<sqlx::types::Uuid>(field.name()) {
                            builder.append_value(uuid.to_string());
                        } else {
                            builder.append_null();
                        }
                    }
                }
                _ => append_value!(builder, field, row, String, StringBuilder)?,
            },
            DataType::Binary => append_value!(builder, field, row, Vec<u8>, BinaryBuilder)?,
            DataType::Timestamp(TimeUnit::Microsecond, _) => {
                if let Some(builder) = builder
                    .as_any_mut()
                    .downcast_mut::<TimestampMicrosecondBuilder>()
                {
                    if let Some(ts) = row.get::<chrono::DateTime<chrono::Utc>>(field.name()) {
                        builder.append_value(ts.timestamp_micros());
                    } else {
                        builder.append_null();
                    }
                }
            }
            DataType::Date32 => {
                if let Some(builder) = builder.as_any_mut().downcast_mut::<Date32Builder>() {
                    if let Some(nd) = row.get::<chrono::NaiveDate>(field.name()) {
                        builder.append_value(nd.num_days_from_ce() - 719_163 /* 1970-01-01 */);
                    } else {
                        builder.append_null();
                    }
                }
            }
            DataType::Time64(TimeUnit::Microsecond) => {
                if let Some(builder) = builder
                    .as_any_mut()
                    .downcast_mut::<Time64MicrosecondBuilder>()
                {
                    if let Some(nt) = row.get::<chrono::NaiveTime>(field.name()) {
                        builder.append_value(
                            i64::from(nt.num_seconds_from_midnight()) * 1_000_000
                                + i64::from(nt.nanosecond()) / 1_000,
                        );
                    } else {
                        builder.append_null();
                    }
                }
            }
            _ => {
                return Err(DataFusionError::Internal(format!(
                    "Unsupported data type for field '{}'",
                    field.name()
                )))
            }
        }

        Ok(())
    }
}