sea-query 1.0.0

🔱 A dynamic query builder for MySQL, Postgres and SQLite
Documentation
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use super::*;
use crate::write_int;

impl TableBuilder for PostgresQueryBuilder {
    fn prepare_column_def(&self, column_def: &ColumnDef, sql: &mut impl SqlWriter) {
        fn f(this: &PostgresQueryBuilder, column_def: &ColumnDef, sql: &mut impl SqlWriter) {
            this.prepare_column_type_check_auto_increment(column_def, sql);
        }

        self.prepare_column_def_common(column_def, sql, |column_def, sql| f(self, column_def, sql));
    }

    fn prepare_column_type(&self, column_type: &ColumnType, sql: &mut impl SqlWriter) {
        match column_type {
            ColumnType::Char(length) => match length {
                Some(length) => {
                    sql.write_str("char(").unwrap();
                    write_int(sql, *length);
                    sql.write_char(')')
                }
                None => sql.write_str("char"),
            },
            ColumnType::String(length) => match length {
                StringLen::N(length) => {
                    sql.write_str("varchar(").unwrap();
                    write_int(sql, *length);
                    sql.write_char(')')
                }
                _ => sql.write_str("varchar"),
            },
            ColumnType::Text => sql.write_str("text"),
            ColumnType::TinyInteger | ColumnType::TinyUnsigned => sql.write_str("smallint"),
            ColumnType::SmallInteger => sql.write_str("smallint"),
            ColumnType::Integer | ColumnType::SmallUnsigned => sql.write_str("integer"),
            ColumnType::BigInteger | ColumnType::Unsigned | ColumnType::BigUnsigned => {
                sql.write_str("bigint")
            }
            ColumnType::Float => sql.write_str("real"),
            ColumnType::Double => sql.write_str("double precision"),
            ColumnType::Decimal(precision) => match precision {
                Some((precision, scale)) => {
                    sql.write_str("decimal(").unwrap();
                    write_int(sql, *precision);
                    sql.write_str(", ").unwrap();
                    write_int(sql, *scale);
                    sql.write_char(')')
                }
                None => sql.write_str("decimal"),
            },
            ColumnType::DateTime => sql.write_str("timestamp without time zone"),
            ColumnType::Timestamp => sql.write_str("timestamp"),
            ColumnType::TimestampWithTimeZone => sql.write_str("timestamp with time zone"),
            ColumnType::Time => sql.write_str("time"),
            ColumnType::Date => sql.write_str("date"),
            ColumnType::Interval(fields, precision) => {
                sql.write_str("interval").unwrap();

                if let Some(fields) = fields {
                    write!(sql, " {fields}").unwrap();
                }

                if let Some(precision) = precision {
                    sql.write_char('(').unwrap();
                    write_int(sql, *precision);
                    sql.write_char(')').unwrap();
                }
                Ok(())
            }
            ColumnType::Binary(_) | ColumnType::VarBinary(_) | ColumnType::Blob => {
                sql.write_str("bytea")
            }
            ColumnType::Bit(length) => match length {
                Some(length) => {
                    sql.write_str("bit(").unwrap();
                    write_int(sql, *length);
                    sql.write_char(')')
                }
                None => sql.write_str("bit"),
            },
            ColumnType::VarBit(length) => {
                sql.write_str("varbit(").unwrap();
                write_int(sql, *length);
                sql.write_char(')')
            }
            ColumnType::Boolean => sql.write_str("bool"),
            ColumnType::Money(precision) => match precision {
                Some((precision, scale)) => {
                    sql.write_str("money(").unwrap();
                    write_int(sql, *precision);
                    sql.write_str(", ").unwrap();
                    write_int(sql, *scale);
                    sql.write_char(')')
                }
                None => sql.write_str("money"),
            },
            ColumnType::Json => sql.write_str("json"),
            ColumnType::JsonBinary => sql.write_str("jsonb"),
            ColumnType::Uuid => sql.write_str("uuid"),
            ColumnType::Array(elem_type) => {
                self.prepare_column_type(elem_type, sql);
                sql.write_str("[]")
            }
            ColumnType::Vector(size) => match size {
                Some(size) => {
                    sql.write_str("vector(").unwrap();
                    write_int(sql, *size);
                    sql.write_str(")")
                }
                None => sql.write_str("vector"),
            },
            ColumnType::Custom(iden) => sql.write_str(&iden.0),
            ColumnType::Enum { name, .. } => sql.write_str(&name.0),
            ColumnType::Cidr => sql.write_str("cidr"),
            ColumnType::Inet => sql.write_str("inet"),
            ColumnType::MacAddr => sql.write_str("macaddr"),
            ColumnType::Year => unimplemented!("Year is not available in Postgres."),
            ColumnType::LTree => sql.write_str("ltree"),
        }
        .unwrap()
    }

    fn column_spec_auto_increment_keyword(&self) -> &str {
        ""
    }

