use hyperdb_api::{
escape_string_literal, Catalog, Connection, CreateMode, HyperProcess, Parameters, Result,
SqlType, TableDefinition,
};
fn customer_table() -> TableDefinition {
TableDefinition::from("Customer")
.add_required_column("Customer ID", SqlType::text())
.add_required_column("Customer Name", SqlType::text())
.add_required_column("Loyalty Reward Points", SqlType::big_int())
.add_required_column("Segment", SqlType::text())
}
fn run_create_hyper_file_from_csv() -> Result<()> {
println!("EXAMPLE - Load data from CSV into table in new Hyper file");
std::fs::create_dir_all("test_results")?;
let path_to_database = "test_results/create_hyper_file_from_csv.hyper";
let path_to_csv = "test_results/customers.csv";
create_sample_csv(path_to_csv)?;
{
let mut process_parameters = Parameters::new();
process_parameters.set("log_file_max_count", "2"); process_parameters.set("log_file_size_limit", "100M"); process_parameters.set("log_dir", "test_results");
let hyper = HyperProcess::new(None, Some(&process_parameters))?;
{
let connection =
Connection::new(&hyper, path_to_database, CreateMode::CreateAndReplace)?;
let catalog = Catalog::new(&connection);
let customer_def = customer_table();
catalog.create_table(&customer_def)?;
println!("Issuing the SQL COPY command to load the csv file into the table. Since the first line");
println!(
"of our csv file contains the column names, we use the `header` option to skip it."
);
let copy_command = format!(
"COPY {} FROM {} WITH (FORMAT csv, NULL 'NULL', DELIMITER ',', HEADER)",
customer_def.qualified_name(),
escape_string_literal(path_to_csv)
);
let row_count = connection.execute_command(©_command)?;
println!("The number of rows in table \"Customer\" is {row_count}.");
}
println!("The connection to the Hyper file has been closed.");
}
println!("The Hyper Process has been shut down.");
Ok(())
}
fn create_sample_csv(path: &str) -> std::io::Result<()> {
use std::io::Write;
if let Some(parent) = std::path::Path::new(path).parent() {
std::fs::create_dir_all(parent)?;
}
let mut file = std::fs::File::create(path)?;
writeln!(
file,
"Customer ID,Customer Name,Loyalty Reward Points,Segment"
)?;
writeln!(file, "DK-13375,Dennis Kane,518,Consumer")?;
writeln!(file, "EB-13705,Ed Braxton,815,Corporate")?;
writeln!(file, "JL-15235,Jane Lopez,2100,Consumer")?;
writeln!(file, "MK-16790,Mike Kelly,320,Corporate")?;
writeln!(file, "SR-20815,Sarah Roberts,1450,Home Office")?;
Ok(())
}
fn main() {
match run_create_hyper_file_from_csv() {
Ok(()) => {}
Err(e) => {
eprintln!("{e}");
std::process::exit(1);
}
}
}