rustyroad 1.0.29

Rusty Road is a framework written in Rust that is based on Ruby on Rails. It is designed to provide the familiar conventions and ease of use of Ruby on Rails, while also taking advantage of the performance and efficiency of Rust.
Documentation
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::database::{get_mysql_pool, get_pg_pool, get_sqlite_pool};
use crate::writers::create_database_if_not_exists;
use sqlx::mysql::{MySqlConnectOptions, MySqlPool};
use sqlx::postgres::{PgConnectOptions, PgPool};
use sqlx::sqlite::SqlitePool;
use std::error::Error;
use std::fs;
use std::io;
use std::sync::Arc;
use toml::Value;

use super::databasetype::DatabaseType;

/// Get the current environment, checking both ENVIRONMENT and ENV variables.
/// Returns "dev" if neither is set.
///
/// This allows users to use either:
/// - `ENVIRONMENT=prod rustyroad ...`
/// - `ENV=prod rustyroad ...`
///
/// If both are set, ENVIRONMENT wins because it is the explicit form.
pub fn get_environment() -> String {
    std::env::var("ENVIRONMENT")
        .or_else(|_| std::env::var("ENV"))
        .unwrap_or_else(|_| "dev".to_string())
}

/// Get the RustyRoad config filename for the active environment.
pub fn get_config_file_name() -> String {
    let environment = get_environment();
    if environment == "dev" {
        "rustyroad.toml".to_string()
    } else {
        format!("rustyroad.{}.toml", environment)
    }
}

#[derive(Debug, Clone)]
pub struct Database {
    pub name: String,
    pub username: String,
    pub password: String,
    pub host: String,
    pub port: u16,
    pub database_type: DatabaseType,
}

#[derive(Debug, Clone)]
pub enum DatabaseConnection {
    Pg(Arc<PgPool>),
    MySql(Arc<MySqlPool>),
    Sqlite(Arc<SqlitePool>),
}

/// # Name: Database
/// ## Description
/// Struct representing a database connection configuration.
/// ## Fields
/// * `name` - The name of the database.
/// * `username` - The username for the database connection.
/// * `password` - The password for the database connection.
/// * `host` - The host where the database is located.
/// * `port` - The port on which the database is running.
/// * `database_type` - The type of the database (e.g., MySQL, PostgreSQL, SQLite).
/// ## Example
/// ```
/// use rustyroad::database::Database;
/// let db = Database::new(
///     "my_database".to_string(),
///    "my_user".to_string(),
///   "my_password".to_string(),
///   "localhost".to_string(),
///  5432,
/// "postgres",
/// );
/// ```
impl Database {
    /// # Name: new
    /// ## Description
    /// Creates a new instance of the `Database` struct.
    /// ## Arguments
    /// * `name` - The name of the database.
    /// * `username` - The username for the database connection.
    /// * `password` - The password for the database connection.
    /// * `host` - The host where the database is located.
    /// * `port` - The port on which the database is running.
    /// * `database_type` - The type of the database (e.g., "postgres", "mysql", "sqlite").
    /// ## Returns
    /// * `Database` - A new instance of the `Database` struct.
    /// ## Example
    /// ```rust
    /// use rustyroad::database::Database;
    /// let db = Database::new(
    ///    "my_database".to_string(),
    ///    "my_user".to_string(),
    ///    "my_password".to_string(),
    ///    "localhost".to_string(),
    ///    5432,
    ///    "postgres",
    /// );
    /// ```
    pub fn new(
        name: String,
        username: String,
        password: String,
        host: String,
        port: u16,
        database_type: &str,
    ) -> Database {
        Database {
            name,
            username,
            password,
            host,
            port,
            database_type: match database_type {
                "postgres" => DatabaseType::Postgres,
                "mysql" => DatabaseType::Mysql,
                "sqlite" => DatabaseType::Sqlite,
                _ => DatabaseType::Mysql,
            },
        }
    }

