|
| 1 | +use crate::*; |
| 2 | + |
| 3 | +pub async fn get_db_connection() -> DbPoolConnection { |
| 4 | + let db_pool: DbPoolConnection = DB.read().await.clone().unwrap(); |
| 5 | + db_pool |
| 6 | +} |
| 7 | + |
| 8 | +pub async fn create_batabase() { |
| 9 | + let db_pool: DbPoolConnection = get_db_connection().await; |
| 10 | + let connection: DbConnection = db_pool.get().await.unwrap(); |
| 11 | + let db_exists: bool = connection |
| 12 | + .query_one( |
| 13 | + "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1);", |
| 14 | + &[&DATABASE_NAME], |
| 15 | + ) |
| 16 | + .await |
| 17 | + .unwrap() |
| 18 | + .get(0); |
| 19 | + if !db_exists { |
| 20 | + println_warning!( |
| 21 | + "database `", |
| 22 | + DATABASE_NAME, |
| 23 | + "` not found. Creating database..." |
| 24 | + ); |
| 25 | + connection |
| 26 | + .batch_execute(&format!("CREATE DATABASE {};", DATABASE_NAME)) |
| 27 | + .await |
| 28 | + .unwrap(); |
| 29 | + println_success!("database `", DATABASE_NAME, "` created successfully"); |
| 30 | + } |
| 31 | + println_success!("database `", DATABASE_NAME, "` ready"); |
| 32 | +} |
| 33 | + |
| 34 | +pub async fn create_table() { |
| 35 | + let db_pool: DbPoolConnection = get_db_connection().await; |
| 36 | + let connection: DbConnection = db_pool.get().await.unwrap(); |
| 37 | + connection |
| 38 | + .batch_execute(&format!( |
| 39 | + "CREATE TABLE IF NOT EXISTS {} ( |
| 40 | + id SERIAL PRIMARY KEY, |
| 41 | + randomNumber INTEGER NOT NULL |
| 42 | + );", |
| 43 | + TABLE_NAME |
| 44 | + )) |
| 45 | + .await |
| 46 | + .unwrap(); |
| 47 | + println_success!("table `", TABLE_NAME, "` ready"); |
| 48 | +} |
| 49 | + |
| 50 | +pub async fn insert_records() { |
| 51 | + let db_pool: DbPoolConnection = get_db_connection().await; |
| 52 | + let connection: DbConnection = db_pool.get().await.unwrap(); |
| 53 | + let row: Row = connection |
| 54 | + .query_one(&format!("SELECT COUNT(*) FROM {}", TABLE_NAME), &[]) |
| 55 | + .await |
| 56 | + .unwrap(); |
| 57 | + let count: i64 = row.get(0); |
| 58 | + let limit: i64 = ROW_LIMIT as i64; |
| 59 | + if count >= limit { |
| 60 | + println_warning!(format!( |
| 61 | + "table '{}' already has {} records. No need to insert.", |
| 62 | + TABLE_NAME, count |
| 63 | + )); |
| 64 | + return; |
| 65 | + } |
| 66 | + let missing_count: i64 = limit - count; |
| 67 | + println_warning!(format!( |
| 68 | + "table '{}' has {} records. Inserting {} missing records...", |
| 69 | + TABLE_NAME, count, missing_count |
| 70 | + )); |
| 71 | + let mut rng: rand::prelude::ThreadRng = rand::rng(); |
| 72 | + let mut values: Vec<String> = Vec::new(); |
| 73 | + for _ in 0..missing_count { |
| 74 | + let random_number: i32 = rng.random_range(1..=10000); |
| 75 | + values.push(format!("(DEFAULT, {})", random_number)); |
| 76 | + } |
| 77 | + let query: String = format!( |
| 78 | + "INSERT INTO {} (id, randomNumber) VALUES {}", |
| 79 | + TABLE_NAME, |
| 80 | + values.join(",") |
| 81 | + ); |
| 82 | + connection.batch_execute(&query).await.unwrap(); |
| 83 | + println_success!(format!( |
| 84 | + "successfully inserted {} missing records into '{}' table.", |
| 85 | + TABLE_NAME, missing_count |
| 86 | + )); |
| 87 | +} |
| 88 | + |
| 89 | +pub async fn init_db() { |
| 90 | + let db_url: &str = match option_env!("POSTGRES_URL") { |
| 91 | + Some(it) => it, |
| 92 | + _ => &format!( |
| 93 | + "{}://{}:{}@{}:{}/{}", |
| 94 | + DATABASE_TYPE, |
| 95 | + DATABASE_USER_NAME, |
| 96 | + DATABASE_USER_PASSWORD, |
| 97 | + DATABASE_HOST, |
| 98 | + DATABASE_PORT, |
| 99 | + DATABASE_NAME |
| 100 | + ), |
| 101 | + }; |
| 102 | + println_warning!("db url: ", db_url); |
| 103 | + let config: Config = db_url.parse::<Config>().unwrap(); |
| 104 | + let db_manager: PostgresConnectionManager<NoTls> = |
| 105 | + PostgresConnectionManager::new(config, NoTls); |
| 106 | + let db_pool: DbPoolConnection = Pool::builder().build(db_manager).await.unwrap(); |
| 107 | + { |
| 108 | + let mut db_pool_lock: RwLockWriteGuard<'_, Option<DbPoolConnection>> = DB.write().await; |
| 109 | + *db_pool_lock = Some(db_pool.clone()); |
| 110 | + } |
| 111 | + create_batabase().await; |
| 112 | + create_table().await; |
| 113 | + insert_records().await; |
| 114 | +} |
| 115 | + |
| 116 | +pub async fn random_world_row() -> Result<QueryRow, Box<dyn std::error::Error>> { |
| 117 | + let random_id: i32 = rand::rng().random_range(1..ROW_LIMIT); |
| 118 | + let db_pool: DbPoolConnection = get_db_connection().await; |
| 119 | + let connection: DbConnection = db_pool |
| 120 | + .get() |
| 121 | + .await |
| 122 | + .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("timeout: {}", e)))?; |
| 123 | + let stmt: Statement = connection |
| 124 | + .prepare(&format!( |
| 125 | + "SELECT id, randomNumber FROM {} WHERE id = $1", |
| 126 | + TABLE_NAME |
| 127 | + )) |
| 128 | + .await?; |
| 129 | + if let Some(rows) = connection.query_opt(&stmt, &[&random_id]).await? { |
| 130 | + let id: i32 = rows.get(0); |
| 131 | + let random_number: i32 = rows.get(1); |
| 132 | + return Ok(QueryRow::new(id, random_number)); |
| 133 | + } |
| 134 | + return Ok(QueryRow::new(0, 0)); |
| 135 | +} |
0 commit comments