Skip to main content

sea_schema/sqlite/def/
table.rs

1use super::{
2    ColumnInfo, DefaultType, ForeignKeysInfo, IndexInfo, IndexedColumns, PartialIndexInfo,
3};
4use crate::Connection;
5use crate::rusqlite_types::RusqliteRow;
6use crate::sqlite::{
7    error::{DiscoveryResult, SqliteDiscoveryError},
8    query::SqliteMaster,
9};
10use sea_query::{
11    Alias, ColumnDef, Expr, ExprTrait, ForeignKey, Index, Keyword, Query, Table,
12    TableCreateStatement, Value,
13};
14
15/// Defines a table for SQLite
16#[derive(Debug, Default, Clone, PartialEq)]
17pub struct TableDef {
18    /// The table name
19    pub name: String,
20    /// A list of foreign keys in the table
21    pub foreign_keys: Vec<ForeignKeysInfo>,
22    /// A list of the indexes in the table
23    pub indexes: Vec<IndexInfo>,
24    /// A list of UNIQUE and PRIMARY KEY constraints on the table
25    pub constraints: Vec<IndexInfo>,
26    /// A list of all the columns and their types
27    pub columns: Vec<ColumnInfo>,
28    /// Whether the primary key should autoincrement
29    pub auto_increment: bool,
30}
31
32#[cfg(feature = "rusqlite")]
33impl From<RusqliteRow> for TableDef {
34    fn from(row: RusqliteRow) -> Self {
35        use crate::rusqlite_types::Row;
36        let row = row.sqlite();
37        TableDef {
38            name: row.get(0),
39            foreign_keys: Vec::default(),
40            indexes: Vec::default(),
41            constraints: Vec::default(),
42            columns: Vec::default(),
43            auto_increment: bool::default(),
44        }
45    }
46}
47
48#[cfg(all(not(feature = "rusqlite"), not(feature = "sqlx-sqlite")))]
49impl From<RusqliteRow> for TableDef {
50    fn from(_: RusqliteRow) -> Self {
51        Self::default()
52    }
53}
54
55impl TableDef {
56    /// Check if the primary key in the table is set to autoincrement as a result of using query
57    /// `SELECT COUNT(*) from sqlite_sequence where name = 'table_name';
58    pub fn pk_is_autoincrement(&mut self, conn: &impl Connection) -> DiscoveryResult<&mut Self> {
59        let check_autoincrement = Query::select()
60            .expr(Expr::val(1))
61            .from(SqliteMaster)
62            .and_where(Expr::col("type").eq("table"))
63            .and_where(Expr::col("name").eq(self.name.as_str()))
64            .and_where(Expr::col("sql").like("%AUTOINCREMENT%"))
65            .to_owned();
66
67        if !conn.query_all(check_autoincrement)?.is_empty() {
68            self.auto_increment = true;
69        }
70
71        Ok(self)
72    }
73
74    /// Get a list of most of the UNIQUE and PRIMARY KEY constraints on the table.
75    /// These are implemented by indexes in most cases. These indexes have type "u" or "pk".
76    /// Note that this does not get the column name mapped by the index.
77    /// To get the column name mapped by the index, the `self.get_single_indexinfo` method is invoked
78    pub fn get_constraints(&mut self, conn: &impl Connection) -> DiscoveryResult<()> {
79        let mut index_query = String::default();
80        index_query.push_str("PRAGMA index_list('");
81        index_query.push_str(&self.name);
82        index_query.push_str("')");
83
84        let partial_index_info_rows = conn.query_all_raw(index_query)?;
85        let mut partial_indexes: Vec<PartialIndexInfo> = Vec::default();
86
87        partial_index_info_rows.into_iter().for_each(|info| {
88            let partial_index_info: PartialIndexInfo = info.into();
89
90            if partial_index_info.origin.as_str() == "u" {
91                partial_indexes.push(partial_index_info);
92            }
93        });
94
95        for partial_index in partial_indexes {
96            let partial_index_column: IndexedColumns =
97                self.get_single_indexinfo(conn, &partial_index.name)?;
98
99            self.constraints.push(IndexInfo {
100                r#type: partial_index_column.r#type,
101                index_name: partial_index_column.name,
102                table_name: partial_index_column.table,
103                unique: partial_index.unique,
104                origin: partial_index.origin,
105                partial: partial_index.partial,
106                columns: partial_index_column.indexed_columns,
107            });
108        }
109
110        Ok(())
111    }
112
113    /// Get a list of all the indexes in the table.
114    /// Note that this does not get the column name mapped by the index.
115    /// To get the column name mapped by the index, the `self.get_single_indexinfo` method is invoked
116    pub fn get_indexes(&mut self, conn: &impl Connection) -> DiscoveryResult<()> {
117        let mut index_query = String::default();
118        index_query.push_str("PRAGMA index_list('");
119        index_query.push_str(&self.name);
120        index_query.push_str("')");
121
122        let partial_index_info_rows = conn.query_all_raw(index_query)?;
123        let mut partial_indexes: Vec<PartialIndexInfo> = Vec::default();
124
125        partial_index_info_rows.into_iter().for_each(|info| {
126            let partial_index_info: PartialIndexInfo = info.into();
127
128            if partial_index_info.origin.as_str() == "c" {
129                partial_indexes.push(partial_index_info);
130            }
131        });
132
133        for partial_index in partial_indexes {
134            let partial_index_column: IndexedColumns =
135                self.get_single_indexinfo(conn, &partial_index.name)?;
136
137            self.indexes.push(IndexInfo {
138                r#type: partial_index_column.r#type,
139                index_name: partial_index_column.name,
140                table_name: partial_index_column.table,
141                unique: partial_index.unique,
142                origin: partial_index.origin,
143                partial: partial_index.partial,
144                columns: partial_index_column.indexed_columns,
145            });
146        }
147
148        Ok(())
149    }
150
151    /// Get a list of all the foreign keys in the table
152    pub fn get_foreign_keys(&mut self, conn: &impl Connection) -> DiscoveryResult<&mut Self> {
153        let mut index_query = String::default();
154        index_query.push_str("PRAGMA foreign_key_list('");
155        index_query.push_str(&self.name);
156        index_query.push_str("')");
157
158        let index_info_rows = conn.query_all_raw(index_query)?;
159
160        let mut last_fk_id = None;
161        index_info_rows.into_iter().for_each(|info| {
162            let mut index_info: ForeignKeysInfo = info.into();
163            let fk_id = index_info.id;
164            if last_fk_id == Some(fk_id) {
165                let last_fk = self.foreign_keys.last_mut().unwrap();
166                last_fk.from.push(index_info.from.pop().unwrap());
167                last_fk.to.push(index_info.to.pop().unwrap());
168            } else {
169                self.foreign_keys.push(index_info);
170            }
171            last_fk_id = Some(fk_id);
172        });
173
174        Ok(self)
175    }
176
177    pub fn get_column_info(&mut self, conn: &impl Connection) -> DiscoveryResult<&TableDef> {
178        let mut query = String::with_capacity(64 + self.name.len());
179        query.push_str("PRAGMA table_xinfo('");
180        query.push_str(&self.name);
181        query.push_str("')");
182
183        let rows = conn.query_all_raw(query)?;
184
185        for row in rows {
186            let column = ColumnInfo::to_column_def(row)?;
187            if column.is_hidden() {
188                continue; // Skip hidden columns
189            }
190            self.columns.push(column);
191        }
192
193        Ok(self)
194    }
195
196    /// Gets the columns that are mapped to an index
197    pub(crate) fn get_single_indexinfo(
198        &mut self,
199        conn: &impl Connection,
200        index_name: &str,
201    ) -> DiscoveryResult<IndexedColumns> {
202        let index_query = Query::select()
203            .expr(Expr::cust("*"))
204            .from(SqliteMaster)
205            .and_where(Expr::col("name").eq(index_name))
206            .to_owned();
207
208        let index_info = conn.query_all(index_query)?;
209        let index_info = index_info
210            .into_iter()
211            .next()
212            .ok_or_else(|| SqliteDiscoveryError::IndexNotFound(index_name.to_owned()))?;
213
214        let mut index_column_query = String::default();
215        index_column_query.push_str("PRAGMA index_info('");
216        index_column_query.push_str(index_name);
217        index_column_query.push_str("')");
218
219        let index_column_info_rows = conn.query_all_raw(index_column_query)?;
220
221        Ok((index_info, index_column_info_rows).into())
222    }
223
224    pub fn write(&self) -> TableCreateStatement {
225        let mut primary_keys = Vec::new();
226
227        let mut new_table = Table::create();
228        new_table.table(Alias::new(&self.name));
229
230        self.columns.iter().for_each(|column_info| {
231            let mut new_column =
232                ColumnDef::new_with_type(Alias::new(&column_info.name), column_info.r#type.clone());
233            if column_info.not_null {
234                new_column.not_null();
235            }
236
237            if self.auto_increment && column_info.primary_key {
238                new_column.primary_key().auto_increment();
239            } else if column_info.primary_key {
240                primary_keys.push(column_info.name.clone());
241            }
242
243            match &column_info.default_value {
244                DefaultType::Integer(integer_value) => {
245                    new_column.default(Value::BigInt(Some(*integer_value)));
246                }
247                DefaultType::Float(float_value) => {
248                    new_column.default(Value::Float(Some(*float_value)));
249                }
250                DefaultType::String(string_value) => {
251                    new_column.default(Value::String(Some(string_value.to_string())));
252                }
253                DefaultType::Null => (),
254                DefaultType::Unspecified => (),
255                DefaultType::CurrentTimestamp => {
256                    new_column.default(Keyword::CurrentTimestamp);
257                }
258            }
259
260            new_table.col(&mut new_column);
261        });
262
263        self.foreign_keys.iter().for_each(|foreign_key| {
264            let mut fk = ForeignKey::create();
265            for from in foreign_key.from.iter() {
266                fk.from(Alias::new(&self.name), Alias::new(from));
267            }
268            for to in foreign_key.to.iter() {
269                fk.to(Alias::new(&foreign_key.table), Alias::new(to));
270            }
271            fk.on_delete(foreign_key.on_delete.to_seaquery_foreign_key_action())
272                .on_update(foreign_key.on_update.to_seaquery_foreign_key_action());
273            new_table.foreign_key(&mut fk);
274        });
275
276        self.constraints.iter().for_each(|index| {
277            new_table.index(&mut index.write());
278        });
279
280        if !primary_keys.is_empty() {
281            let mut primary_key_stmt = Index::create();
282            for primary_key in primary_keys.iter() {
283                primary_key_stmt.col(Alias::new(primary_key));
284            }
285            new_table.primary_key(&mut primary_key_stmt);
286        }
287
288        new_table
289    }
290}