forked from alexjustesen/speedtest-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.rs
More file actions
75 lines (68 loc) · 2.28 KB
/
Copy pathdb.rs
File metadata and controls
75 lines (68 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[cfg(feature = "mysql")]
use sqlx::MySql;
use sqlx::Pool;
#[cfg(feature = "postgres")]
use sqlx::Postgres;
#[cfg(feature = "sqlite")]
use sqlx::Sqlite;
#[cfg(not(any(feature = "sqlite", feature = "mysql", feature = "postgres")))]
compile_error!(
"At least one of the features \"sqlite\", \"mysql\", or \"postgres\" must be enabled."
);
#[derive(Clone)]
pub enum Database {
#[cfg(feature = "sqlite")]
Sqlite(Pool<Sqlite>),
#[cfg(feature = "mysql")]
MySql(Pool<MySql>),
#[cfg(feature = "postgres")]
Postgres(Pool<Postgres>),
}
impl Database {
pub async fn connect(database_url: &str) -> Result<Self, sqlx::Error> {
#[cfg(feature = "sqlite")]
if database_url.starts_with("sqlite") {
let pool = sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(5)
.connect(database_url)
.await?;
return Ok(Database::Sqlite(pool));
}
#[cfg(feature = "mysql")]
if database_url.starts_with("mysql") {
let pool = sqlx::mysql::MySqlPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await?;
return Ok(Database::MySql(pool));
}
#[cfg(feature = "postgres")]
if database_url.starts_with("postgres") {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await?;
return Ok(Database::Postgres(pool));
}
panic!(
"Database URL '{database_url}' not supported or feature not enabled. Enable the corresponding feature: sqlite, mysql, or postgres"
);
}
pub async fn run_migrations(&self) -> Result<(), sqlx::Error> {
match self {
#[cfg(feature = "sqlite")]
Database::Sqlite(pool) => {
sqlx::migrate!("./migrations").run(pool).await?;
}
#[cfg(feature = "mysql")]
Database::MySql(pool) => {
sqlx::migrate!("./migrations").run(pool).await?;
}
#[cfg(feature = "postgres")]
Database::Postgres(pool) => {
sqlx::migrate!("./migrations").run(pool).await?;
}
}
Ok(())
}
}