Skip to main content

datafusion_cli/
cli_context.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::sync::Arc;
6
7use datafusion::{
8    dataframe::DataFrame,
9    error::DataFusionError,
10    execution::{TaskContext, context::SessionState},
11    logical_expr::LogicalPlan,
12    prelude::SessionContext,
13};
14use object_store::ObjectStore;
15
16use crate::object_storage::{AwsOptions, GcpOptions};
17
18#[async_trait::async_trait]
19/// The CLI session context trait provides a way to have a session context that can be used with datafusion's CLI code.
20pub trait CliSessionContext {
21    /// Get an atomic reference counted task context.
22    fn task_ctx(&self) -> Arc<TaskContext>;
23
24    /// Get the session state.
25    fn session_state(&self) -> SessionState;
26
27    /// Register an object store with the session context.
28    fn register_object_store(
29        &self,
30        url: &url::Url,
31        object_store: Arc<dyn ObjectStore>,
32    ) -> Option<Arc<dyn ObjectStore + 'static>>;
33
34    /// Register table options extension from scheme.
35    fn register_table_options_extension_from_scheme(&self, scheme: &str);
36
37    /// Execute a logical plan and return a DataFrame.
38    async fn execute_logical_plan(
39        &self,
40        plan: LogicalPlan,
41    ) -> Result<DataFrame, DataFusionError>;
42}
43
44#[async_trait::async_trait]
45impl CliSessionContext for SessionContext {
46    fn task_ctx(&self) -> Arc<TaskContext> {
47        self.task_ctx()
48    }
49
50    fn session_state(&self) -> SessionState {
51        self.state()
52    }
53
54    fn register_object_store(
55        &self,
56        url: &url::Url,
57        object_store: Arc<dyn ObjectStore>,
58    ) -> Option<Arc<dyn ObjectStore + 'static>> {
59        self.register_object_store(url, object_store)
60    }
61
62    fn register_table_options_extension_from_scheme(&self, scheme: &str) {
63        match scheme {
64            // For Amazon S3 or Alibaba Cloud OSS
65            "s3" | "oss" | "cos" => {
66                // Register AWS specific table options in the session context:
67                self.register_table_options_extension(AwsOptions::default())
68            }
69            // For Google Cloud Storage
70            "gs" | "gcs" => {
71                // Register GCP specific table options in the session context:
72                self.register_table_options_extension(GcpOptions::default())
73            }
74            // For unsupported schemes, do nothing:
75            _ => {}
76        }
77    }
78
79    async fn execute_logical_plan(
80        &self,
81        plan: LogicalPlan,
82    ) -> Result<DataFrame, DataFusionError> {
83        self.execute_logical_plan(plan).await
84    }
85}