torrust_tracker/core/databases/
driver.rs

1//! Database driver factory.
2//!
3//! See [`databases::driver::build`](crate::core::databases::driver::build)
4//! function for more information.
5use serde::{Deserialize, Serialize};
6
7use super::error::Error;
8use super::mysql::Mysql;
9use super::sqlite::Sqlite;
10use super::{Builder, Database};
11
12/// The database management system used by the tracker.
13///
14/// Refer to:
15///
16/// - [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration).
17/// - [Torrust Tracker](https://docs.rs/torrust-tracker).
18///
19/// For more information about persistence.
20#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)]
21pub enum Driver {
22    /// The Sqlite3 database driver.
23    Sqlite3,
24    /// The `MySQL` database driver.
25    MySQL,
26}
27
28/// It builds a new database driver.
29///
30/// Example for `SQLite3`:
31///
32/// ```rust,no_run
33/// use torrust_tracker::core::databases;
34/// use torrust_tracker::core::databases::driver::Driver;
35///
36/// let db_driver = Driver::Sqlite3;
37/// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string();
38/// let database = databases::driver::build(&db_driver, &db_path);
39/// ```
40///
41/// Example for `MySQL`:
42///
43/// ```rust,no_run
44/// use torrust_tracker::core::databases;
45/// use torrust_tracker::core::databases::driver::Driver;
46///
47/// let db_driver = Driver::MySQL;
48/// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string();
49/// let database = databases::driver::build(&db_driver, &db_path);
50/// ```
51///
52/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration)
53/// for more information about the database configuration.
54///
55/// > **WARNING**: The driver instantiation runs database migrations.
56///
57/// # Errors
58///
59/// This function will return an error if unable to connect to the database.
60///
61/// # Panics
62///
63/// This function will panic if unable to create database tables.
64pub fn build(driver: &Driver, db_path: &str) -> Result<Box<dyn Database>, Error> {
65    let database = match driver {
66        Driver::Sqlite3 => Builder::<Sqlite>::build(db_path),
67        Driver::MySQL => Builder::<Mysql>::build(db_path),
68    }?;
69
70    database.create_database_tables().expect("Could not create database tables.");
71
72    Ok(database)
73}