From 1475599d71c5523f457add5d0386d8b61031da58 Mon Sep 17 00:00:00 2001 From: Banyc <36535895+Banyc@users.noreply.github.com> Date: Sat, 9 Dec 2023 20:15:37 +0800 Subject: [PATCH] feat: non-interactive mode --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/main.rs | 27 ++++++++++++++++++++++++++- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eff93ea..d6af568 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -395,7 +395,7 @@ dependencies = [ [[package]] name = "dfsql" -version = "0.3.0" +version = "0.3.1" dependencies = [ "anyhow", "chumsky", diff --git a/Cargo.toml b/Cargo.toml index 38859de..4b451de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dfsql" -version = "0.3.0" +version = "0.3.1" edition = "2021" description = "SQL REPL for Data Frames" license = "MIT" diff --git a/src/main.rs b/src/main.rs index 1c89793..3ca6ada 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,13 @@ use std::{ borrow::Cow, collections::HashMap, - io::{BufRead, BufReader, Write}, + io::{BufRead, BufReader, Read, Write}, path::{Path, PathBuf}, }; use anyhow::{bail, Context}; use clap::Parser; +use dfsql::{df::apply, sql}; use fancy_regex::Regex; use handler::{HandleLineResult, LineExecutor}; use polars::prelude::*; @@ -19,6 +20,8 @@ const SQL_EXTENSION: &str = "dfsql"; #[derive(Debug, Parser)] pub struct Cli { + /// `.dfsql` file to execute + sql: Option, /// Input file containing a data frame #[clap(short, long)] input: PathBuf, @@ -47,6 +50,28 @@ impl Cli { let df = read_df_file(path, self.infer_schema_length)?; others.insert(name.to_string(), df); } + if let Some(sql_file) = &self.sql { + // Non-interactive mode + if self.lazy { + bail!( + "`lazy` option is unavailable if a `.{SQL_EXTENSION}` is provided via the argument `sql`" + ); + } + + let mut file = std::fs::File::options().read(true).open(sql_file)?; + let mut src = String::new(); + file.read_to_string(&mut src)?; + drop(file); + let Some(s) = sql::parse(&src) else { + return Ok(()); + }; + let df = apply(df, &s, &others)?.collect()?; + match &self.output { + Some(output) => write_df_output(df, output)?, + None => println!("{df}"), + } + return Ok(()); + } let mut handler = LineExecutor::new(df.clone(), others); let mut rl = Editor::new()?; if !self.lazy {