sea_query/index/
create.rs

1use inherent::inherent;
2
3use crate::{backend::SchemaBuilder, types::*, SchemaStatementBuilder};
4use crate::{ConditionHolder, ConditionalStatement, IntoCondition};
5
6use super::common::*;
7
8/// Create an index for an existing table
9///
10/// # Examples
11///
12/// ```
13/// use sea_query::{tests_cfg::*, *};
14///
15/// let index = Index::create()
16///     .name("idx-glyph-aspect")
17///     .table(Glyph::Table)
18///     .col(Glyph::Aspect)
19///     .to_owned();
20///
21/// assert_eq!(
22///     index.to_string(MysqlQueryBuilder),
23///     r#"CREATE INDEX `idx-glyph-aspect` ON `glyph` (`aspect`)"#
24/// );
25/// assert_eq!(
26///     index.to_string(PostgresQueryBuilder),
27///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect")"#
28/// );
29/// assert_eq!(
30///     index.to_string(SqliteQueryBuilder),
31///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect")"#
32/// );
33/// ```
34/// Create index if not exists
35/// ```
36/// use sea_query::{tests_cfg::*, *};
37///
38/// let index = Index::create()
39///     .if_not_exists()
40///     .name("idx-glyph-aspect")
41///     .table(Glyph::Table)
42///     .col(Glyph::Aspect)
43///     .to_owned();
44///
45/// assert_eq!(
46///     index.to_string(MysqlQueryBuilder),
47///     r#"CREATE INDEX `idx-glyph-aspect` ON `glyph` (`aspect`)"#
48/// );
49/// assert_eq!(
50///     index.to_string(PostgresQueryBuilder),
51///     r#"CREATE INDEX IF NOT EXISTS "idx-glyph-aspect" ON "glyph" ("aspect")"#
52/// );
53/// assert_eq!(
54///     index.to_string(SqliteQueryBuilder),
55///     r#"CREATE INDEX IF NOT EXISTS "idx-glyph-aspect" ON "glyph" ("aspect")"#
56/// );
57/// ```
58/// Index with prefix
59/// ```
60/// use sea_query::{tests_cfg::*, *};
61///
62/// let index = Index::create()
63///     .name("idx-glyph-aspect")
64///     .table(Glyph::Table)
65///     .col((Glyph::Aspect, 128))
66///     .to_owned();
67///
68/// assert_eq!(
69///     index.to_string(MysqlQueryBuilder),
70///     r#"CREATE INDEX `idx-glyph-aspect` ON `glyph` (`aspect` (128))"#
71/// );
72/// assert_eq!(
73///     index.to_string(PostgresQueryBuilder),
74///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" (128))"#
75/// );
76/// assert_eq!(
77///     index.to_string(SqliteQueryBuilder),
78///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect")"#
79/// );
80/// ```
81/// Index with order
82/// ```
83/// use sea_query::{tests_cfg::*, *};
84///
85/// let index = Index::create()
86///     .name("idx-glyph-aspect")
87///     .table(Glyph::Table)
88///     .col((Glyph::Aspect, IndexOrder::Desc))
89///     .to_owned();
90///
91/// assert_eq!(
92///     index.to_string(MysqlQueryBuilder),
93///     r#"CREATE INDEX `idx-glyph-aspect` ON `glyph` (`aspect` DESC)"#
94/// );
95/// assert_eq!(
96///     index.to_string(PostgresQueryBuilder),
97///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" DESC)"#
98/// );
99/// assert_eq!(
100///     index.to_string(SqliteQueryBuilder),
101///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" DESC)"#
102/// );
103/// ```
104/// Index on multi-columns
105/// ```
106/// use sea_query::{tests_cfg::*, *};
107///
108/// let index = Index::create()
109///     .name("idx-glyph-aspect")
110///     .table(Glyph::Table)
111///     .col((Glyph::Image, IndexOrder::Asc))
112///     .col((Glyph::Aspect, IndexOrder::Desc))
113///     .unique()
114///     .to_owned();
115///
116/// assert_eq!(
117///     index.to_string(MysqlQueryBuilder),
118///     r#"CREATE UNIQUE INDEX `idx-glyph-aspect` ON `glyph` (`image` ASC, `aspect` DESC)"#
119/// );
120/// assert_eq!(
121///     index.to_string(PostgresQueryBuilder),
122///     r#"CREATE UNIQUE INDEX "idx-glyph-aspect" ON "glyph" ("image" ASC, "aspect" DESC)"#
123/// );
124/// assert_eq!(
125///     index.to_string(SqliteQueryBuilder),
126///     r#"CREATE UNIQUE INDEX "idx-glyph-aspect" ON "glyph" ("image" ASC, "aspect" DESC)"#
127/// );
128/// ```
129/// Index with prefix and order
130/// ```
131/// use sea_query::{tests_cfg::*, *};
132///
133/// let index = Index::create()
134///     .name("idx-glyph-aspect")
135///     .table(Glyph::Table)
136///     .col((Glyph::Aspect, 64, IndexOrder::Asc))
137///     .to_owned();
138///
139/// assert_eq!(
140///     index.to_string(MysqlQueryBuilder),
141///     r#"CREATE INDEX `idx-glyph-aspect` ON `glyph` (`aspect` (64) ASC)"#
142/// );
143/// assert_eq!(
144///     index.to_string(PostgresQueryBuilder),
145///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" (64) ASC)"#
146/// );
147/// assert_eq!(
148///     index.to_string(SqliteQueryBuilder),
149///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" ASC)"#
150/// );
151/// ```
152///
153/// Partial Index with prefix and order
154/// ```
155/// use sea_query::{tests_cfg::*, *};
156///
157/// let index = Index::create()
158///     .name("idx-glyph-aspect")
159///     .table(Glyph::Table)
160///     .col((Glyph::Aspect, 64, IndexOrder::Asc))
161///     .and_where(Expr::col((Glyph::Table, Glyph::Aspect)).is_in(vec![3, 4]))
162///     .to_owned();
163///
164/// assert_eq!(
165///     index.to_string(PostgresQueryBuilder),
166///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" (64) ASC) WHERE "glyph"."aspect" IN (3, 4)"#
167/// );
168/// assert_eq!(
169///     index.to_string(SqliteQueryBuilder),
170///     r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" ASC) WHERE "glyph"."aspect" IN (3, 4)"#
171/// );
172/// ```
173///
174/// Index include non-key columns
175/// ```
176/// use sea_query::{tests_cfg::*, *};
177///
178/// let index = Index::create()
179///     .name("idx-font-name-include-language")
180///     .table(Font::Table)
181///     .col(Font::Name)
182///     .include(Font::Language)
183///     .to_owned();
184///
185/// assert_eq!(
186///     index.to_string(PostgresQueryBuilder),
187///     r#"CREATE INDEX "idx-font-name-include-language" ON "font" ("name") INCLUDE ("language")"#
188/// )
189/// ```
190#[derive(Default, Debug, Clone)]
191pub struct IndexCreateStatement {
192    pub(crate) table: Option<TableRef>,
193    pub(crate) index: TableIndex,
194    pub(crate) primary: bool,
195    pub(crate) unique: bool,
196    pub(crate) nulls_not_distinct: bool,
197    pub(crate) index_type: Option<IndexType>,
198    pub(crate) if_not_exists: bool,
199    pub(crate) r#where: ConditionHolder,
200    pub(crate) include_columns: Vec<DynIden>,
201}
202
203/// Specification of a table index
204#[derive(Debug, Clone)]
205pub enum IndexType {
206    BTree,
207    FullText,
208    Hash,
209    Custom(DynIden),
210}
211
212impl IndexCreateStatement {
213    /// Construct a new [`IndexCreateStatement`]
214    pub fn new() -> Self {
215        Self {
216            table: None,
217            index: Default::default(),
218            primary: false,
219            unique: false,
220            nulls_not_distinct: false,
221            index_type: None,
222            if_not_exists: false,
223            r#where: ConditionHolder::new(),
224            include_columns: vec![],
225        }
226    }
227
228    /// Create index if index not exists
229    pub fn if_not_exists(&mut self) -> &mut Self {
230        self.if_not_exists = true;
231        self
232    }
233
234    /// Set index name
235    pub fn name<T>(&mut self, name: T) -> &mut Self
236    where
237        T: Into<String>,
238    {
239        self.index.name(name);
240        self
241    }
242
243    /// Set target table
244    pub fn table<T>(&mut self, table: T) -> &mut Self
245    where
246        T: IntoTableRef,
247    {
248        self.table = Some(table.into_table_ref());
249        self
250    }
251
252    /// Add index column
253    pub fn col<C>(&mut self, col: C) -> &mut Self
254    where
255        C: IntoIndexColumn,
256    {
257        self.index.col(col.into_index_column());
258        self
259    }
260
261    /// Set index as primary
262    pub fn primary(&mut self) -> &mut Self {
263        self.primary = true;
264        self
265    }
266
267    /// Set index as unique
268    pub fn unique(&mut self) -> &mut Self {
269        self.unique = true;
270        self
271    }
272
273    /// Set nulls to not be treated as distinct values. Only available on Postgres.
274    pub fn nulls_not_distinct(&mut self) -> &mut Self {
275        self.nulls_not_distinct = true;
276        self
277    }
278
279    /// Set index as full text.
280    /// On MySQL, this is `FULLTEXT`.
281    /// On PgSQL, this is `GIN`.
282    pub fn full_text(&mut self) -> &mut Self {
283        self.index_type(IndexType::FullText)
284    }
285
286    /// Set index type. Not available on Sqlite.
287    pub fn index_type(&mut self, index_type: IndexType) -> &mut Self {
288        self.index_type = Some(index_type);
289        self
290    }
291
292    pub fn include<C>(&mut self, col: C) -> &mut Self
293    where
294        C: IntoIden,
295    {
296        self.include_columns.push(col.into_iden());
297        self
298    }
299
300    pub fn is_primary_key(&self) -> bool {
301        self.primary
302    }
303
304    pub fn is_unique_key(&self) -> bool {
305        self.unique
306    }
307
308    pub fn is_nulls_not_distinct(&self) -> bool {
309        self.nulls_not_distinct
310    }
311
312    pub fn get_index_spec(&self) -> &TableIndex {
313        &self.index
314    }
315
316    pub fn take(&mut self) -> Self {
317        Self {
318            table: self.table.take(),
319            index: self.index.take(),
320            primary: self.primary,
321            unique: self.unique,
322            nulls_not_distinct: self.nulls_not_distinct,
323            index_type: self.index_type.take(),
324            if_not_exists: self.if_not_exists,
325            r#where: self.r#where.clone(),
326            include_columns: self.include_columns.clone(),
327        }
328    }
329}
330
331#[inherent]
332impl SchemaStatementBuilder for IndexCreateStatement {
333    pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
334        let mut sql = String::with_capacity(256);
335        schema_builder.prepare_index_create_statement(self, &mut sql);
336        sql
337    }
338
339    pub fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String {
340        let mut sql = String::with_capacity(256);
341        schema_builder.prepare_index_create_statement(self, &mut sql);
342        sql
343    }
344
345    pub fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String;
346}
347
348impl ConditionalStatement for IndexCreateStatement {
349    fn and_or_where(&mut self, condition: LogicalChainOper) -> &mut Self {
350        self.r#where.add_and_or(condition);
351        self
352    }
353
354    fn cond_where<C>(&mut self, condition: C) -> &mut Self
355    where
356        C: IntoCondition,
357    {
358        self.r#where.add_condition(condition.into_condition());
359        self
360    }
361}