Skip to main content

datafusion_cli/
exec.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
5//! Execution functions
6
7use crate::cli_context::CliSessionContext;
8use crate::helper::split_from_semicolon;
9use crate::print_format::PrintFormat;
10use crate::{
11    command::{Command, OutputFormat},
12    helper::CliHelper,
13    object_storage::{get_object_store, stdin::StdinUtils},
14    print_options::{MaxRows, PrintOptions},
15};
16use datafusion::common::instant::Instant;
17use datafusion::common::{plan_datafusion_err, plan_err};
18use datafusion::config::{ConfigFileType, Dialect};
19use datafusion::datasource::listing::ListingTableUrl;
20use datafusion::error::{DataFusionError, Result};
21use datafusion::execution::memory_pool::MemoryConsumer;
22use datafusion::logical_expr::{DdlStatement, LogicalPlan};
23use datafusion::physical_plan::execution_plan::EmissionType;
24use datafusion::physical_plan::spill::get_record_batch_memory_size;
25use datafusion::physical_plan::{ExecutionPlanProperties, execute_stream};
26use datafusion::sql::parser::{DFParserBuilder, Statement};
27use datafusion::sql::sqlparser;
28use datafusion::sql::sqlparser::dialect::dialect_from_str;
29use futures::StreamExt;
30use log::warn;
31use object_store::Error::Generic;
32use rustyline::Editor;
33use rustyline::error::ReadlineError;
34use std::collections::HashMap;
35use std::fs::File;
36use std::io::BufReader;
37use std::io::prelude::*;
38use tokio::signal;
39
40/// run and execute SQL statements and commands, against a context with the given print options
41pub async fn exec_from_commands(
42    ctx: &dyn CliSessionContext,
43    commands: Vec<String>,
44    print_options: &PrintOptions,
45) -> Result<()> {
46    for sql in commands {
47        exec_and_print(ctx, print_options, sql).await?;
48    }
49
50    Ok(())
51}
52
53/// run and execute SQL statements and commands from a file, against a context with the given print options
54pub async fn exec_from_lines(
55    ctx: &dyn CliSessionContext,
56    reader: &mut BufReader<File>,
57    print_options: &PrintOptions,
58) -> Result<()> {
59    let mut query = "".to_owned();
60
61    for line in reader.lines() {
62        match line {
63            Ok(line) if line.starts_with("#!") || line.starts_with("--") => {}
64            Ok(line) => {
65                let line = line.trim_end();
66                query.push_str(line);
67                if line.ends_with(';') {
68                    match exec_and_print(ctx, print_options, query).await {
69                        Ok(_) => {}
70                        Err(err) => eprintln!("{err}"),
71                    }
72                    query = "".to_string();
73                } else {
74                    query.push('\n');
75                }
76            }
77            _ => {
78                break;
79            }
80        }
81    }
82
83    // run the left over query if the last statement doesn't contain ‘;’
84    // ignore if it only consists of '\n'
85    if query.contains(|c| c != '\n') {
86        exec_and_print(ctx, print_options, query).await?;
87    }
88
89    Ok(())
90}
91
92pub async fn exec_from_files(
93    ctx: &dyn CliSessionContext,
94    files: Vec<String>,
95    print_options: &PrintOptions,
96) -> Result<()> {
97    let files = files
98        .into_iter()
99        .map(|file_path| File::open(file_path).unwrap())
100        .collect::<Vec<_>>();
101
102    for file in files {
103        let mut reader = BufReader::new(file);
104        exec_from_lines(ctx, &mut reader, print_options).await?;
105    }
106
107    Ok(())
108}
109
110/// run and execute SQL statements and commands against a context with the given print options
111pub async fn exec_from_repl(
112    ctx: &dyn CliSessionContext,
113    print_options: &mut PrintOptions,
114) -> rustyline::Result<()> {
115    let mut rl = Editor::new()?;
116    rl.set_helper(Some(CliHelper::new(
117        &ctx.task_ctx().session_config().options().sql_parser.dialect,
118        print_options.color,
119    )));
120    rl.load_history(".history").ok();
121
122    loop {
123        // Parser options can change through any input, including `\i` files,
124        // so sync the validator before every read.
125        rl.helper_mut()
126            .unwrap()
127            .set_parser_options(&ctx.task_ctx().session_config().options().sql_parser);
128
129        match rl.readline("> ") {
130            Ok(line) if line.starts_with('\\') => {
131                rl.add_history_entry(line.trim_end())?;
132                let command = line.split_whitespace().collect::<Vec<_>>().join(" ");
133                if let Ok(cmd) = &command[1..].parse::<Command>() {
134                    match cmd {
135                        Command::Quit => break,
136                        Command::OutputFormat(subcommand) => {
137                            if let Some(subcommand) = subcommand {
138                                if let Ok(command) = subcommand.parse::<OutputFormat>() {
139                                    if let Err(e) = command.execute(print_options) {
140                                        eprintln!("{e}")
141                                    }
142                                } else {
143                                    eprintln!(
144                                        "'\\{}' is not a valid command, you can use '\\?' to see all commands",
145                                        &line[1..]
146                                    );
147                                }
148                            } else {
149                                println!("Output format is {:?}.", print_options.format);
150                            }
151                        }
152                        _ => {
153                            if let Err(e) = cmd.execute(ctx, print_options).await {
154                                eprintln!("{e}")
155                            }
156                        }
157                    }
158                } else {
159                    eprintln!(
160                        "'\\{}' is not a valid command, you can use '\\?' to see all commands",
161                        &line[1..]
162                    );
163                }
164            }
165            Ok(line) => {
166                let lines = split_from_semicolon(&line);
167                for line in lines {
168                    rl.add_history_entry(line.trim_end())?;
169                    tokio::select! {
170                        res = exec_and_print(ctx, print_options, line) => match res {
171                            Ok(_) => {}
172                            Err(err) => eprintln!("{err}"),
173                        },
174                        _ = signal::ctrl_c() => {
175                            println!("^C");
176                        },
177                    }
178                }
179            }
180            Err(ReadlineError::Interrupted) => {
181                println!("^C");
182                rl.helper().unwrap().reset_hint();
183            }
184            Err(ReadlineError::Eof) => {
185                println!("\\q");
186                break;
187            }
188            Err(err) => {
189                eprintln!("Unknown error happened {err:?}");
190                break;
191            }
192        }
193    }
194
195    rl.save_history(".history")
196}
197
198pub(super) async fn exec_and_print(
199    ctx: &dyn CliSessionContext,
200    print_options: &PrintOptions,
201    sql: String,
202) -> Result<()> {
203    let task_ctx = ctx.task_ctx();
204    let options = task_ctx.session_config().options();
205    let dialect = &options.sql_parser.dialect;
206    let dialect = dialect_from_str(dialect).ok_or_else(|| {
207        plan_datafusion_err!(
208            "Unsupported SQL dialect: {dialect}. Available dialects: {}.",
209            Dialect::available()
210        )
211    })?;
212
213    let statements = DFParserBuilder::new(sql.as_str())
214        .with_dialect(dialect.as_ref())
215        .with_recursion_limit(options.sql_parser.recursion_limit.get())
216        .build()?
217        .parse_statements()?;
218    for statement in statements {
219        StatementExecutor::new(statement)
220            .execute(ctx, print_options)
221            .await?;
222    }
223
224    Ok(())
225}
226
227/// Executor for SQL statements, including special handling for S3 region detection retry logic
228struct StatementExecutor {
229    statement: Statement,
230    statement_for_retry: Option<Statement>,
231}
232
233impl StatementExecutor {
234    fn new(statement: Statement) -> Self {
235        let statement_for_retry = matches!(statement, Statement::CreateExternalTable(_))
236            .then(|| statement.clone());
237
238        Self {
239            statement,
240            statement_for_retry,
241        }
242    }
243
244    async fn execute(
245        self,
246        ctx: &dyn CliSessionContext,
247        print_options: &PrintOptions,
248    ) -> Result<()> {
249        let now = Instant::now();
250        let (df, adjusted) = self
251            .create_and_execute_logical_plan(ctx, print_options)
252            .await?;
253        let physical_plan = df.create_physical_plan().await?;
254        let task_ctx = ctx.task_ctx();
255        let options = task_ctx.session_config().options();
256        let print_options = adjusted.into_inner();
257
258        // Track memory usage for the query result if it's bounded
259        let reservation =
260            MemoryConsumer::new("DataFusion-Cli").register(task_ctx.memory_pool());
261
262        if physical_plan.boundedness().is_unbounded() {
263            if physical_plan.pipeline_behavior() == EmissionType::Final {
264                return plan_err!(
265                    "The given query can generate a valid result only once \
266                    the source finishes, but the source is unbounded"
267                );
268            }
269            // As the input stream comes, we can generate results.
270            // However, memory safety is not guaranteed.
271            let stream = execute_stream(physical_plan, task_ctx.clone())?;
272            print_options
273                .print_stream(stream, now, &options.format)
274                .await?;
275        } else {
276            // Non-table formats write every row, so only limit collection when the
277            // selected output format applies the maxrows option.
278            let schema = physical_plan.schema();
279            let mut stream = execute_stream(physical_plan, task_ctx.clone())?;
280            let mut results = vec![];
281            let mut row_count = 0_usize;
282            let max_rows = match (print_options.format, print_options.maxrows) {
283                (PrintFormat::Table, MaxRows::Limited(n)) => n,
284                _ => usize::MAX,
285            };
286            while let Some(batch) = stream.next().await {
287                let batch = batch?;
288                let curr_num_rows = batch.num_rows();
289                // Stop collecting results if the number of rows exceeds the limit
290                // results batch should include the last batch that exceeds the limit
291                if row_count < max_rows.saturating_add(curr_num_rows) {
292                    // Try to grow the reservation to accommodate the batch in memory
293                    reservation.try_grow(get_record_batch_memory_size(&batch))?;
294                    results.push(batch);
295                }
296                row_count += curr_num_rows;
297            }
298            print_options.print_batches(
299                schema,
300                &results,
301                now,
302                row_count,
303                &options.format,
304            )?;
305            reservation.free();
306        }
307
308        Ok(())
309    }
310
311    async fn create_and_execute_logical_plan(
312        mut self,
313        ctx: &dyn CliSessionContext,
314        print_options: &PrintOptions,
315    ) -> Result<(datafusion::dataframe::DataFrame, AdjustedPrintOptions)> {
316        let adjusted = AdjustedPrintOptions::new(print_options.clone())
317            .with_statement(&self.statement);
318
319        let plan = create_plan(ctx, self.statement, false).await?;
320        let adjusted = adjusted.with_plan(&plan);
321
322        let df = match ctx.execute_logical_plan(plan).await {
323            Ok(df) => Ok(df),
324            Err(DataFusionError::ObjectStore(err))
325                if matches!(err.as_ref(), Generic { store, source: _ } if "S3".eq_ignore_ascii_case(store))
326                    && self.statement_for_retry.is_some() =>
327            {
328                warn!(
329                    "S3 region is incorrect, auto-detecting the correct region (this may be slow). Consider updating your region configuration."
330                );
331                let plan =
332                    create_plan(ctx, self.statement_for_retry.take().unwrap(), true)
333                        .await?;
334                ctx.execute_logical_plan(plan).await
335            }
336            Err(e) => Err(e),
337        }?;
338
339        Ok((df, adjusted))
340    }
341}
342
343/// Track adjustments to the print options based on the plan / statement being executed
344#[derive(Debug)]
345struct AdjustedPrintOptions {
346    inner: PrintOptions,
347}
348
349impl AdjustedPrintOptions {
350    fn new(inner: PrintOptions) -> Self {
351        Self { inner }
352    }
353    /// Adjust print options based on any statement specific requirements
354    fn with_statement(mut self, statement: &Statement) -> Self {
355        if let Statement::Statement(sql_stmt) = statement {
356            // SHOW / SHOW ALL
357            if let sqlparser::ast::Statement::ShowVariable { .. } = sql_stmt.as_ref() {
358                self.inner.maxrows = MaxRows::Unlimited
359            }
360        }
361        self
362    }
363
364    /// Adjust print options based on any plan specific requirements
365    fn with_plan(mut self, plan: &LogicalPlan) -> Self {
366        // For plans like `Explain` ignore `MaxRows` option and always display
367        // all rows
368        if matches!(
369            plan,
370            LogicalPlan::Explain(_) | LogicalPlan::Show(_) | LogicalPlan::Analyze(_)
371        ) {
372            self.inner.maxrows = MaxRows::Unlimited;
373        }
374        self
375    }
376
377    /// Finalize and return the inner `PrintOptions`
378    fn into_inner(mut self) -> PrintOptions {
379        if self.inner.format == PrintFormat::Automatic {
380            self.inner.format = PrintFormat::Table;
381        }
382
383        self.inner
384    }
385}
386
387fn config_file_type_from_str(ext: &str) -> Option<ConfigFileType> {
388    match ext.to_lowercase().as_str() {
389        "csv" => Some(ConfigFileType::CSV),
390        "json" => Some(ConfigFileType::JSON),
391        "parquet" => Some(ConfigFileType::PARQUET),
392        _ => None,
393    }
394}
395
396async fn create_plan(
397    ctx: &dyn CliSessionContext,
398    statement: Statement,
399    resolve_region: bool,
400) -> Result<LogicalPlan, DataFusionError> {
401    let mut plan = ctx.session_state().statement_to_plan(statement).await?;
402
403    // Note that cmd is a mutable reference so that create_external_table function can remove all
404    // datafusion-cli specific options before passing through to datafusion. Otherwise, datafusion
405    // will raise Configuration errors.
406    if let LogicalPlan::Ddl(DdlStatement::CreateExternalTable(cmd)) = &mut plan {
407        // To support custom formats, treat error as None
408        let format = config_file_type_from_str(&cmd.file_type);
409
410        // Expose stdin (e.g. `cat data.csv | datafusion-cli`) as a `stdin://`
411        // object store, registered like any other scheme in `get_object_store`.
412        for location in &mut cmd.locations {
413            *location = StdinUtils::rewrite_location(location, format.as_ref());
414            register_object_store_and_config_extensions(
415                ctx,
416                location,
417                &cmd.options,
418                format.clone(),
419                resolve_region,
420            )
421            .await?;
422        }
423    }
424
425    if let LogicalPlan::Copy(copy_to) = &mut plan {
426        let format = config_file_type_from_str(&copy_to.file_type.get_ext());
427
428        register_object_store_and_config_extensions(
429            ctx,
430            &copy_to.output_url,
431            &copy_to.options,
432            format,
433            false,
434        )
435        .await?;
436    }
437    Ok(plan)
438}
439
440/// Asynchronously registers an object store and its configuration extensions
441/// to the session context.
442///
443/// This function dynamically registers a cloud object store based on the given
444/// location and options. It first parses the location to determine the scheme
445/// and constructs the URL accordingly. Depending on the scheme, it also registers
446/// relevant options. The function then alters the default table options with the
447/// given custom options. Finally, it retrieves and registers the object store
448/// in the session context.
449///
450/// # Parameters
451///
452/// * `ctx`: A reference to the `SessionContext` for registering the object store.
453/// * `location`: A string reference representing the location of the object store.
454/// * `options`: A reference to a hash map containing configuration options for
455///   the object store.
456///
457/// # Returns
458///
459/// A `Result<()>` which is an Ok value indicating successful registration, or
460/// an error upon failure.
461///
462/// # Errors
463///
464/// This function can return an error if the location parsing fails, options
465/// alteration fails, or if the object store cannot be retrieved and registered
466/// successfully.
467pub(crate) async fn register_object_store_and_config_extensions(
468    ctx: &dyn CliSessionContext,
469    location: &String,
470    options: &HashMap<String, String>,
471    format: Option<ConfigFileType>,
472    resolve_region: bool,
473) -> Result<()> {
474    // Parse the location URL to extract the scheme and other components
475    let table_path = ListingTableUrl::parse(location)?;
476
477    // Extract the scheme (e.g., "s3", "gcs") from the parsed URL
478    let scheme = table_path.scheme();
479
480    // Obtain a reference to the URL
481    let url = table_path.as_ref();
482
483    // Register the options based on the scheme extracted from the location
484    ctx.register_table_options_extension_from_scheme(scheme);
485
486    // Clone and modify the default table options based on the provided options
487    let mut table_options = ctx.session_state().default_table_options();
488    if let Some(format) = format {
489        table_options.set_config_format(format);
490    }
491    table_options.alter_with_string_hash_map(options)?;
492
493    // Retrieve the appropriate object store based on the scheme, URL, and modified table options
494    let store = get_object_store(
495        &ctx.session_state(),
496        scheme,
497        url,
498        &table_options,
499        resolve_region,
500    )
501    .await?;
502
503    // Register the retrieved object store in the session context's runtime environment
504    ctx.register_object_store(url, store);
505
506    Ok(())
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    use datafusion::common::plan_err;
514    use datafusion::sql::parser::DFParser;
515
516    use datafusion::prelude::SessionContext;
517    use datafusion_common::assert_contains;
518    use url::Url;
519
520    async fn create_external_table_test(location: &str, sql: &str) -> Result<()> {
521        let ctx = SessionContext::new();
522        let plan = ctx.state().create_logical_plan(sql).await?;
523
524        if let LogicalPlan::Ddl(DdlStatement::CreateExternalTable(cmd)) = &plan {
525            let format = config_file_type_from_str(&cmd.file_type);
526            for location in &cmd.locations {
527                register_object_store_and_config_extensions(
528                    &ctx,
529                    location,
530                    &cmd.options,
531                    format.clone(),
532                    false,
533                )
534                .await?;
535            }
536        } else {
537            return plan_err!("LogicalPlan is not a CreateExternalTable");
538        }
539
540        // Ensure the URL is supported by the object store
541        ctx.runtime_env()
542            .object_store(ListingTableUrl::parse(location)?)?;
543
544        Ok(())
545    }
546
547    async fn copy_to_table_test(location: &str, sql: &str) -> Result<()> {
548        let ctx = SessionContext::new();
549        // AWS CONFIG register.
550
551        let plan = ctx.state().create_logical_plan(sql).await?;
552
553        if let LogicalPlan::Copy(cmd) = &plan {
554            let format = config_file_type_from_str(&cmd.file_type.get_ext());
555            register_object_store_and_config_extensions(
556                &ctx,
557                &cmd.output_url,
558                &cmd.options,
559                format,
560                false,
561            )
562            .await?;
563        } else {
564            return plan_err!("LogicalPlan is not a CreateExternalTable");
565        }
566
567        // Ensure the URL is supported by the object store
568        ctx.runtime_env()
569            .object_store(ListingTableUrl::parse(location)?)?;
570
571        Ok(())
572    }
573
574    #[tokio::test]
575    async fn create_object_store_table_http() -> Result<()> {
576        // Should be OK
577        let location = "http://example.com/file.parquet";
578        let sql =
579            format!("CREATE EXTERNAL TABLE test STORED AS PARQUET LOCATION '{location}'");
580        create_external_table_test(location, &sql).await?;
581
582        Ok(())
583    }
584    #[tokio::test]
585    async fn copy_to_external_object_store_test() -> Result<()> {
586        let aws_envs = vec![
587            "AWS_ENDPOINT",
588            "AWS_ACCESS_KEY_ID",
589            "AWS_SECRET_ACCESS_KEY",
590            "AWS_ALLOW_HTTP",
591        ];
592        for aws_env in aws_envs {
593            if std::env::var(aws_env).is_err() {
594                eprint!("aws envs not set, skipping s3 test");
595                return Ok(());
596            }
597        }
598
599        let locations = vec![
600            "s3://bucket/path/file.parquet",
601            "oss://bucket/path/file.parquet",
602            "cos://bucket/path/file.parquet",
603            "gcs://bucket/path/file.parquet",
604        ];
605        let ctx = SessionContext::new();
606        let task_ctx = ctx.task_ctx();
607        let dialect = &task_ctx.session_config().options().sql_parser.dialect;
608        let dialect = dialect_from_str(dialect).ok_or_else(|| {
609            plan_datafusion_err!(
610                "Unsupported SQL dialect: {dialect}. Available dialects: {}.",
611                Dialect::available()
612            )
613        })?;
614        for location in locations {
615            let sql = format!("copy (values (1,2)) to '{location}' STORED AS PARQUET;");
616            let statements = DFParser::parse_sql_with_dialect(&sql, dialect.as_ref())?;
617            for statement in statements {
618                //Should not fail
619                let mut plan = create_plan(&ctx, statement, false).await?;
620                if let LogicalPlan::Copy(copy_to) = &mut plan {
621                    assert_eq!(copy_to.output_url, location);
622                    assert_eq!(copy_to.file_type.get_ext(), "parquet".to_string());
623                    ctx.runtime_env()
624                        .object_store_registry
625                        .get_store(&Url::parse(&copy_to.output_url).unwrap())?;
626                } else {
627                    return plan_err!("LogicalPlan is not a CopyTo");
628                }
629            }
630        }
631        Ok(())
632    }
633
634    #[tokio::test]
635    async fn copy_to_object_store_table_s3() -> Result<()> {
636        let access_key_id = "fake_access_key_id";
637        let secret_access_key = "fake_secret_access_key";
638        let location = "s3://bucket/path/file.parquet";
639
640        // Missing region, use object_store defaults
641        let sql = format!("COPY (values (1,2)) TO '{location}' STORED AS PARQUET
642            OPTIONS ('aws.access_key_id' '{access_key_id}', 'aws.secret_access_key' '{secret_access_key}')");
643        copy_to_table_test(location, &sql).await?;
644
645        Ok(())
646    }
647
648    #[tokio::test]
649    async fn create_object_store_table_s3() -> Result<()> {
650        let access_key_id = "fake_access_key_id";
651        let secret_access_key = "fake_secret_access_key";
652        let region = "fake_us-east-2";
653        let session_token = "fake_session_token";
654        let location = "s3://bucket/path/file.parquet";
655
656        // Missing region, use object_store defaults
657        let sql = format!("CREATE EXTERNAL TABLE test STORED AS PARQUET
658            OPTIONS('aws.access_key_id' '{access_key_id}', 'aws.secret_access_key' '{secret_access_key}') LOCATION '{location}'");
659        create_external_table_test(location, &sql).await?;
660
661        // Should be OK
662        let sql = format!("CREATE EXTERNAL TABLE test STORED AS PARQUET
663            OPTIONS('aws.access_key_id' '{access_key_id}', 'aws.secret_access_key' '{secret_access_key}', 'aws.region' '{region}', 'aws.session_token' '{session_token}') LOCATION '{location}'");
664        create_external_table_test(location, &sql).await?;
665
666        Ok(())
667    }
668
669    #[tokio::test]
670    async fn create_object_store_table_oss() -> Result<()> {
671        let access_key_id = "fake_access_key_id";
672        let secret_access_key = "fake_secret_access_key";
673        let endpoint = "fake_endpoint";
674        let location = "oss://bucket/path/file.parquet";
675
676        // Should be OK
677        let sql = format!("CREATE EXTERNAL TABLE test STORED AS PARQUET
678            OPTIONS('aws.access_key_id' '{access_key_id}', 'aws.secret_access_key' '{secret_access_key}', 'aws.oss.endpoint' '{endpoint}') LOCATION '{location}'");
679        create_external_table_test(location, &sql).await?;
680
681        Ok(())
682    }
683
684    #[tokio::test]
685    async fn create_object_store_table_cos() -> Result<()> {
686        let access_key_id = "fake_access_key_id";
687        let secret_access_key = "fake_secret_access_key";
688        let endpoint = "fake_endpoint";
689        let location = "cos://bucket/path/file.parquet";
690
691        // Should be OK
692        let sql = format!("CREATE EXTERNAL TABLE test STORED AS PARQUET
693            OPTIONS('aws.access_key_id' '{access_key_id}', 'aws.secret_access_key' '{secret_access_key}', 'aws.cos.endpoint' '{endpoint}') LOCATION '{location}'");
694        create_external_table_test(location, &sql).await?;
695
696        Ok(())
697    }
698
699    #[tokio::test]
700    async fn create_object_store_table_gcs() -> Result<()> {
701        let service_account_path = "fake_service_account_path";
702        let service_account_key = "{\"private_key\": \"fake_private_key.pem\",\"client_email\":\"fake_client_email\", \"private_key_id\":\"id\"}";
703        let application_credentials_path = "fake_application_credentials_path";
704        let location = "gcs://bucket/path/file.parquet";
705
706        // for service_account_path
707        let sql = format!("CREATE EXTERNAL TABLE test STORED AS PARQUET
708            OPTIONS('gcp.service_account_path' '{service_account_path}') LOCATION '{location}'");
709        let err = create_external_table_test(location, &sql)
710            .await
711            .unwrap_err();
712        assert_contains!(err.to_string(), "os error 2");
713
714        // for service_account_key
715        let sql = format!(
716            "CREATE EXTERNAL TABLE test STORED AS PARQUET OPTIONS('gcp.service_account_key' '{service_account_key}') LOCATION '{location}'"
717        );
718        let err = create_external_table_test(location, &sql)
719            .await
720            .unwrap_err();
721        assert_contains!(err.to_string(), "Error reading pem file: no items found");
722
723        // for application_credentials_path
724        let sql = format!("CREATE EXTERNAL TABLE test STORED AS PARQUET
725            OPTIONS('gcp.application_credentials_path' '{application_credentials_path}') LOCATION '{location}'");
726        let err = create_external_table_test(location, &sql)
727            .await
728            .unwrap_err();
729        assert_contains!(err.to_string(), "os error 2");
730
731        Ok(())
732    }
733
734    #[tokio::test]
735    async fn create_external_table_local_file() -> Result<()> {
736        let location = "path/to/file.parquet";
737
738        // Ensure that local files are also registered
739        let sql =
740            format!("CREATE EXTERNAL TABLE test STORED AS PARQUET LOCATION '{location}'");
741        create_external_table_test(location, &sql).await.unwrap();
742
743        Ok(())
744    }
745
746    #[tokio::test]
747    async fn create_external_table_format_option() -> Result<()> {
748        let location = "path/to/file.cvs";
749
750        // Test with format options
751        let sql = format!(
752            "CREATE EXTERNAL TABLE test STORED AS CSV LOCATION '{location}' OPTIONS('format.has_header' 'true')"
753        );
754        create_external_table_test(location, &sql).await.unwrap();
755
756        Ok(())
757    }
758}