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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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
//
//   http://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.

//! Context (remote or local)

use datafusion::dataframe::DataFrame;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::context::{SessionConfig, SessionContext};
use std::sync::Arc;

/// The CLI supports using a local DataFusion context or a distributed BallistaContext
pub enum Context {
    /// In-process execution with DataFusion
    Local(SessionContext),
    /// Distributed execution with Ballista (if available)
    Remote(BallistaContext),
}

impl Context {
    /// create a new remote context with given host and port
    pub async fn new_remote(host: &str, port: u16) -> Result<Context> {
        Ok(Context::Remote(BallistaContext::try_new(host, port).await?))
    }

    /// create a local context using the given config
    pub fn new_local(config: &SessionConfig) -> Context {
        Context::Local(SessionContext::with_config(config.clone()))
    }

    /// execute an SQL statement against the context
    pub async fn sql(&mut self, sql: &str) -> Result<Arc<DataFrame>> {
        match self {
            Context::Local(datafusion) => datafusion.sql(sql).await,
            Context::Remote(ballista) => ballista.sql(sql).await,
        }
    }
}

// implement wrappers around the BallistaContext to support running without ballista

#[cfg(feature = "ballista")]
pub struct BallistaContext(ballista::context::BallistaContext);
#[cfg(feature = "ballista")]
impl BallistaContext {
    pub async fn try_new(host: &str, port: u16) -> Result<Self> {
        use ballista::context::BallistaContext;
        use ballista::prelude::BallistaConfig;
        let builder =
            BallistaConfig::builder().set("ballista.with_information_schema", "true");
        let config = builder
            .build()
            .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
        let remote_ctx = BallistaContext::remote(host, port, &config)
            .await
            .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
        Ok(Self(remote_ctx))
    }
    pub async fn sql(&mut self, sql: &str) -> Result<Arc<DataFrame>> {
        self.0.sql(sql).await
    }
}

#[cfg(not(feature = "ballista"))]
pub struct BallistaContext();
#[cfg(not(feature = "ballista"))]
impl BallistaContext {
    pub async fn try_new(_host: &str, _port: u16) -> Result<Self> {
        Err(DataFusionError::NotImplemented(
            "Remote execution not supported. Compile with feature 'ballista' to enable"
                .to_string(),
        ))
    }
    pub async fn sql(&mut self, _sql: &str) -> Result<Arc<DataFrame>> {
        unreachable!()
    }
}