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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::error::Error;

/**
Representation of a CREATE INDEX builder.
*/
pub trait CreateIndex<'until_build> {
    /**
    Creates a unique index.

    Null values are considered different from all other null values.
     */
    fn unique(self) -> Self;

    /**
    Creates the index only if it doesn't exist yet.
     */
    fn if_not_exists(self) -> Self;

    /**
    Adds a column to the index.

    **Parameter**:
    - `column`: String representing the column to index.
     */
    fn add_column(self, column: &'until_build str) -> Self;

    /**
    Sets the condition to apply. This will build a partial index.

    **Parameter**:
    - `condition`: String representing condition to apply the index to
     */
    fn set_condition(self, condition: String) -> Self;

    /**
    This method is used to build the create index operation
     */
    fn build(self) -> Result<String, Error>;
}

/**
Representation of a create index operation
*/
pub struct CreateIndexData<'until_build> {
    pub(crate) name: &'until_build str,
    pub(crate) table_name: &'until_build str,
    pub(crate) unique: bool,
    pub(crate) if_not_exists: bool,
    pub(crate) columns: Vec<&'until_build str>,
    pub(crate) condition: Option<String>,
}

/**
Implementation of database specific implementations of the [CreateIndex] trait.

Should only be constructed via [crate::DBImpl::create_index].
*/
pub enum CreateIndexImpl<'until_build> {
    /**
    SQLite representation of the CREATE INDEX operation.
     */
    #[cfg(feature = "sqlite")]
    Sqlite(CreateIndexData<'until_build>),
    /**
    MySQL representation of the CREATE INDEX operation.
     */
    #[cfg(feature = "mysql")]
    MySQL(CreateIndexData<'until_build>),
    /**
    Postgres representation of the CREATE INDEX operation.
     */
    #[cfg(feature = "postgres")]
    Postgres(CreateIndexData<'until_build>),
}

impl<'until_build> CreateIndex<'until_build> for CreateIndexImpl<'until_build> {
    fn unique(mut self) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            CreateIndexImpl::Sqlite(ref mut d) => d.unique = true,
            #[cfg(feature = "mysql")]
            CreateIndexImpl::MySQL(ref mut d) => d.unique = true,
            #[cfg(feature = "postgres")]
            CreateIndexImpl::Postgres(ref mut d) => d.unique = true,
        };
        self
    }

    fn if_not_exists(mut self) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            CreateIndexImpl::Sqlite(ref mut d) => d.if_not_exists = true,
            #[cfg(feature = "mysql")]
            CreateIndexImpl::MySQL(ref mut d) => d.if_not_exists = true,
            #[cfg(feature = "postgres")]
            CreateIndexImpl::Postgres(ref mut d) => d.if_not_exists = true,
        };
        self
    }

    fn add_column(mut self, column: &'until_build str) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            CreateIndexImpl::Sqlite(ref mut d) => d.columns.push(column),
            #[cfg(feature = "mysql")]
            CreateIndexImpl::MySQL(ref mut d) => d.columns.push(column),
            #[cfg(feature = "postgres")]
            CreateIndexImpl::Postgres(ref mut d) => d.columns.push(column),
        }
        self
    }

    fn set_condition(mut self, condition: String) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            CreateIndexImpl::Sqlite(ref mut d) => d.condition = Some(condition),
            #[cfg(feature = "mysql")]
            CreateIndexImpl::MySQL(ref mut d) => d.condition = Some(condition),
            #[cfg(feature = "postgres")]
            CreateIndexImpl::Postgres(ref mut d) => d.condition = Some(condition),
        }
        self
    }

    fn build(self) -> Result<String, Error> {
        match self {
            #[cfg(feature = "sqlite")]
            CreateIndexImpl::Sqlite(d) => {
                if d.columns.is_empty() {
                    return Err(Error::SQLBuildError(format!(
                        "Couldn't create index on {}: Missing column(s) to create the index on",
                        d.table_name
                    )));
                }

                Ok(format!(
                    "CREATE {} INDEX{} {} ON {} ({}) {};",
                    if d.unique { "UNIQUE" } else { "" },
                    if d.if_not_exists {
                        " IF NOT EXISTS"
                    } else {
                        ""
                    },
                    d.name,
                    d.table_name,
                    d.columns.join(", "),
                    d.condition.as_ref().map_or("", |x| x.as_str()),
                ))
            }
            #[cfg(feature = "mysql")]
            CreateIndexImpl::MySQL(d) => {
                if d.columns.is_empty() {
                    return Err(Error::SQLBuildError(format!(
                        "Couldn't create index on {}: Missing column(s) to create the index on",
                        d.table_name
                    )));
                }

                Ok(format!(
                    "CREATE {} INDEX{} {} ON {} ({});",
                    if d.unique { "UNIQUE" } else { "" },
                    if d.if_not_exists {
                        " IF NOT EXISTS"
                    } else {
                        ""
                    },
                    d.name,
                    d.table_name,
                    d.columns.join(", "),
                ))
            }
            #[cfg(feature = "postgres")]
            CreateIndexImpl::Postgres(d) => {
                if d.columns.is_empty() {
                    return Err(Error::SQLBuildError(format!(
                        "Couldn't create index on {}: Missing column(s) to create the index on",
                        d.table_name
                    )));
                }

                Ok(format!(
                    "CREATE{} INDEX{} {} ON {} ({}){};",
                    if d.unique { " UNIQUE" } else { "" },
                    if d.if_not_exists {
                        " IF NOT EXISTS"
                    } else {
                        ""
                    },
                    d.name,
                    d.table_name,
                    d.columns.join(", "),
                    match d.condition {
                        None => String::from(""),
                        Some(cond) => format!(" WHERE {}", cond.as_str()),
                    }
                ))
            }
        }
    }
}