|
- extern crate clap;
- extern crate r2d2;
- extern crate r2d2_sqlite;
- extern crate rusqlite;
- extern crate simple_error;
-
- use clap::{App, SubCommand};
- use r2d2::Pool;
- use r2d2_sqlite::SqliteConnectionManager;
- use rusqlite::params;
- use serde_json::{Map, Value};
- use serde_rusqlite::from_row;
- use serde_rusqlite::Result as SRResult;
- use simple_error::*;
-
- fn main() -> Result<(), SimpleError> {
- let matches = App::new("Rust DB Play")
- .version("1.0")
- .author("Jonathan Altman <jonathan@async.io>")
- .about("Test out Rust database result serialization")
- .subcommand(SubCommand::with_name("sqlite").about("Test on sqlite"))
- .subcommand(SubCommand::with_name("postgres").about("Test on postgres"))
- .get_matches();
-
- return match matches.subcommand_name() {
- Some("sqlite") => test_sqlite(),
- Some("postgres") => test_postgres(),
- None => bail!("No database specified"),
- _ => bail!("Unknown database specified"),
- };
- }
-
- fn test_postgres() -> Result<(), SimpleError> {
- println!("Postgres: Not implemented yet");
- return Ok(());
- }
-
- fn test_sqlite() -> Result<(), SimpleError> {
- let (pool, table_name) = setup_sqlite().unwrap();
- return match test_sqlite_json(pool, &table_name) {
- Ok(()) => Ok(()),
- // @TODO (2019-11-19, Jonathan) Extract sqlite error here
- Err(_) => bail!("Error in testing sqlite"),
- };
- }
-
- fn setup_sqlite() -> SRResult<(Pool<SqliteConnectionManager>, String)> {
- fn setup_pool() -> Pool<SqliteConnectionManager> {
- let manager = SqliteConnectionManager::memory();
- let pool = Pool::new(manager).unwrap();
- pool
- }
- fn setup_db_structure(pool: &Pool<SqliteConnectionManager>, table_name: &str) -> SRResult<()> {
- let conn = pool.get().unwrap();
- conn.execute(
- format!(
- "CREATE TABLE {} (
- id INTEGER PRIMARY KEY,
- name TEXT NOT NULL,
- time_created TEXT NOT NULL,
- data BLOB,
- data_null BLOB
- )",
- table_name
- )
- .as_str(),
- params![],
- )?;
-
- conn.execute(
- "INSERT INTO person (name, time_created, data, data_null)
- VALUES (?1, ?2, ?3, ?4)",
- params![
- "Steven".to_string(),
- time::get_time(),
- "This is some text".to_string(),
- None as Option<Vec<u8>>
- ],
- )?;
- Ok(())
- }
-
- const TABLE_NAME: &str = "person";
- let pool = setup_pool();
- setup_db_structure(&pool, TABLE_NAME)?;
- Ok((pool, TABLE_NAME.to_string()))
- }
-
- fn test_sqlite_json(pool: Pool<SqliteConnectionManager>, table_name: &String) -> SRResult<()> {
- let conn = pool.get().unwrap();
- let mut stmt = conn.prepare(&format!("SELECT * FROM {}", table_name))?;
- let result_iter = stmt.query_map(params![], |row| {
- Ok(from_row::<Map<String, Value>>(row).unwrap())
- })?;
- for cur_result in result_iter {
- println!(
- "Found row {:?}",
- serde_json::to_string(&cur_result.unwrap()).unwrap()
- );
- }
- Ok(())
- }
|