use diesel::prelude::*; use diesel::connection::SimpleConnection; use diesel::r2d2::{ConnectionManager, CustomizeConnection, Pool}; use std::env; use crate::models::*; #[derive(Debug)] pub struct Fuck (); impl CustomizeConnection for Fuck { fn on_acquire (&self, 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 ").unwrap (); Ok (()) } fn on_release (&self, _conn: SqliteConnection) {} } pub fn get_pool () -> Pool> { let url = env::var ("DATABASE_URL") .expect ("DATABASE_URL must be set"); let manager = ConnectionManager::::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)); conn.batch_execute (" PRAGMA journal_mode = WAL; -- better write-concurrency PRAGMA synchronous = NORMAL; -- fsync only in critical moments PRAGMA wal_autocheckpoint = 1000; -- write WAL changes back every 1000 pages, for an in average 1MB WAL file. May affect readers if number is increased PRAGMA wal_checkpoint(TRUNCATE); -- free some space by truncating possibly massive WAL files from the last run. PRAGMA busy_timeout = 5000; -- sleep if the database is busy PRAGMA cache_size=-2000000 ").unwrap (); conn } pub fn get_word (w : &str) -> Vec { let conn = &mut connect (); use crate::schema::words::dsl::*; let results = words .filter (word.eq (w)) .limit (5) .select (Word::as_select ()) .load (conn) .expect ("error loading words"); for wd in results { println! ("{}", wd.word); } todo! () } pub fn entry_as_word (entry : &serde_json::Value) -> Option<&str> { entry.get ("word")?.as_str () } pub fn insert_word ( conn : &mut SqliteConnection, entry : serde_json::Value, ) -> Option<()> { use crate::schema::words; let word = entry_as_word (&entry)?; let new_word = NewWord { word, info: &entry.to_string (), }; diesel::insert_into (words::table) .values (new_word) .execute (conn).map_or_else ( |e| { println! ("error for {}: {}", word, e); None }, Some )?; Some (()) }