Skip to content

Commit e543e8f

Browse files
committed
Add SQLite Support for Testing
1 parent 6f12db1 commit e543e8f

File tree

7 files changed

+61
-10
lines changed

7 files changed

+61
-10
lines changed

.env.sample

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
APP_HOST=localhost
22
APP_PORT=8000
3-
DATABASE_URL=postgres://username:password@server/db_name
3+
# For Postgres
4+
DATABASE_URL=postgres://username:password@server/db_name
5+
# For SQLite
6+
DATABASE_URL=file://path/to/database/file.db

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,7 @@ features = ["serde"]
3333
[dependencies.uuid]
3434
version = "0.8.1"
3535
features = ["v4"]
36+
37+
[dev-dependencies.diesel]
38+
version = "1.4.5"
39+
features = ["sqlite", "r2d2", "chrono"]

rustfmt.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
reorder_imports = true

src/config/db.rs

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,62 @@
1+
#[allow(unused_imports)]
12
use diesel::{
23
pg::PgConnection,
4+
sqlite::SqliteConnection,
5+
sql_query,
36
r2d2::{self, ConnectionManager},
47
};
58

69
embed_migrations!();
710

11+
#[cfg(not(test))]
812
pub type Connection = PgConnection;
13+
14+
#[cfg(test)]
15+
pub type Connection = SqliteConnection;
16+
917
pub type Pool = r2d2::Pool<ConnectionManager<Connection>>;
1018

19+
#[cfg(not(test))]
1120
pub fn migrate_and_config_db(url: &str) -> Pool {
12-
info!("Migrating and configurating database...");
21+
info!("Migrating and configurating database...");
1322
let manager = ConnectionManager::<Connection>::new(url);
1423
let pool = r2d2::Pool::builder().build(manager).expect("Failed to create pool.");
1524
embedded_migrations::run(&pool.get().expect("Failed to migrate."));
1625

1726
pool
1827
}
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+
}

src/main.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,6 @@ async fn main() -> io::Result<()> {
5252
let app_url = format!("{}:{}", &app_host, &app_port);
5353
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL not found.");
5454

55-
let pool = config::db::migrate_and_config_db(&db_url);
56-
5755
HttpServer::new(move || {
5856
App::new()
5957
.wrap(Cors::new() // allowed_origin return access-control-allow-origin: * by default
@@ -64,7 +62,7 @@ async fn main() -> io::Result<()> {
6462
.allowed_header(http::header::CONTENT_TYPE)
6563
.max_age(3600)
6664
.finish())
67-
.data(pool.clone())
65+
.data(config::db::migrate_and_config_db(&db_url))
6866
.wrap(actix_web::middleware::Logger::default())
6967
.wrap(crate::middleware::authen_middleware::Authentication)
7068
.wrap_fn(|req, srv| {

src/models/login_history.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::{
33
models::user::User,
44
schema::login_history::{self, dsl::*},
55
};
6-
use chrono::{DateTime, Utc};
6+
use chrono::{NaiveDateTime, Utc};
77
use diesel::prelude::*;
88

99
#[derive(Identifiable, Associations, Queryable)]
@@ -12,22 +12,23 @@ use diesel::prelude::*;
1212
pub struct LoginHistory {
1313
pub id: i32,
1414
pub user_id: i32,
15-
pub login_timestamp: DateTime<Utc>,
15+
pub login_timestamp: NaiveDateTime,
1616
}
1717

1818
#[derive(Insertable)]
1919
#[table_name = "login_history"]
2020
pub struct LoginHistoryInsertableDTO {
2121
pub user_id: i32,
22-
pub login_timestamp: DateTime<Utc>,
22+
pub login_timestamp: NaiveDateTime,
2323
}
2424

2525
impl LoginHistory {
2626
pub fn create(un: &str, conn: &Connection) -> Option<LoginHistoryInsertableDTO> {
2727
if let Ok(user) = User::find_user_by_username(un, conn) {
28+
let now = Utc::now();
2829
Some(LoginHistoryInsertableDTO {
2930
user_id: user.id,
30-
login_timestamp: Utc::now(),
31+
login_timestamp: now.naive_utc(),
3132
})
3233
} else {
3334
None

src/schema.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ table! {
22
login_history (id) {
33
id -> Int4,
44
user_id -> Int4,
5-
login_timestamp -> Timestamptz,
5+
login_timestamp -> Timestamp,
66
}
77
}
88

0 commit comments

Comments
 (0)