toasty_sql/stmt/
create_index.rs

1use super::Statement;
2
3use toasty_core::{
4    schema::db::{Index, IndexId, IndexOp, TableId},
5    stmt,
6};
7
8/// A `CREATE INDEX` statement.
9#[derive(Debug, Clone)]
10pub struct CreateIndex {
11    /// Name of the index
12    pub index: IndexId,
13
14    /// Which table to index
15    pub on: TableId,
16
17    /// The columns to index
18    pub columns: Vec<stmt::OrderByExpr>,
19
20    /// When true, the index is unique
21    pub unique: bool,
22}
23
24impl Statement {
25    /// Creates a `CREATE INDEX` statement from a schema [`Index`].
26    pub fn create_index(index: &Index) -> Self {
27        CreateIndex {
28            index: index.id,
29            on: index.on,
30            columns: index
31                .columns
32                .iter()
33                .map(|index_column| stmt::OrderByExpr {
34                    expr: stmt::Expr::column(index_column.column),
35                    order: match index_column.op {
36                        IndexOp::Eq => None,
37                        IndexOp::Sort(direction) => Some(direction),
38                    },
39                })
40                .collect(),
41            unique: index.unique,
42        }
43        .into()
44    }
45}
46
47impl From<CreateIndex> for Statement {
48    fn from(value: CreateIndex) -> Self {
49        Self::CreateIndex(value)
50    }
51}