    /// # Name: create_database_connection
    /// ## Description
    /// Creates a database connection based on the database type.
    /// ## Returns
    /// * `Result<DatabaseConnection, Box<dyn Error + Send>>` - A result containing the database connection or an error.
    /// ## Example
    /// ```rust
    /// use rustyroad::database::Database;
    /// let db = Database::new(
    ///   "my_database".to_string(),
    ///   "my_user".to_string(),
    ///   "my_password".to_string(),
    ///   "localhost".to_string(),
    ///   5432,
    ///   "postgres",
    /// );
    /// let connection = db.create_database_connection().await.unwrap();
    /// ```
    pub async fn create_database_connection(
        &self,
    ) -> Result<DatabaseConnection, Box<dyn Error + Send>> {
        match &self.database_type {
            DatabaseType::Mysql => {
                let options = MySqlConnectOptions::new()
                    .username(&self.username)
                    .password(&self.password)
                    .database(&self.name)
                    .host(&self.host)
                    .port(self.port);
                let pool = MySqlPool::connect_with(options).await.unwrap_or_else(|e| {
                    panic!(
                        "Failed to create MySQL connection pool.\n\n\
                        Config: rustyroad.toml [database] section\n\
                        Host: {}:{}\n\
                        Database: {}\n\
                        User: {}\n\n\
                        Check that MySQL is running and credentials are correct.\n\n\
                        Original error: {}",
                        self.host, self.port, self.name, self.username, e
                    )
                });
                Ok(DatabaseConnection::MySql(Arc::new(pool)))
            }
            DatabaseType::Sqlite => {
                let pool = SqlitePool::connect(&format!("{}.db", self.name))
                    .await
                    .unwrap_or_else(|e| {
                        panic!(
                            "Could not connect to SQLite database at '{}.db'.\n\n\
                        Ensure the file exists and is readable, or check permissions.\n\n\
                        Original error: {}",
                            self.name, e
                        )
                    });
                Ok(DatabaseConnection::Sqlite(Arc::new(pool)))
            }
            DatabaseType::Postgres => {
                let database: Database = Database::get_database_from_rustyroad_toml().unwrap();
                let name = database.name.clone();
                let username = database.username.clone();
                let host = database.host.clone();
                let port = database.port;
                let admin_database_url = format!(
                    "postgres://{}:{}@{}:{}/postgres",
                    username, database.password, host, port,
                );
                create_database_if_not_exists(admin_database_url.as_str(), database)
                    .await
                    .unwrap_or_else(|e| panic!(
                        "Failed to create PostgreSQL database '{}'.\n\n\
                        Admin URL: postgres://{}:***@{}:{}/postgres\n\
                        Config: rustyroad.toml\n\n\
                        Ensure PostgreSQL is running and the admin credentials can create databases.\n\n\
                        Original error: {}",
                        name, username, host, port, e
                    ));

                let options = PgConnectOptions::new()
                    .username(&self.username)
                    .password(&self.password)
                    .database(&self.name)
                    .host(&self.host)
                    .port(self.port);
                let pool = PgPool::connect_with(options).await.unwrap_or_else(|e| {
                    panic!(
                        "Failed to create PostgreSQL connection pool for '{}' at {}:{}.\n\n\
                        Config file: rustyroad.toml\n\n\
                        Original error: {}",
                        self.name, self.host, self.port, e
                    )
                });

                Ok(DatabaseConnection::Pg(Arc::new(pool)))
            }
            DatabaseType::Mongo => todo!(),
        }
    }

    /// # Name: get_database_from_rustyroad_toml
    /// ## Description
    /// Reads the database configuration from the `rustyroad.toml` file based on the current environment.
    /// ## Returns
    /// * `Result<Database, std::io::Error>` - A result containing the `Database` struct or an error if the file could not be read.
    /// ## Example
    /// ```rust
    /// use rustyroad::database::Database;
    /// let database = Database::get_database_from_rustyroad_toml().unwrap();
    /// ```
    pub fn get_database_from_rustyroad_toml() -> Result<Database, std::io::Error> {
        let file_name = get_config_file_name();

        let file = fs::read_to_string(&file_name).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!(
                    "RustyRoad could not read '{file_name}'.\n\nRun this command from your project root (the folder containing '{file_name}').\nIf you haven't created a project yet, run: rustyroad new <project_name>\n\nOriginal error: {e}",
                ),
            )
        })?;

        let toml: Value = toml::from_str(&file).map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "Failed to parse '{file_name}'.\n\nMake sure it contains a [database] section.\n\nOriginal error: {e}",
                ),
            )
        })?;

        let database_table = toml
            .get("database")
            .and_then(|v| v.as_table())
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "'{file_name}' is missing a [database] section.\n\nExpected something like:\n\n[database]\ndatabase_name = \"my_db\"\ndatabase_user = \"user\"\ndatabase_password = \"pass\"\ndatabase_host = \"localhost\"\ndatabase_port = \"5432\"\ndatabase_type = \"postgres\"\n",
                    ),
                )
            })?;

        let get_required = |key: &str| -> Result<&str, io::Error> {
            database_table
                .get(key)
                .and_then(|v| v.as_str())
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!(
                            "'{file_name}' is missing [database].{key}.\n\nSee README for the expected rustyroad.toml format.",
                        ),
                    )
                })
        };

        let database_name = get_required("database_name")?.to_string();
        let database_user = get_required("database_user")?.to_string();
        let database_password = get_required("database_password")?.to_string();
        let database_host = get_required("database_host")?.to_string();
        let database_port_raw = get_required("database_port")?;
        let database_port = database_port_raw.parse::<u16>().map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "'{file_name}' has an invalid [database].database_port value '{database_port_raw}'. Expected a number like '5432'.\n\nOriginal error: {e}",
                ),
            )
        })?;
        let database_type = get_required("database_type")?;

        Ok(Database::new(
            database_name,
            database_user,
            database_password,
            database_host,
            database_port,
            database_type,
        ))
    }

    /// # Name: get_db_pool
    /// Description: Returns a database connection pool based on the database type.
    ///
    /// # Arguments
    /// * `database` - Database struct
    ///
    /// # Returns
    /// * `DatabaseConnection` - Database connection pool
    ///
    /// # Example
    /// ```
    /// use rustyroad::database::Database;
    /// let database = Database::get_database_from_rustyroad_toml().unwrap();
    /// let db_pool = database.get_db_pool(database).unwrap();
    /// ```
    pub async fn get_db_pool(database: Database) -> Result<PoolConnection, Box<dyn Error + Send>> {
        match database.database_type {
            DatabaseType::Mysql => {
                let pool = get_mysql_pool(&database)
                    .await
                    .expect("Error getting mysql pool");
                Ok(PoolConnection::MySql(pool))
            }
            DatabaseType::Sqlite => {
                let pool = get_sqlite_pool(&database)
                    .await
                    .expect("Error getting sqlite pool");
                Ok(PoolConnection::Sqlite(pool))
            }
            DatabaseType::Postgres => {
                let pool = get_pg_pool(&database).await.expect("Error getting pg pool");
                Ok(PoolConnection::Pg(pool))
            }
            DatabaseType::Mongo => todo!(),
        }
    }
}

