|
| 1 | +#[allow(unused_imports)] |
1 | 2 | use diesel::{ |
2 | 3 | pg::PgConnection, |
| 4 | + sqlite::SqliteConnection, |
| 5 | + sql_query, |
3 | 6 | r2d2::{self, ConnectionManager}, |
4 | 7 | }; |
5 | 8 |
|
6 | 9 | embed_migrations!(); |
7 | 10 |
|
| 11 | +#[cfg(not(test))] |
8 | 12 | pub type Connection = PgConnection; |
| 13 | + |
| 14 | +#[cfg(test)] |
| 15 | +pub type Connection = SqliteConnection; |
| 16 | + |
9 | 17 | pub type Pool = r2d2::Pool<ConnectionManager<Connection>>; |
10 | 18 |
|
| 19 | +#[cfg(not(test))] |
11 | 20 | pub fn migrate_and_config_db(url: &str) -> Pool { |
12 | | - info!("Migrating and configurating database..."); |
| 21 | + info!("Migrating and configurating database..."); |
13 | 22 | let manager = ConnectionManager::<Connection>::new(url); |
14 | 23 | let pool = r2d2::Pool::builder().build(manager).expect("Failed to create pool."); |
15 | 24 | embedded_migrations::run(&pool.get().expect("Failed to migrate.")); |
16 | 25 |
|
17 | 26 | pool |
18 | 27 | } |
| 28 | + |
| 29 | +#[cfg(test)] |
| 30 | +pub fn migrate_and_config_db(url: &str) -> Pool { |
| 31 | + use crate::diesel::RunQueryDsl; |
| 32 | + info!("Migrating and configurating database..."); |
| 33 | + let manager = ConnectionManager::<Connection>::new(url); |
| 34 | + let pool = r2d2::Pool::builder().build(manager).expect("Failed to create pool."); |
| 35 | + |
| 36 | + sql_query(r#"DROP TABLE IF EXISTS login_history;"#).execute(&pool.get().unwrap()); |
| 37 | + sql_query(r#"DROP TABLE IF EXISTS users;"#).execute(&pool.get().unwrap()); |
| 38 | + sql_query(r#"DROP TABLE IF EXISTS people;"#).execute(&pool.get().unwrap()); |
| 39 | + sql_query(r#"CREATE TABLE people ( |
| 40 | + id INTEGER PRIMARY KEY NOT NULL, |
| 41 | + name TEXT NOT NULL, |
| 42 | + gender BOOLEAN NOT NULL, |
| 43 | + age INTEGER NOT NULL, |
| 44 | + address TEXT NOT NULL, |
| 45 | + phone TEXT NOT NULL, |
| 46 | + email TEXT NOT NULL |
| 47 | + );"#).execute(&pool.get().unwrap()); |
| 48 | + sql_query(r#"CREATE TABLE users ( |
| 49 | + id INTEGER PRIMARY KEY NOT NULL, |
| 50 | + username TEXT NOT NULL, |
| 51 | + email TEXT NOT NULL, |
| 52 | + password TEXT NOT NULL, |
| 53 | + login_session TEXT NOT NULL DEFAULT '' |
| 54 | + );"#).execute(&pool.get().unwrap()); |
| 55 | + sql_query(r#"CREATE TABLE login_history ( |
| 56 | + id INTEGER PRIMARY KEY NOT NULL, |
| 57 | + user_id INTEGER NOT NULL REFERENCES users(id), |
| 58 | + login_timestamp INTEGER NOT NULL |
| 59 | + );"#).execute(&pool.get().unwrap()); |
| 60 | + |
| 61 | + pool |
| 62 | +} |
0 commit comments