@@ -0,0 +1,86 @@
|
||||
pub mod models;
|
||||
pub mod schema;
|
||||
|
||||
use diesel::prelude::*;
|
||||
use diesel::connection::SimpleConnection;
|
||||
use diesel::r2d2::{ConnectionManager, CustomizeConnection, Pool};
|
||||
use std::env;
|
||||
use models::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Fuck ();
|
||||
|
||||
fn init_conn (conn : &mut SqliteConnection) -> Result<(), diesel::r2d2::Error> {
|
||||
conn.batch_execute ("
|
||||
PRAGMA busy_timeout = 15000;
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
PRAGMA wal_autocheckpoint = 1000;
|
||||
PRAGMA wal_checkpoint(TRUNCATE);
|
||||
PRAGMA cache_size=-2000000
|
||||
")?;
|
||||
Ok (())
|
||||
}
|
||||
|
||||
impl CustomizeConnection<SqliteConnection, diesel::r2d2::Error> for Fuck {
|
||||
fn on_acquire (&self, conn : &mut SqliteConnection) -> Result<
|
||||
(), diesel::r2d2::Error
|
||||
> {
|
||||
init_conn (conn)
|
||||
}
|
||||
|
||||
fn on_release (&self, _conn: SqliteConnection) {}
|
||||
}
|
||||
|
||||
pub fn get_pool () -> Pool<ConnectionManager<SqliteConnection>> {
|
||||
let url = env::var ("DATABASE_URL")
|
||||
.expect ("DATABASE_URL must be set");
|
||||
let manager = ConnectionManager::<SqliteConnection>::new (url);
|
||||
Pool::builder ()
|
||||
.connection_customizer (Box::new (Fuck ()))
|
||||
.test_on_check_out (true)
|
||||
.build (manager)
|
||||
.expect ("Could not build connection pool")
|
||||
}
|
||||
|
||||
pub fn connect () -> SqliteConnection {
|
||||
let database_url = env::var ("DATABASE_URL")
|
||||
.expect ("DATABASE_URL must be set");
|
||||
let mut conn = SqliteConnection::establish (&database_url)
|
||||
.unwrap_or_else (|_| panic! ("Error connecting to {}", database_url));
|
||||
init_conn (&mut conn).unwrap ();
|
||||
conn
|
||||
}
|
||||
|
||||
pub fn get_word (w : &str) -> Vec<Word> {
|
||||
let conn = &mut connect ();
|
||||
use schema::words::dsl::*;
|
||||
words
|
||||
.filter (word.eq (w))
|
||||
.select (Word::as_select ())
|
||||
.load (conn)
|
||||
.expect ("error loading words")
|
||||
}
|
||||
|
||||
pub fn entry_as_word (entry : &serde_json::Value) -> Option<&str> {
|
||||
entry.get ("word")?.as_str ()
|
||||
}
|
||||
|
||||
pub fn insert_word (
|
||||
conn : &mut SqliteConnection,
|
||||
info : &serde_json::Value,
|
||||
) -> Option<()> {
|
||||
use schema::words;
|
||||
let word = entry_as_word (info)?;
|
||||
let new_word = NewWord { word, info };
|
||||
diesel::insert_into (words::table)
|
||||
.values (new_word)
|
||||
.execute (conn).map_or_else (
|
||||
|e| {
|
||||
println! ("error for {}: {}", word, e);
|
||||
None
|
||||
},
|
||||
Some
|
||||
)?;
|
||||
Some (())
|
||||
}
|
||||
Reference in New Issue
Block a user