Browse Source

Factored out to pass connection pool, not pooled connection

Switched around to pass around the connection pool from which to
get a new connection. rather than a pooled connection already
pulled off the pool.
master
Jonathan M. Altman 5 years ago
parent
commit
8da87f3b60
2 changed files with 69 additions and 63 deletions
  1. +1
    -0
      .gitignore
  2. +68
    -63
      src/main.rs

+ 1
- 0
.gitignore View File

@@ -1,2 +1,3 @@
/target
**/*.rs.bk
*.iml

+ 68
- 63
src/main.rs View File

@@ -5,93 +5,98 @@ 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::from_row;
use serde_rusqlite::Result as SRResult;
use r2d2::{PooledConnection};
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();
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")
};
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(());
println!("Postgres: Not implemented yet");
return Ok(());
}

fn test_sqlite() -> Result<(), SimpleError> {
let (conn, table_name) = setup_sqlite().unwrap();
return match test_sqlite_json(conn, &table_name) {
Ok(()) => Ok(()),
// @TODO (2019-11-19, Jonathan) Extract sqlite error here
Err(_) => bail!("Error in testing sqlite")
};
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<(PooledConnection<SqliteConnectionManager>, String)> {
fn setup_conn() -> PooledConnection<SqliteConnectionManager> {
let manager = SqliteConnectionManager::memory();
let pool = r2d2::Pool::new(manager).unwrap();
let conn = pool.get().unwrap();
conn
}
fn setup_db_structure(conn: &PooledConnection<SqliteConnectionManager>) -> SRResult<()> {
conn.execute(
"CREATE TABLE person (
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
)",
params![],
)?;
table_name
)
.as_str(),
params![],
)?;

conn.execute(
"INSERT INTO person (name, time_created, data, data_null)
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(())
}
let conn = setup_conn();
setup_db_structure(&conn)?;
Ok((conn, "person".to_string()))
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(conn: PooledConnection<SqliteConnectionManager>, table_name: &String) -> SRResult<()>{
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(())
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(())
}

Loading…
Cancel
Save