    fn prepare_table_alter_statement(&self, alter: &TableAlterStatement, sql: &mut impl SqlWriter) {
        if alter.options.is_empty() {
            panic!("No alter option found")
        };
        sql.write_str("ALTER TABLE ").unwrap();
        if let Some(table) = &alter.table {
            self.prepare_table_ref_table_stmt(table, sql);
            sql.write_str(" ").unwrap();
        }

        let mut opts = alter.options.iter();

        join_io!(
            opts,
            opt,
            join {
                sql.write_str(", ").unwrap();
            },
            do {
                match opt {
                    TableAlterOption::AddColumn(AddColumnOption {
                        column,
                        if_not_exists,
                    }) => {
                        sql.write_str("ADD COLUMN ").unwrap();
                        if *if_not_exists {
                            sql.write_str("IF NOT EXISTS ").unwrap();
                        }

                        self.prepare_column_def_common(column, sql, |column_def, sql| {
                            if let Some(column_type) = &column_def.types {
                                write!(sql, " ").unwrap();
                                if column_def.spec.auto_increment {
                                    self.prepare_column_auto_increment(column_type, sql);
                                } else {
                                    self.prepare_column_type(column_type, sql);
                                }
                            }
                        });
                    }
                    TableAlterOption::ModifyColumn(column_def) => {
                        self.prepare_modify_column(sql, column_def);
                    }
                    TableAlterOption::RenameColumn(from_name, to_name) => {
                        sql.write_str("RENAME COLUMN ").unwrap();
                        self.prepare_iden(from_name, sql);
                        sql.write_str(" TO ").unwrap();
                        self.prepare_iden(to_name, sql);
                    }
                    TableAlterOption::DropColumn(DropColumnOption{
                        column_name,
                        if_exists
                    }) => {
                        sql.write_str("DROP COLUMN ").unwrap();
                         if *if_exists {
                            sql.write_str("IF EXISTS ").unwrap();
                        }
                        self.prepare_iden(column_name, sql);
                    }
                    TableAlterOption::DropForeignKey(name) => {
                        let mut foreign_key = TableForeignKey::new();
                        foreign_key.name(name.to_string());
                        let drop = ForeignKeyDropStatement {
                            foreign_key,
                            table: None,
                        };
                        self.prepare_foreign_key_drop_statement_internal(
                            &drop,
                            sql,
                            Mode::TableAlter,
                        );
                    }
                    TableAlterOption::AddForeignKey(foreign_key) => {
                        let create = ForeignKeyCreateStatement {
                            foreign_key: foreign_key.to_owned(),
                        };
                        self.prepare_foreign_key_create_statement_internal(
                            &create,
                            sql,
                            Mode::TableAlter,
                        );
                    }
                    TableAlterOption::DropConstraint(name) => {
                        sql.write_str("DROP CONSTRAINT ").unwrap();
                        self.prepare_iden(name, sql);
                    }
                }
            }
        );
    }

    fn prepare_table_rename_statement(
        &self,
        rename: &TableRenameStatement,
        sql: &mut impl SqlWriter,
    ) {
        sql.write_str("ALTER TABLE ").unwrap();
        if let Some(from_name) = &rename.from_name {
            self.prepare_table_ref_table_stmt(from_name, sql);
        }
        sql.write_str(" RENAME TO ").unwrap();
        if let Some(to_name) = &rename.to_name {
            self.prepare_table_ref_table_stmt(to_name, sql);
        }
    }

    fn prepare_partition_by(&self, partition_by: &PartitionBy, sql: &mut impl SqlWriter) {
        match partition_by {
            PartitionBy::Range(cols) => {
                sql.write_str("RANGE (").unwrap();
                self.prepare_partition_cols(cols, sql);
                sql.write_char(')').unwrap();
            }
            PartitionBy::List(cols) => {
                sql.write_str("LIST (").unwrap();
                self.prepare_partition_cols(cols, sql);
                sql.write_char(')').unwrap();
            }
            PartitionBy::Hash(cols) => {
                sql.write_str("HASH (").unwrap();
                self.prepare_partition_cols(cols, sql);
                sql.write_char(')').unwrap();
            }
            PartitionBy::Key(_) => panic!("Postgres does not support PARTITION BY KEY"),
        }
    }

    fn prepare_partition_values(
        &self,
        partition_values: &PartitionValues,
        sql: &mut impl SqlWriter,
    ) {
        sql.write_str("FOR VALUES ").unwrap();
        match partition_values {
            PartitionValues::In(values) => {
                sql.write_str("IN (").unwrap();
                self.prepare_partition_exprs(values, sql);
                sql.write_char(')').unwrap();
            }
            PartitionValues::FromTo(from, to) => {
                sql.write_str("FROM (").unwrap();
                self.prepare_partition_exprs(from, sql);
                sql.write_str(") TO (").unwrap();
                self.prepare_partition_exprs(to, sql);
                sql.write_char(')').unwrap();
            }
            PartitionValues::LessThan(_) => panic!("Postgres does not support VALUES LESS THAN"),
            PartitionValues::With(modulus, remainder) => {
                write!(sql, "WITH (MODULUS {modulus}, REMAINDER {remainder})").unwrap();
            }
        }
    }
}

