Created
February 19, 2020 17:44
-
-
Save ayourtch/552e614174915e794c8d0307aa10ce16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate chrono; | |
extern crate diesel; | |
use super::flextimestamp::FlexTimestamp; | |
use super::flexuuid::FlexUuid; | |
use super::models; | |
use super::schema; | |
use diesel::pg::PgConnection; | |
use diesel::prelude::*; | |
use diesel::sqlite::SqliteConnection; | |
use dotenv::dotenv; | |
use std::env; | |
pub enum DbConnection { | |
SqliteConn(SqliteConnection), | |
PostgresConn(PgConnection), | |
} | |
pub fn db_get_conn() -> DbConnection { | |
dotenv().ok(); | |
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); | |
let ret = if database_url.starts_with("postgres://") { | |
let conn = PgConnection::establish(&database_url).expect(&format!( | |
"Error connecting to {} (using PostgreSQL)", | |
database_url | |
)); | |
DbConnection::PostgresConn(conn) | |
} else { | |
let conn = SqliteConnection::establish(&database_url).expect(&format!( | |
"Error connecting to {} (using Sqlite3)", | |
database_url | |
)); | |
DbConnection::SqliteConn(conn) | |
}; | |
ret | |
} | |
macro_rules! multidb_run { | |
($dbc: expr, $what: expr, $action: tt, $errmsg: expr) => { | |
match $dbc { | |
DbConnection::SqliteConn(sqlite_conn) => ($what).$action(sqlite_conn).expect($errmsg), | |
DbConnection::PostgresConn(pg_conn) => ($what).$action(pg_conn).expect($errmsg), | |
} | |
}; | |
} | |
macro_rules! define_db_insert { | |
($fnname: ident, $tblname: ident, $itemtype: ident) => { | |
pub fn $fnname(dbc: &DbConnection, new_item: &models::$itemtype) -> usize { | |
let new_item = crate::models::$itemtype { | |
UpdatedAt: FlexTimestamp::now(), | |
..new_item.clone() | |
}; | |
multidb_run!( | |
dbc, | |
diesel::insert_into(schema::$tblname::table).values(&new_item), | |
execute, | |
&format!("Error saving new {} - {:?}", stringify!($itemtype), new_item) | |
) | |
} | |
}; | |
} | |
define_db_insert!(db_insert_post, Posts, NewPost); | |
define_db_insert!(db_insert_comment, Comments, NewComment); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment