datafusion-table-providers 0.12.0

Extend the capabilities of DataFusion to support additional data sources via implementations of the `TableProvider` trait.
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
/*
Copyright 2024 The Spice.ai OSS Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use crate::mysql::write::MySQLTableWriter;
use crate::sql::arrow_sql_gen::statement::{CreateTableBuilder, IndexBuilder, InsertBuilder};
use crate::sql::db_connection_pool::dbconnection::mysqlconn::MySQLConnection;
use crate::sql::db_connection_pool::dbconnection::DbConnection;
use crate::sql::db_connection_pool::mysqlpool::MySQLConnectionPool;
use crate::sql::db_connection_pool::{self, mysqlpool, DbConnectionPool};
use crate::sql::sql_provider_datafusion::{self, SqlTable};
use crate::util::{
    self, column_reference::ColumnReference, constraints::get_primary_keys_from_constraints,
    indexes::IndexType, on_conflict::OnConflict, secrets::to_secret_map, to_datafusion_error,
};
use crate::util::{column_reference, constraints, on_conflict};
use async_trait::async_trait;
use datafusion::arrow::array::RecordBatch;
use datafusion::arrow::datatypes::{Schema, SchemaRef};
use datafusion::catalog::Session;
use datafusion::sql::unparser::dialect::MySqlDialect;
use datafusion::{
    catalog::TableProviderFactory, common::Constraints, datasource::TableProvider,
    error::DataFusionError, logical_expr::CreateExternalTable, sql::TableReference,
};
use mysql_async::prelude::{Queryable, ToValue};
use mysql_async::{Metrics, TxOpts};
use sea_query::{Alias, DeleteStatement, MysqlQueryBuilder};
use snafu::prelude::*;
use sql_table::MySQLTable;
use std::collections::HashMap;
use std::sync::Arc;

pub type DynMySQLConnectionPool =
    dyn DbConnectionPool<mysql_async::Conn, &'static (dyn ToValue + Sync)> + Send + Sync;

pub type DynMySQLConnection = dyn DbConnection<mysql_async::Conn, &'static (dyn ToValue + Sync)>;

#[cfg(feature = "mysql-federation")]
pub mod federation;
pub(crate) mod mysql_window;
pub mod sql_table;
pub mod write;

#[derive(Debug, Snafu)]
pub enum Error {
    #[snafu(display("DbConnectionError: {source}"))]
    DbConnectionError {
        source: db_connection_pool::dbconnection::GenericError,
    },

    #[snafu(display("Unable to construct SQL table: {source}"))]
    UnableToConstructSQLTable {
        source: sql_provider_datafusion::Error,
    },

    #[snafu(display("Unable to delete all data from the MySQL table: {source}"))]
    UnableToDeleteAllTableData { source: mysql_async::Error },

    #[snafu(display("Unable to insert Arrow batch to MySQL table: {source}"))]
    UnableToInsertArrowBatch { source: mysql_async::Error },

    #[snafu(display("Unable to downcast DbConnection to MySQLConnection"))]
    UnableToDowncastDbConnection {},

    #[snafu(display("Unable to begin MySQL transaction: {source}"))]
    UnableToBeginTransaction { source: mysql_async::Error },

    #[snafu(display("Unable to create MySQL connection pool: {source}"))]
    UnableToCreateMySQLConnectionPool { source: mysqlpool::Error },

    #[snafu(display("Unable to create the MySQL table: {source}"))]
    UnableToCreateMySQLTable { source: mysql_async::Error },

    #[snafu(display("Unable to create an index for the MySQL table: {source}"))]
    UnableToCreateIndexForMySQLTable { source: mysql_async::Error },

    #[snafu(display("Unable to commit the MySQL transaction: {source}"))]
    UnableToCommitMySQLTransaction { source: mysql_async::Error },

    #[snafu(display("Unable to create insertion statement for MySQL table: {source}"))]
    UnableToCreateInsertStatement {
        source: crate::sql::arrow_sql_gen::statement::Error,
    },

    #[snafu(display("The table '{table_name}' doesn't exist in the MySQL server"))]
    TableDoesntExist { table_name: String },

    #[snafu(display("Constraint Violation: {source}"))]
    ConstraintViolation { source: constraints::Error },

    #[snafu(display("Error parsing column reference: {source}"))]
    UnableToParseColumnReference { source: column_reference::Error },

    #[snafu(display("Error parsing on_conflict: {source}"))]
    UnableToParseOnConflict { source: on_conflict::Error },
}

type Result<T, E = Error> = std::result::Result<T, E>;

pub struct MySQLTableFactory {
    pool: Arc<MySQLConnectionPool>,
}

impl MySQLTableFactory {
    #[must_use]
    pub fn new(pool: Arc<MySQLConnectionPool>) -> Self {
        Self { pool }
    }

    pub async fn table_provider(
        &self,
        table_reference: TableReference,
    ) -> Result<Arc<dyn TableProvider + 'static>, Box<dyn std::error::Error + Send + Sync>> {
        let pool = Arc::clone(&self.pool);
        let table_provider = Arc::new(
            MySQLTable::new(&pool, table_reference)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?,
        );

        #[cfg(feature = "mysql-federation")]
        let table_provider = Arc::new(
            table_provider
                .create_federated_table_provider()
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?,
        );

        Ok(table_provider)
    }

    pub async fn read_write_table_provider(
        &self,
        table_reference: TableReference,
    ) -> Result<Arc<dyn TableProvider + 'static>, Box<dyn std::error::Error + Send + Sync>> {
        let read_provider = Self::table_provider(self, table_reference.clone()).await?;
        let schema = read_provider.schema();

        let table_name = table_reference.to_string();
        let mysql = MySQL::new(
            table_name,
            Arc::clone(&self.pool),
            schema,
            Constraints::default(),
        );

        Ok(MySQLTableWriter::create(read_provider, mysql, None))
    }

    pub fn conn_pool_metrics(&self) -> Arc<Metrics> {
        self.pool.metrics()
    }
}

#[derive(Debug)]
pub struct MySQLTableProviderFactory {}

impl MySQLTableProviderFactory {
    #[must_use]
    pub fn new() -> Self {
        Self {}
    }
}

impl Default for MySQLTableProviderFactory {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl TableProviderFactory for MySQLTableProviderFactory {
    async fn create(
        &self,
        _state: &dyn Session,
        cmd: &CreateExternalTable,
    ) -> datafusion::common::Result<Arc<dyn TableProvider>> {
        let name = cmd.name.to_string();
        let mut options = cmd.options.clone();
        let schema: Schema = cmd.schema.as_ref().as_arrow().clone();

        let indexes_option_str = options.remove("indexes");
        let unparsed_indexes: HashMap<String, IndexType> = match indexes_option_str {
            Some(indexes_str) => util::hashmap_from_option_string(&indexes_str),
            None => HashMap::new(),
        };

        let unparsed_indexes = unparsed_indexes
            .into_iter()
            .map(|(key, value)| {
                let columns = ColumnReference::try_from(key.as_str())
                    .context(UnableToParseColumnReferenceSnafu)
                    .map_err(util::to_datafusion_error);
                (columns, value)
            })
            .collect::<Vec<(Result<ColumnReference, DataFusionError>, IndexType)>>();

        let mut indexes: Vec<(ColumnReference, IndexType)> = Vec::new();
        for (columns, index_type) in unparsed_indexes {
            let columns = columns?;
            indexes.push((columns, index_type));
        }

        let mut on_conflict: Option<OnConflict> = None;
        if let Some(on_conflict_str) = options.remove("on_conflict") {
            on_conflict = Some(
                OnConflict::try_from(on_conflict_str.as_str())
                    .context(UnableToParseOnConflictSnafu)
                    .map_err(util::to_datafusion_error)?,
            );
        }

        let params = to_secret_map(options);

        let pool = Arc::new(
            MySQLConnectionPool::new(params)
                .await
                .context(UnableToCreateMySQLConnectionPoolSnafu)
                .map_err(to_datafusion_error)?,
        );
        let schema = Arc::new(schema);
        let mysql = MySQL::new(
            name.clone(),
            Arc::clone(&pool),
            Arc::clone(&schema),
            cmd.constraints.clone(),
        );

        let mut db_conn = pool
            .connect()
            .await
            .context(DbConnectionSnafu)
            .map_err(to_datafusion_error)?;

        let mysql_conn = MySQL::mysql_conn(&mut db_conn).map_err(to_datafusion_error)?;
        let mut conn_guard = mysql_conn.conn.lock().await;
        let mut transaction = conn_guard
            .start_transaction(TxOpts::default())
            .await
            .context(UnableToBeginTransactionSnafu)
            .map_err(to_datafusion_error)?;

        let primary_keys = get_primary_keys_from_constraints(&cmd.constraints, &schema);

        mysql
            .create_table(Arc::clone(&schema), &mut transaction, primary_keys)
            .await
            .map_err(to_datafusion_error)?;

        for index in indexes {
            mysql
                .create_index(
                    &mut transaction,
                    index.0.iter().collect(),
                    index.1 == IndexType::Unique,
                )
                .await
                .map_err(to_datafusion_error)?;
        }

        transaction
            .commit()
            .await
            .context(UnableToCommitMySQLTransactionSnafu)
            .map_err(to_datafusion_error)?;

        drop(conn_guard);

        let dyn_pool: Arc<DynMySQLConnectionPool> = pool;

        let read_provider = Arc::new(
            SqlTable::new_with_schema(
                "mysql",
                &dyn_pool,
                Arc::clone(&schema),
                TableReference::bare(name.clone()),
            )
            .with_dialect(Arc::new(MySqlDialect {})),
        );

        #[cfg(feature = "mysql-federation")]
        let read_provider = Arc::new(read_provider.create_federated_table_provider()?);
        Ok(MySQLTableWriter::create(read_provider, mysql, on_conflict))
    }
}

#[derive(Debug)]
pub struct MySQL {
    table_name: String,
    pool: Arc<MySQLConnectionPool>,
    schema: SchemaRef,
    constraints: Constraints,
}

impl MySQL {
    #[must_use]
    pub fn new(
        table_name: String,
        pool: Arc<MySQLConnectionPool>,
        schema: SchemaRef,
        constraints: Constraints,
    ) -> Self {
        Self {
            table_name,
            pool,
            schema,
            constraints,
        }
    }

    #[must_use]
    pub fn table_name(&self) -> &str {
        &self.table_name
    }

    #[must_use]
    pub fn constraints(&self) -> &Constraints {
        &self.constraints
    }

    pub async fn connect(&self) -> Result<Box<DynMySQLConnection>> {
        let mut conn = self.pool.connect().await.context(DbConnectionSnafu)?;

        let mysql_conn = Self::mysql_conn(&mut conn)?;

        if !self.table_exists(mysql_conn).await {
            TableDoesntExistSnafu {
                table_name: self.table_name.clone(),
            }
            .fail()?;
        }

        Ok(conn)
    }

    pub fn mysql_conn(db_connection: &mut Box<DynMySQLConnection>) -> Result<&mut MySQLConnection> {
        let conn = db_connection
            .as_any_mut()
            .downcast_mut::<MySQLConnection>()
            .context(UnableToDowncastDbConnectionSnafu)?;

        Ok(conn)
    }

    async fn table_exists(&self, mysql_connection: &MySQLConnection) -> bool {
        let sql = format!(
            "SELECT EXISTS (
          SELECT 1
          FROM information_schema.tables
          WHERE table_name = '{name}'
        )",
            name = self.table_name
        );
        tracing::trace!("{sql}");
        let Ok(Some((exists,))) = mysql_connection
            .conn
            .lock()
            .await
            .query_first::<(bool,), _>(&sql)
            .await
        else {
            return false;
        };

        exists
    }

    async fn insert_batch(
        &self,
        transaction: &mut mysql_async::Transaction<'_>,
        batch: RecordBatch,
        on_conflict: Option<OnConflict>,
    ) -> Result<()> {
        let batches = vec![batch];
        let insert_table_builder =
            InsertBuilder::new(&TableReference::bare(self.table_name.clone()), &batches);

        let sea_query_on_conflict =
            on_conflict.map(|oc| oc.build_sea_query_on_conflict(&self.schema));

        let sql = insert_table_builder
            .build_mysql(sea_query_on_conflict)
            .context(UnableToCreateInsertStatementSnafu)?;

        transaction
            .exec_drop(&sql, ())
            .await
            .context(UnableToInsertArrowBatchSnafu)?;

        Ok(())
    }

    async fn delete_all_table_data(
        &self,
        transaction: &mut mysql_async::Transaction<'_>,
    ) -> Result<()> {
        let delete = DeleteStatement::new()
            .from_table(Alias::new(self.table_name.clone()))
            .to_string(MysqlQueryBuilder);
        transaction
            .exec_drop(delete.as_str(), ())
            .await
            .context(UnableToDeleteAllTableDataSnafu)?;

        Ok(())
    }

    async fn create_table(
        &self,
        schema: SchemaRef,
        transaction: &mut mysql_async::Transaction<'_>,
        primary_keys: Vec<String>,
    ) -> Result<()> {
        let create_table_statement =
            CreateTableBuilder::new(schema, &self.table_name).primary_keys(primary_keys);
        let create_stmts = create_table_statement.build_mysql();

        transaction
            .exec_drop(create_stmts, ())
            .await
            .context(UnableToCreateMySQLTableSnafu)
    }

    async fn create_index(
        &self,
        transaction: &mut mysql_async::Transaction<'_>,
        columns: Vec<&str>,
        unique: bool,
    ) -> Result<()> {
        let mut index_builder = IndexBuilder::new(&self.table_name, columns);
        if unique {
            index_builder = index_builder.unique();
        }
        let sql = index_builder.build_mysql();

        transaction
            .exec_drop(sql, ())
            .await
            .context(UnableToCreateIndexForMySQLTableSnafu)
    }
}