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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use sea_query::{
    Alias, ColumnDef, Expr, ForeignKey, Index, Query, Table, TableCreateStatement, Value,
};

use super::{
    ColumnInfo, DefaultType, ForeignKeysInfo, IndexInfo, IndexedColumns, PartialIndexInfo,
};
use crate::sqlite::{error::DiscoveryResult, executor::Executor};
use crate::sqlx_types::{sqlite::SqliteRow, Row};

/// Defines a table for SQLite
#[derive(Debug, Default, Clone)]
pub struct TableDef {
    /// The table name
    pub name: String,
    /// A list of foreign keys in the table
    pub foreign_keys: Vec<ForeignKeysInfo>,
    /// A list of all the columns and their types
    pub columns: Vec<ColumnInfo>,
    /// Whether the primary key should autoincrement
    pub auto_increment: bool,
}

#[cfg(feature = "sqlx-sqlite")]
/// Gets the table name from a `SqliteRow` and maps it to the [TableDef]
impl From<&SqliteRow> for TableDef {
    fn from(row: &SqliteRow) -> Self {
        let row: String = row.get(0);
        TableDef {
            name: row,
            foreign_keys: Vec::default(),
            columns: Vec::default(),
            auto_increment: bool::default(),
        }
    }
}

#[cfg(not(feature = "sqlx-sqlite"))]
/// Gets the table name from a `SqliteRow` and maps it to the [TableDef]
impl From<&SqliteRow> for TableDef {
    fn from(row: &SqliteRow) -> Self {
        Self::default()
    }
}

impl TableDef {
    /// Check if the primary key in the table is set to autoincrement as a result of using query
    /// `SELECT COUNT(*) from sqlite_sequence where name = 'table_name';
    pub async fn pk_is_autoincrement(&mut self, executor: &Executor) -> DiscoveryResult<&mut Self> {
        let check_autoincrement = Query::select()
            .expr(Expr::val(1))
            .from(Alias::new("sqlite_master"))
            .and_where(Expr::col(Alias::new("type")).eq("table"))
            .and_where(Expr::col(Alias::new("name")).eq(self.name.as_str()))
            .and_where(Expr::col(Alias::new("sql")).like("%AUTOINCREMENT%"))
            .to_owned();

        if !executor.fetch_all(check_autoincrement).await.is_empty() {
            self.auto_increment = true;
        }

        Ok(self)
    }

    /// Get a list of all the indexes in the table.
    /// Note that this does not get the column name mapped by the index.
    /// To get the column name mapped by the index, the `self.get_single_indexinfo` method is invoked
    pub async fn get_indexes(
        &mut self,
        executor: &Executor,
        indexes: &mut Vec<IndexInfo>,
    ) -> DiscoveryResult<()> {
        let mut index_query = String::default();
        index_query.push_str("PRAGMA index_list('");
        index_query.push_str(&self.name);
        index_query.push_str("')");

        let partial_index_info_rows = executor.fetch_all_raw(index_query).await;
        let mut partial_indexes: Vec<PartialIndexInfo> = Vec::default();

        partial_index_info_rows.iter().for_each(|info| {
            let partial_index_info: PartialIndexInfo = info.into();

            if partial_index_info.origin.as_str() != "pk" {
                partial_indexes.push(partial_index_info);
            }
        });

        for partial_index in partial_indexes {
            let partial_index_column: IndexedColumns = self
                .get_single_indexinfo(executor, &partial_index.name)
                .await?;

            indexes.push(IndexInfo {
                r#type: partial_index_column.r#type,
                index_name: partial_index_column.name,
                table_name: partial_index_column.table,
                unique: partial_index.unique,
                origin: partial_index.origin,
                partial: partial_index.partial,
                columns: partial_index_column.indexed_columns,
            });
        }

        Ok(())
    }

    /// Get a list of all the foreign keys in the table
    pub async fn get_foreign_keys(&mut self, executor: &Executor) -> DiscoveryResult<&mut Self> {
        let mut index_query = String::default();
        index_query.push_str("PRAGMA foreign_key_list('");
        index_query.push_str(&self.name);
        index_query.push_str("')");

        let index_info_rows = executor.fetch_all_raw(index_query).await;

        index_info_rows.iter().for_each(|info| {
            let index_info: ForeignKeysInfo = info.into();

            self.foreign_keys.push(index_info);
        });

        Ok(self)
    }

    /// Get a list of all the columns in the table mapped as [ColumnInfo]
    pub async fn get_column_info(&mut self, executor: &Executor) -> DiscoveryResult<&TableDef> {
        let mut index_query = String::default();
        index_query.push_str("PRAGMA table_info('");
        index_query.push_str(&self.name);
        index_query.push_str("')");

        let index_info_rows = executor.fetch_all_raw(index_query).await;

        for info in index_info_rows {
            let column = ColumnInfo::to_column_def(&info)?;
            self.columns.push(column);
        }

        Ok(self)
    }

    /// Checks the column that is mapped to an index
    pub(crate) async fn get_single_indexinfo(
        &mut self,
        executor: &Executor,
        index_name: &str,
    ) -> DiscoveryResult<IndexedColumns> {
        let index_query = Query::select()
            .expr(Expr::cust("*"))
            .from(Alias::new("sqlite_master"))
            .and_where(Expr::col(Alias::new("name")).eq(index_name))
            .to_owned();

        let index_info = executor.fetch_one(index_query).await;

        Ok((&index_info).into())
    }

    pub fn write(&self) -> TableCreateStatement {
        let mut primary_keys = Vec::new();

        let mut new_table = Table::create();
        new_table.table(Alias::new(&self.name));

        self.columns.iter().for_each(|column_info| {
            let mut new_column = ColumnDef::new(Alias::new(&column_info.name));
            if column_info.not_null {
                new_column.not_null();
            }

            if self.auto_increment && column_info.primary_key {
                new_column.primary_key().auto_increment();
            } else if column_info.primary_key {
                primary_keys.push(column_info.name.clone());
            }

            column_info.r#type.write_type(&mut new_column);

            match &column_info.default_value {
                DefaultType::Integer(integer_value) => {
                    new_column.default(Value::Int(Some(*integer_value)));
                }
                DefaultType::Float(float_value) => {
                    new_column.default(Value::Float(Some(*float_value)));
                }
                DefaultType::String(string_value) => {
                    new_column.default(Value::String(Some(Box::new(string_value.to_string()))));
                }
                DefaultType::Null => (),
                DefaultType::Unspecified => (),
            }

            new_table.col(&mut new_column);
        });

        self.foreign_keys.iter().for_each(|foreign_key| {
            new_table.foreign_key(
                &mut ForeignKey::create()
                    .from(Alias::new(&self.name), Alias::new(&foreign_key.from))
                    .to(Alias::new(&foreign_key.table), Alias::new(&foreign_key.to))
                    .on_delete(foreign_key.on_delete.to_seaquery_foreign_key_action())
                    .on_update(foreign_key.on_update.to_seaquery_foreign_key_action())
                    .to_owned(),
            );
        });

        if !primary_keys.is_empty() {
            let mut primary_key_stmt = Index::create();
            for primary_key in primary_keys.iter() {
                primary_key_stmt.col(Alias::new(primary_key));
            }
            new_table.primary_key(&mut primary_key_stmt);
        }

        new_table
    }
}