Skip to main content

utopia_query/schema/
sqlite.rs

1//! [`Sqlite`]: the SQLite schema.
2
3use super::column::{self, Column};
4use super::enums::ColumnType;
5use super::feature;
6use super::table::{self, Table};
7use super::{Schema, base};
8use crate::builder::{AnyBuilder, Executor, Statement};
9use crate::error::{Error, Result};
10
11/// The SQLite schema: backtick quoting, `INTEGER PRIMARY KEY AUTOINCREMENT`
12/// inline, `TEXT` for most types, `DELETE FROM` for truncation.
13///
14/// ```
15/// use utopia_query::schema::{Schema, Sqlite};
16///
17/// let mut table = Sqlite::new().table("notes");
18/// table.id("id");
19/// table.text("body");
20/// assert_eq!(
21///     table.create()?.query,
22///     "CREATE TABLE `notes` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `body` TEXT NOT NULL)"
23/// );
24/// # Ok::<(), utopia_query::Error>(())
25/// ```
26///
27/// ```php
28/// use Utopia\Query\Schema\SQLite;
29///
30/// $table = (new SQLite())->table('notes');
31/// $table->id();
32/// $table->text('body');
33/// echo $table->create()->query, "\n";
34/// ```
35///
36/// PHP: `Utopia\Query\Schema\SQLite`.
37#[derive(Clone, Default)]
38pub struct Sqlite {
39    executor: Option<Executor>,
40}
41
42impl std::fmt::Debug for Sqlite {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("Sqlite").field("executor", &self.executor.is_some()).finish()
45    }
46}
47
48impl Sqlite {
49    /// A SQLite schema without an executor.
50    ///
51    /// PHP: `new SQLite()`.
52    pub fn new() -> Self {
53        Sqlite::default()
54    }
55}
56
57/// `query` without its first `, PRIMARY KEY (`...`)` clause
58/// (`preg_replace('/, PRIMARY KEY \(`[^`]+`\)/', '', $query, 1)`).
59fn without_primary_clause(query: &str) -> String {
60    const NEEDLE: &str = ", PRIMARY KEY (`";
61    let mut from = 0;
62    while let Some(found) = query[from..].find(NEEDLE) {
63        let start = from + found;
64        let name_start = start + NEEDLE.len();
65        let rest = &query.as_bytes()[name_start..];
66        let name_len = rest.iter().position(|&b| b == b'`').unwrap_or(rest.len());
67        if name_len > 0 && rest[name_len..].starts_with(b"`)") {
68            let end = name_start + name_len + 2;
69            return format!("{}{}", &query[..start], &query[end..]);
70        }
71        from = start + 1;
72    }
73    query.to_owned()
74}
75
76impl Schema for Sqlite {
77    fn executor(&self) -> Option<&Executor> {
78        self.executor.as_ref()
79    }
80
81    fn set_executor(&mut self, executor: Executor) -> &mut Self {
82        self.executor = Some(executor);
83        self
84    }
85
86    fn literal(&self) -> crate::StringLiteral {
87        crate::StringLiteral::Standard
88    }
89
90    fn quote(&self, identifier: &str) -> Result<String> {
91        crate::quote(identifier, '`')
92    }
93
94    fn quote_literal(&self, identifier: &str) -> Result<String> {
95        crate::quote_literal(identifier, '`')
96    }
97
98    fn compile_column_type(&self, column: &Column<Self>) -> Result<String> {
99        let c = &column.def;
100        Ok(match c.kind {
101            ColumnType::String | ColumnType::Varchar | ColumnType::Relationship => {
102                format!("VARCHAR({})", c.length.unwrap_or(255))
103            }
104            ColumnType::Text | ColumnType::MediumText | ColumnType::LongText => "TEXT".into(),
105            ColumnType::TinyInteger
106            | ColumnType::SmallInteger
107            | ColumnType::Integer
108            | ColumnType::BigInteger
109            | ColumnType::Id
110            | ColumnType::Serial
111            | ColumnType::BigSerial
112            | ColumnType::SmallSerial => "INTEGER".into(),
113            ColumnType::Float | ColumnType::Double => "REAL".into(),
114            ColumnType::Decimal => format!("NUMERIC({}, {})", c.precision.unwrap_or(10), c.scale.unwrap_or(0)),
115            ColumnType::Boolean => "INTEGER".into(),
116            ColumnType::Datetime | ColumnType::Timestamp => "TEXT".into(),
117            ColumnType::Json | ColumnType::Object => "TEXT".into(),
118            ColumnType::Binary => "BLOB".into(),
119            ColumnType::Enum => "TEXT".into(),
120            ColumnType::Point | ColumnType::Linestring | ColumnType::Polygon => "TEXT".into(),
121            ColumnType::Uuid => "TEXT".into(),
122            ColumnType::Uuid7 => "VARCHAR(36)".into(),
123            ColumnType::Vector => return Err(Error::Unsupported("Vector type is not supported in SQLite.".into())),
124            ColumnType::Array | ColumnType::Tuple => {
125                return Err(Error::Unsupported("Array/Tuple column types are not supported in SQLite.".into()));
126            }
127        })
128    }
129
130    fn compile_auto_increment(&self) -> &'static str {
131        "AUTOINCREMENT"
132    }
133
134    /// An auto-incrementing primary key is `INTEGER PRIMARY KEY
135    /// AUTOINCREMENT` inline; other columns compile as usual.
136    fn compile_column_definition(&self, column: &Column<Self>) -> Result<String> {
137        let c = &column.def;
138        if !c.auto_increment || !c.primary {
139            return base::column_definition(self, column);
140        }
141        let mut out = base::column_start(self, column)?;
142        base::add(&mut out, &["PRIMARY KEY ", self.compile_auto_increment()]);
143        if !c.nullable {
144            base::add(&mut out, &["NOT NULL"]);
145        }
146        base::add_default(self, &mut out, column)?;
147        if let Some(check) = &c.check {
148            base::add(&mut out, &["CHECK (", check, ")"]);
149        }
150        Ok(out)
151    }
152
153    /// Without the trailing `PRIMARY KEY (...)` clause when a column carries
154    /// its key inline.
155    fn compile_create(&self, table: &Table<Self>, if_not_exists: bool) -> Result<Statement> {
156        let inline = table.columns().iter().any(|c| c.def.auto_increment && c.def.primary);
157        let statement = base::create(self, table, if_not_exists)?;
158        if !inline {
159            return Ok(statement);
160        }
161        let query = without_primary_clause(&statement.query);
162        Ok(base::statement(self, query, statement.bindings))
163    }
164
165    fn compile_unsigned(&self) -> &'static str {
166        ""
167    }
168
169    fn compile_rename(&self, from: &str, to: &str) -> Result<Statement> {
170        base::plain(self, format!("ALTER TABLE {} RENAME TO {}", self.quote(from)?, self.quote(to)?))
171    }
172
173    fn compile_truncate(&self, name: &str) -> Result<Statement> {
174        base::plain(self, format!("DELETE FROM {}", self.quote(name)?))
175    }
176
177    fn drop_index(&self, _table: &str, name: &str) -> Result<Statement> {
178        base::plain(self, format!("DROP INDEX {}", self.quote(name)?))
179    }
180}
181
182impl column::AutoIncrement for Sqlite {}
183impl column::Collation for Sqlite {}
184impl column::Comment for Sqlite {}
185impl column::Generated for Sqlite {}
186impl column::Unique for Sqlite {}
187impl column::VirtualGenerated for Sqlite {}
188impl table::Serial for Sqlite {}
189impl table::Checks for Sqlite {}
190impl table::ColumnAlterations for Sqlite {}
191impl table::CompositePrimary for Sqlite {}
192impl table::InlineForeignKey for Sqlite {}
193
194impl feature::Views for Sqlite {
195    fn create_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
196        base::create_view(self, "CREATE VIEW", name, query)
197    }
198
199    fn drop_view(&self, name: &str) -> Result<Statement> {
200        base::plain(self, format!("DROP VIEW {}", self.quote(name)?))
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::without_primary_clause;
207
208    #[test]
209    fn removes_the_first_primary_clause() {
210        assert_eq!(without_primary_clause("(`a` INT, PRIMARY KEY (`a`))"), "(`a` INT)");
211        assert_eq!(
212            without_primary_clause("(`a` INT, PRIMARY KEY (``), PRIMARY KEY (`b`))"),
213            "(`a` INT, PRIMARY KEY (``))"
214        );
215        assert_eq!(without_primary_clause("(`a` INT)"), "(`a` INT)");
216    }
217}