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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
//
// SPDX-License-Identifier: EUPL-1.2

use diesel::backend::Backend;
use diesel::query_builder::*;
use diesel::result::QueryResult;
use diesel::RunQueryDsl;

/// Database drop statement
///
/// This `struct` is created by [`drop_database`] function
#[derive(Debug, Clone)]
pub struct DropDatabaseStatement {
    db_name: String,
    if_exists: bool,
}

impl DropDatabaseStatement {
    pub fn new(db_name: &str) -> Self {
        DropDatabaseStatement {
            db_name: db_name.to_owned(),
            if_exists: false,
        }
    }

    pub fn if_exists(self) -> Self {
        DropDatabaseStatement {
            if_exists: true,
            ..self
        }
    }
}

impl<DB: Backend> QueryFragment<DB> for DropDatabaseStatement {
    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
        out.push_sql("DROP DATABASE ");
        if self.if_exists {
            out.push_sql("IF EXISTS ");
        }
        out.push_identifier(&self.db_name)?;
        Ok(())
    }
}

impl<Conn> RunQueryDsl<Conn> for DropDatabaseStatement {}

impl QueryId for DropDatabaseStatement {
    type QueryId = ();

    const HAS_STATIC_QUERY_ID: bool = false;
}

/// Database create statement
///
/// This `struct` is created by [`create_database`] function
#[derive(Debug, Clone)]
pub struct CreateDatabaseStatement {
    db_name: String,
}

impl CreateDatabaseStatement {
    pub fn new(db_name: &str) -> Self {
        CreateDatabaseStatement {
            db_name: db_name.to_owned(),
        }
    }
}

impl<DB: Backend> QueryFragment<DB> for CreateDatabaseStatement {
    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
        out.push_sql("CREATE DATABASE ");
        out.push_identifier(&self.db_name)?;
        Ok(())
    }
}

impl<Conn> RunQueryDsl<Conn> for CreateDatabaseStatement {}

impl QueryId for CreateDatabaseStatement {
    type QueryId = ();

    const HAS_STATIC_QUERY_ID: bool = false;
}

/// Takes a database name and creates a diesel drop database statement struct
pub fn drop_database(db_name: &str) -> DropDatabaseStatement {
    DropDatabaseStatement::new(db_name)
}

/// Takes a database name and creates a diesel create database statement struct
pub fn create_database(db_name: &str) -> CreateDatabaseStatement {
    CreateDatabaseStatement::new(db_name)
}