/// # Name: PoolConnection
/// ## Description
/// Enum representing different types of database connection pools.
/// ## Variants
/// * `Pg` - PostgreSQL connection pool.
/// * `MySql` - MySQL connection pool.
/// * `Sqlite` - SQLite connection pool.
/// ## Example
/// ```rust
/// use rustyroad::database::PoolConnection;
/// let pg_pool: PoolConnection = PoolConnection::Pg(sqlx::PgPool::connect("postgres://user:password@localhost/dbname").await.unwrap());
/// let mysql_pool: PoolConnection = PoolConnection::MySql(sqlx::MySqlPool::connect("mysql://user:password@localhost/dbname").await.unwrap());
/// let sqlite_pool: PoolConnection = PoolConnection::Sqlite(sqlx::SqlitePool::connect("sqlite://my_database.db").await.unwrap());
/// ```
#[derive(Debug, Clone)]
pub enum PoolConnection {
    Pg(sqlx::PgPool),
    MySql(sqlx::MySqlPool),
    Sqlite(sqlx::SqlitePool),
}

#[cfg(test)]
mod tests {
    use super::{get_config_file_name, get_environment};
    use std::sync::{Mutex, OnceLock};

    struct EnvGuard {
        env: Option<String>,
        environment: Option<String>,
    }

    impl EnvGuard {
        fn capture() -> Self {
            Self {
                env: std::env::var("ENV").ok(),
                environment: std::env::var("ENVIRONMENT").ok(),
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            restore_var("ENV", self.env.as_deref());
            restore_var("ENVIRONMENT", self.environment.as_deref());
        }
    }

    fn restore_var(key: &str, value: Option<&str>) {
        unsafe {
            match value {
                Some(value) => std::env::set_var(key, value),
                None => std::env::remove_var(key),
            }
        }
    }

    fn env_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    #[test]
    fn defaults_to_dev_when_no_environment_is_set() {
        let _lock = env_lock().lock().unwrap();
        let _guard = EnvGuard::capture();

        unsafe {
            std::env::remove_var("ENV");
            std::env::remove_var("ENVIRONMENT");
        }

        assert_eq!(get_environment(), "dev");
        assert_eq!(get_config_file_name(), "rustyroad.toml");
    }

    #[test]
    fn falls_back_to_env_shorthand_when_environment_is_absent() {
        let _lock = env_lock().lock().unwrap();
        let _guard = EnvGuard::capture();

        unsafe {
            std::env::set_var("ENV", "prod");
            std::env::remove_var("ENVIRONMENT");
        }

        assert_eq!(get_environment(), "prod");
        assert_eq!(get_config_file_name(), "rustyroad.prod.toml");
    }

    #[test]
    fn prefers_explicit_environment_over_env_shorthand() {
        let _lock = env_lock().lock().unwrap();
        let _guard = EnvGuard::capture();

        unsafe {
            std::env::set_var("ENV", "dev");
            std::env::set_var("ENVIRONMENT", "prod");
        }

        assert_eq!(get_environment(), "prod");
        assert_eq!(get_config_file_name(), "rustyroad.prod.toml");
    }
}