impl PostgresQueryBuilder {
    fn prepare_partition_cols(&self, cols: &[DynIden], sql: &mut impl SqlWriter) {
        let mut first = true;
        for col in cols {
            if !first {
                sql.write_str(", ").unwrap();
            }
            self.prepare_iden(col, sql);
            first = false;
        }
    }

    fn prepare_partition_exprs(&self, exprs: &[Expr], sql: &mut impl SqlWriter) {
        let mut first = true;
        for expr in exprs {
            if !first {
                sql.write_str(", ").unwrap();
            }
            self.prepare_expr(expr, sql);
            first = false;
        }
    }
}

impl PostgresQueryBuilder {
    fn prepare_column_auto_increment(&self, column_type: &ColumnType, sql: &mut impl SqlWriter) {
        let num_ty = if cfg!(feature = "option-postgres-use-serial") {
            match column_type {
                ColumnType::SmallInteger => "smallserial",
                ColumnType::Integer => "serial",
                ColumnType::BigInteger => "bigserial",
                _ => unimplemented!("{:?} doesn't support auto increment", column_type),
            }
        } else {
            match column_type {
                ColumnType::SmallInteger => "smallint GENERATED BY DEFAULT AS IDENTITY",
                ColumnType::Integer => "integer GENERATED BY DEFAULT AS IDENTITY",
                ColumnType::BigInteger => "bigint GENERATED BY DEFAULT AS IDENTITY",
                _ => unimplemented!("{:?} doesn't support auto increment", column_type),
            }
        };

        sql.write_str(num_ty).unwrap();
    }

    fn prepare_column_type_check_auto_increment(
        &self,
        column_def: &ColumnDef,
        sql: &mut impl SqlWriter,
    ) {
        if let Some(column_type) = &column_def.types {
            let is_auto_increment = column_def.spec.auto_increment;

            sql.write_str(" ").unwrap();

            if is_auto_increment {
                self.prepare_column_auto_increment(column_type, sql);
            } else {
                self.prepare_column_type(column_type, sql);
            }
        }
    }

    fn prepare_column_def_common<F, W>(&self, column_def: &ColumnDef, sql: &mut W, f: F)
    where
        F: Fn(&ColumnDef, &mut W),
        W: SqlWriter,
    {
        self.prepare_iden(&column_def.name, sql);

        f(column_def, sql);

        self.prepare_column_spec(&column_def.spec, sql);
    }

    fn prepare_modify_column(&self, sql: &mut impl SqlWriter, column_def: &ColumnDef) {
        let mut is_first = true;

        macro_rules! write_comma_if_not_first {
            () => {
                if !is_first {
                    write!(sql, ", ").unwrap();
                } else {
                    is_first = false
                }
            };
        }

        if let Some(column_type) = &column_def.types {
            write!(sql, "ALTER COLUMN ").unwrap();
            self.prepare_iden(&column_def.name, sql);
            write!(sql, " TYPE ").unwrap();
            self.prepare_column_type(column_type, sql);
            is_first = false;
        }

        if column_def.spec.auto_increment {
            //
        }

        if let Some(nullable) = column_def.spec.nullable {
            write_comma_if_not_first!();
            write!(sql, "ALTER COLUMN ").unwrap();
            self.prepare_iden(&column_def.name, sql);
            if nullable {
                write!(sql, " DROP NOT NULL").unwrap();
            } else {
                write!(sql, " SET NOT NULL").unwrap();
            }
        }

        if let Some(default) = &column_def.spec.default {
            write_comma_if_not_first!();
            write!(sql, "ALTER COLUMN ").unwrap();
            self.prepare_iden(&column_def.name, sql);
            write!(sql, " SET DEFAULT ").unwrap();
            QueryBuilder::prepare_expr(self, default, sql);
        }
        if column_def.spec.unique {
            write_comma_if_not_first!();
            write!(sql, "ADD UNIQUE (").unwrap();
            self.prepare_iden(&column_def.name, sql);
            write!(sql, ")").unwrap();
        }
        if column_def.spec.primary_key {
            write_comma_if_not_first!();
            write!(sql, "ADD PRIMARY KEY (").unwrap();
            self.prepare_iden(&column_def.name, sql);
            write!(sql, ")").unwrap();
        }
        if let Some(check) = &column_def.spec.check {
            write_comma_if_not_first!();
            self.prepare_check_constraint(check, sql);
        }

        if let Some(x) = &column_def.spec.generated {
            let _ = x;
        }

        if let Some(x) = &column_def.spec.comment {
            let _ = x;
        }

        if let Some(expr) = &column_def.spec.using {
            write!(sql, " USING ").unwrap();
            QueryBuilder::prepare_expr(self, expr, sql);
        }

        if let Some(extra) = &column_def.spec.extra {
            write!(sql, "{extra}").unwrap()
        }

        let _ = is_first;
    }
}