omni_orchestrator/db_manager/
manager.rs

1use crate::db_manager;
2use crate::db_manager::connection::ConnectionManager;
3use crate::db_manager::error::DatabaseError;
4use crate::db_manager::migration::MigrationManager;
5use crate::schemas::v1::models::platform::{self, Platform};
6use log::{error, info, warn};
7use sqlx::{MySql, Pool};
8use std::sync::Arc;
9
10/// Central manager for all database operations
11pub struct DatabaseManager {
12    /// Connection manager for database pools
13    connection_manager: ConnectionManager,
14}
15
16impl DatabaseManager {
17    /// Creates a new database manager
18    pub async fn new(connection_url: &str) -> Result<Self, DatabaseError> {
19        // Create connection manager
20        let connection_manager = ConnectionManager::new(connection_url).await?;
21
22        // Create the manager
23        let manager = Self { connection_manager };
24
25        // Initialize the main database schema
26        manager.initialize_main_schema().await?;
27
28        Ok(manager)
29    }
30
31    /// Initializes the main database schema
32    pub async fn initialize_main_schema(&self) -> Result<(), DatabaseError> {
33        MigrationManager::initialize_main_schema(self).await
34    }
35
36    /// Gets the main database pool
37    pub fn get_main_pool(&self) -> &Pool<MySql> {
38        self.connection_manager.main_pool()
39    }
40
41    /// Gets or initializes a platform database
42    pub async fn get_platform_pool(
43        &self,
44        platform_name: &String,
45        platform_id: i64,
46    ) -> Result<Pool<MySql>, DatabaseError> {
47        // Get or create the pool
48        let pool = self
49            .connection_manager
50            .platform_pool(platform_id, &platform_name)
51            .await?;
52
53        // TODO: @Caznix @tristanpoland We need to find a new home for this
54        // Initialize the schema
55        // MigrationManager::initialize_platform_schema(&pool, platform).await?;
56
57        Ok(pool)
58    }
59
60    /// Gets all available platforms
61    pub async fn get_all_platforms(&self) -> Result<Vec<Platform>, DatabaseError> {
62        let pool = self.connection_manager.main_pool();
63
64        crate::schemas::v1::db::queries::platforms::get_all_platforms(pool)
65            .await
66            .map_err(|e| DatabaseError::Other(format!("Failed to retrieve platforms: {}", e)))
67    }
68
69    /// Creates a new platform in the main database and initializes its schema
70    pub async fn create_platform(
71        &self,
72        db_manager: &db_manager::DatabaseManager,
73        platform: Platform
74    ) -> Result<i64, DatabaseError> {
75        // First, create the platform entry in the main database
76        let platform = self.create_platform_entry(&platform).await?;
77
78        let platform_id = platform.id.ok_or_else(|| {
79            DatabaseError::Other("Platform ID is missing after creation".to_string())
80        })?;
81
82        self.initialize_platform_database(&db_manager, &platform.name, platform_id)
83            .await?;
84
85        info!(
86            "Platform created successfully: {} (ID: {})",
87            platform.name, platform_id
88        );
89
90        Ok(platform_id)
91    }
92
93    /// Creates a platform entry in the main database
94    async fn create_platform_entry(&self, platform: &Platform) -> Result<Platform, DatabaseError> {
95        let pool = self.connection_manager.main_pool();
96
97        crate::schemas::v1::db::queries::platforms::create_platform(
98            pool,
99            platform.name.as_str(),
100            Some(platform.description.as_str()),
101        )
102        .await
103        .map_err(|e| DatabaseError::Other(format!("Failed to create platform: {}", e)))
104    }
105
106    /// Initializes a platform database schema
107    async fn initialize_platform_database(
108        &self,
109        db_manager: &db_manager::DatabaseManager,
110        platform_name: &String,
111        platform_id: i64,
112    ) -> Result<(), DatabaseError> {
113        // Get the platform pool (this will create the database if it doesn't exist)
114        let pool = self
115            .connection_manager
116            .platform_pool(platform_id, platform_name)
117            .await?;
118
119        // TODO: @Caznix @tristanpoland We need to find a new home for this
120        // Initialize the schema
121        MigrationManager::initialize_platform_schema(db_manager, platform_name.clone(), platform_id).await?;
122
123        info!(
124            "Platform database initialized for platform: {} (ID: {})",
125            platform_name, platform_id
126        );
127
128        Ok(())
129    }
130
131    /// Deletes a platform and its associated database
132    pub async fn delete_platform(&self, platform_id: i64) -> Result<(), DatabaseError> {
133        // Get platform details before deletion for logging
134        let platform = self.get_platform_by_id(platform_id).await?;
135
136        // TODO: @Caznix @tristanpoland We need to implement this
137        // Delete the platform's dedicated database
138        // self.delete_platform_database(&platform.name, platform_id)
139        //     .await?;
140
141        // Delete the platform entry from the main database
142        self.delete_platform_entry(platform_id).await?;
143
144        info!(
145            "Platform deleted successfully: {} (ID: {})",
146            platform.name, platform_id
147        );
148
149        Ok(())
150    }
151
152    /// Gets a platform by ID
153    async fn get_platform_by_id(&self, platform_id: i64) -> Result<Platform, DatabaseError> {
154        let pool = self.connection_manager.main_pool();
155
156        crate::schemas::v1::db::queries::platforms::get_platform_by_id(pool, platform_id)
157            .await
158            .map_err(|e| {
159                DatabaseError::Other(format!(
160                    "Failed to retrieve platform with ID {}: {}",
161                    platform_id, e
162                ))
163            })
164    }
165
166    /// Deletes a platform entry from the main database
167    async fn delete_platform_entry(&self, platform_id: i64) -> Result<(), DatabaseError> {
168        let pool = self.connection_manager.main_pool();
169
170        crate::schemas::v1::db::queries::platforms::delete_platform(pool, platform_id)
171            .await
172            .map_err(|e| {
173                DatabaseError::Other(format!(
174                    "Failed to delete platform with ID {}: {}",
175                    platform_id, e
176                ))
177            })
178    }
179
180    //TODO: @Caznix @tristanpoland We need to implement this
181    // Deletes a platform's dedicated database
182    // async fn delete_platform_database(
183    //     &self,
184    //     platform_name: &String,
185    //     platform_id: i64,
186    // ) -> Result<(), DatabaseError> {
187    //     // We need to access the connection manager to delete the database
188    //     self.connection_manager
189    //         .delete_platform_database(platform_id, platform_name)
190    //         .await
191    //         .map_err(|e| {
192    //             error!(
193    //                 "Failed to delete platform database for {} (ID: {}): {}",
194    //                 platform_name, platform_id, e
195    //             );
196    //             DatabaseError::Other(format!("Failed to delete platform database: {}", e))
197    //         })
198    // }
199}