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