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: @Caznix @tristanpoland We need to find a new home for this
57        // Initialize the schema
58        // MigrationManager::initialize_platform_schema(&pool, platform).await?;
59
60        Ok(pool)
61    }
62
63    /// Gets all available platforms
64    pub async fn get_all_platforms(&self) -> Result<Vec<Platform>, DatabaseError> {
65        let pool = self.connection_manager.main_pool();
66
67        crate::schemas::v1::db::queries::platforms::get_all_platforms(pool)
68            .await
69            .map_err(|e| DatabaseError::Other(format!("Failed to retrieve platforms: {}", e)))
70    }
71
72    /// Creates a new platform in the main database and initializes its schema
73    pub async fn create_platform(
74        &self,
75        db_manager: &db_manager::DatabaseManager,
76        platform: Platform
77    ) -> Result<i64, DatabaseError> {
78        // First, create the platform entry in the main database
79        let platform = self.create_platform_entry(&platform).await?;
80
81        let platform_id = platform.id.ok_or_else(|| {
82            DatabaseError::Other("Platform ID is missing after creation".to_string())
83        })?;
84
85        self.initialize_platform_database(&db_manager, &platform.name, platform_id)
86            .await?;
87
88        info!(
89            "Platform created successfully: {} (ID: {})",
90            platform.name, platform_id
91        );
92
93        Ok(platform_id)
94    }
95
96    /// Creates a platform entry in the main database
97    async fn create_platform_entry(&self, platform: &Platform) -> Result<Platform, DatabaseError> {
98        let pool = self.connection_manager.main_pool();
99
100        crate::schemas::v1::db::queries::platforms::create_platform(
101            pool,
102            platform.name.as_str(),
103            Some(platform.description.as_str()),
104        )
105        .await
106        .map_err(|e| DatabaseError::Other(format!("Failed to create platform: {}", e)))
107    }
108
109    /// Initializes a platform database schema
110    async fn initialize_platform_database(
111        &self,
112        db_manager: &db_manager::DatabaseManager,
113        platform_name: &String,
114        platform_id: i64,
115    ) -> Result<(), DatabaseError> {
116        // Get the platform pool (this will create the database if it doesn't exist)
117        let pool = self
118            .connection_manager
119            .platform_pool(platform_id, platform_name)
120            .await?;
121
122        // TODO: @Caznix @tristanpoland We need to find a new home for this
123        // Initialize the schema
124        MigrationManager::initialize_platform_schema(db_manager, platform_name.clone(), platform_id).await?;
125
126        info!(
127            "Platform database initialized for platform: {} (ID: {})",
128            platform_name, platform_id
129        );
130
131        Ok(())
132    }
133
134    /// Deletes a platform and its associated database
135    pub async fn delete_platform(&self, platform_id: i64) -> Result<(), DatabaseError> {
136        // Get platform details before deletion for logging
137        let platform = self.get_platform_by_id(platform_id).await?;
138
139        // TODO: @Caznix @tristanpoland We need to implement this
140        // Delete the platform's dedicated database
141        // self.delete_platform_database(&platform.name, platform_id)
142        //     .await?;
143
144        // Delete the platform entry from the main database
145        self.delete_platform_entry(platform_id).await?;
146
147        info!(
148            "Platform deleted successfully: {} (ID: {})",
149            platform.name, platform_id
150        );
151
152        Ok(())
153    }
154
155    /// Gets a platform by ID
156    async fn get_platform_by_id(&self, platform_id: i64) -> Result<Platform, DatabaseError> {
157        let pool = self.connection_manager.main_pool();
158
159        crate::schemas::v1::db::queries::platforms::get_platform_by_id(pool, platform_id)
160            .await
161            .map_err(|e| {
162                DatabaseError::Other(format!(
163                    "Failed to retrieve platform with ID {}: {}",
164                    platform_id, e
165                ))
166            })
167    }
168
169    /// Deletes a platform entry from the main database
170    async fn delete_platform_entry(&self, platform_id: i64) -> Result<(), DatabaseError> {
171        let pool = self.connection_manager.main_pool();
172
173        crate::schemas::v1::db::queries::platforms::delete_platform(pool, platform_id)
174            .await
175            .map_err(|e| {
176                DatabaseError::Other(format!(
177                    "Failed to delete platform with ID {}: {}",
178                    platform_id, e
179                ))
180            })
181    }
182
183    //TODO: @Caznix @tristanpoland We need to implement this
184    // Deletes a platform's dedicated database
185    // async fn delete_platform_database(
186    //     &self,
187    //     platform_name: &String,
188    //     platform_id: i64,
189    // ) -> Result<(), DatabaseError> {
190    //     // We need to access the connection manager to delete the database
191    //     self.connection_manager
192    //         .delete_platform_database(platform_id, platform_name)
193    //         .await
194    //         .map_err(|e| {
195    //             error!(
196    //                 "Failed to delete platform database for {} (ID: {}): {}",
197    //                 platform_name, platform_id, e
198    //             );
199    //             DatabaseError::Other(format!("Failed to delete platform database: {}", e))
200    //         })
201    // }
202}