Usare DuckDB in Rust
DuckDB è un database che potremmo usare al posto del classico SQLite.
Come potete vedere dalla documentazione, supporta parecchi linguaggi; inoltre pare essere più veloce e performante rispetto a SQLite.
In questo articolo vediamo come usarlo in Rust.
Per l'articolo ci serviranno queste due librerie:
[dependencies]
chrono = { version = "0.4.39" }
duckdb = { version = "1.2.0", features = ["bundled"] }
Considerate che l'installazione di duckdb dipende anche da quale OS state usando; io sono su Windows 11.
Qui sotto un pò di codice:
use chrono::{DateTime, Utc};
use duckdb::Connection;
use std::path::Path;
#[derive(Debug)]
struct OperationLog {
id: i32,
operation: String,
date: String,
}
fn main() {
let db_file = "db.duckdb";
let mut create_table = false;
if !Path::new(&db_file).exists() {
create_table = true;
}
let now: DateTime<Utc> = Utc::now();
let conn = Connection::open(db_file).unwrap();
if create_table {
println!("Creating table");
conn.execute_batch(
r"CREATE TABLE IF NOT EXISTS operation_log (id INTEGER PRIMARY KEY, operation VARCHAR, date VARCHAR);
CREATE SEQUENCE seq_id START 1;"
)
.unwrap();
}
conn.execute(
"INSERT INTO operation_log (id, operation, date) VALUES (NEXTVAL('seq_id'), ?, ?)",
["PROVA 1", now.timestamp().to_string().as_str()],
)
.unwrap();
let mut stmt = conn
.prepare("SELECT id, operation, date FROM operation_log")
.unwrap();
let rows = stmt
.query_map([], |row| {
let id: i32 = row.get(0)?;
let operation: String = row.get(1)?;
let date: String = row.get(2)?;
let timestamp = DateTime::from_timestamp(date.parse().unwrap(), 0).unwrap();
let formatted_date = timestamp.format("%Y-%m-%d %H:%M:%S").to_string();
Ok(OperationLog {
id,
operation,
date: formatted_date,
})
})
.unwrap();
for row in rows {
println!("{:?}", row.unwrap());
}
}
Il campo date l'ho salvato in stringa perchè mi stava dando problemi di conversione.
Enjoy!
rust cargo duckdb database
Commentami!