Skip to content

Apache DataFusion SQL Query Engine

2.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! # Arrow Flight Examples
//!
//! These examples demonstrate Arrow Flight usage.
//!
//! ## Usage
//! ```bash
//! cargo run --example flight -- [all|client|server|sql_server]
//! ```
//!
//! Each subcommand runs a corresponding example:
//! - `all` — run all examples included in this module
//!   Note: The Flight server must be started in a separate process
//!   before running the `client` example. Therefore, running `all` will
//!   not produce a full server+client workflow automatically.
//!
//! - `client`
//!   (file: client.rs, desc: Execute SQL queries via Arrow Flight protocol)
//!
//! - `server`
//!   (file: server.rs, desc: Run DataFusion server accepting FlightSQL/JDBC queries)
//!
//! - `sql_server`
//!   (file: sql_server.rs, desc: Standalone SQL server for JDBC clients)

mod client;
mod server;
mod sql_server;

use datafusion::error::{DataFusionError, Result};
use strum::{IntoEnumIterator, VariantNames};
use strum_macros::{Display, EnumIter, EnumString, VariantNames};

/// The `all` option cannot run all examples end-to-end because the
/// `server` example must run in a separate process before the `client`
/// example can connect.
/// Therefore, `all` only iterates over individually runnable examples.
#[derive(EnumIter, EnumString, Display, VariantNames)]
#[strum(serialize_all = "snake_case")]
enum ExampleKind {
    All,
    Client,
    Server,
    SqlServer,
}

impl ExampleKind {
    const EXAMPLE_NAME: &str = "flight";

    fn runnable() -> impl Iterator<Item = ExampleKind> {
        ExampleKind::iter().filter(|v| !matches!(v, ExampleKind::All))
    }

    async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        match self {
            ExampleKind::All => {
                for example in ExampleKind::runnable() {
                    println!("Running example: {example}");
                    Box::pin(example.run()).await?;
                }
            }
            ExampleKind::Client => client::client().await?,
            ExampleKind::Server => server::server().await?,
            ExampleKind::SqlServer => sql_server::sql_server().await?,
        }
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let usage = format!(
        "Usage: cargo run --example {} -- [{}]",
        ExampleKind::EXAMPLE_NAME,
        ExampleKind::VARIANTS.join("|")
    );

    let example: ExampleKind = std::env::args()
        .nth(1)
        .unwrap_or_else(|| ExampleKind::All.to_string())
        .parse()
        .map_err(|_| DataFusionError::Execution(format!("Unknown example. {usage}")))?;

    example.run().await
}