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
use crate::database::lib::Database;
use crate::database::lib::DatabaseType;
use crate::database::DB;
use crate::{error::LunaOrmError, LunaOrmResult};

use sqlx::any::AnyConnectOptions;
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqliteSynchronous};
use sqlx::AnyPool;
use sqlx::MySqlPool;
use sqlx::{MySql, MySqlConnection};

use std::fs;
use std::path::Path;
use std::str::FromStr;

use crate::command_executor::CommandExecutor;
use crate::sql_executor::SqlExecutor;
use crate::sql_generator::MySqlGenerator;

use path_absolutize::*;

pub struct MysqlDatabase {
    database_type: DatabaseType,
    pool: AnyPool,
    sql_generator: MySqlGenerator,
}

impl SqlExecutor for MysqlDatabase {
    fn get_pool(&self) -> LunaOrmResult<&AnyPool> {
        Ok(&self.pool)
    }
}

impl CommandExecutor for MysqlDatabase {
    type G = MySqlGenerator;

    fn get_generator(&self) -> &Self::G {
        &self.sql_generator
    }
}

impl Database for MysqlDatabase {
    fn get_type(&self) -> &DatabaseType {
        &self.database_type
    }
}

impl From<MysqlDatabase> for DB<MysqlDatabase> {
    fn from(value: MysqlDatabase) -> Self {
        Self(value)
    }
}

impl MysqlDatabase {
    pub async fn build(url: &str, user: &str, password: &str) -> LunaOrmResult<Self> {
        let url = format!("mysql://{}:{}@{}", user, password, url);

        let any_options = AnyConnectOptions::from_str(&url).unwrap();
        let pool = AnyPool::connect_with(any_options)
            .await
            .map_err(|_e| LunaOrmError::DatabaseInitFail("init pool fail".to_string()))?;

        let generator = MySqlGenerator::new();
        let database = MysqlDatabase {
            database_type: DatabaseType::MySql,
            pool,
            sql_generator: generator,
        };
        return Ok(database);
    }
}