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
//! ALTER TABLE statement builder
//!
//! This module provides the `AlterTableStatement` type for building SQL ALTER TABLE queries.
use crate::{
backend::QueryBuilder,
types::{ColumnDef, DynIden, ForeignKeyAction, IntoIden, IntoTableRef, TableRef},
};
use super::traits::{QueryBuilderTrait, QueryStatementBuilder, QueryStatementWriter};
/// ALTER TABLE statement builder
///
/// This struct provides a fluent API for constructing ALTER TABLE queries.
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
/// use reinhardt_query::types::ddl::{ColumnDef, ColumnType};
///
/// let query = Query::alter_table()
/// .table("users")
/// .add_column(
/// ColumnDef::new("age")
/// .column_type(ColumnType::Integer)
/// );
/// ```
#[derive(Debug, Clone)]
pub struct AlterTableStatement {
pub(crate) table: Option<TableRef>,
pub(crate) operations: Vec<AlterTableOperation>,
}
/// ALTER TABLE operation
///
/// This enum represents the various operations that can be performed with ALTER TABLE.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum AlterTableOperation {
/// ADD COLUMN
AddColumn(ColumnDef),
/// DROP COLUMN
DropColumn {
/// Column name to drop
name: DynIden,
/// IF EXISTS clause
if_exists: bool,
},
/// RENAME COLUMN
RenameColumn {
/// Old column name
old: DynIden,
/// New column name
new: DynIden,
},
/// MODIFY COLUMN / ALTER COLUMN (type or constraints)
ModifyColumn(ColumnDef),
/// ADD CONSTRAINT
AddConstraint(crate::types::TableConstraint),
/// DROP CONSTRAINT
DropConstraint {
/// Constraint name
name: DynIden,
/// IF EXISTS clause
if_exists: bool,
},
/// RENAME TABLE
RenameTable(DynIden),
}
impl AlterTableStatement {
/// Create a new ALTER TABLE statement
pub fn new() -> Self {
Self {
table: None,
operations: Vec::new(),
}
}
/// Take the ownership of data in the current [`AlterTableStatement`]
pub fn take(&mut self) -> Self {
Self {
table: self.table.take(),
operations: std::mem::take(&mut self.operations),
}
}
/// Set the table to alter
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users");
/// ```
pub fn table<T>(&mut self, tbl: T) -> &mut Self
where
T: IntoTableRef,
{
self.table = Some(tbl.into_table_ref());
self
}
/// Add a column
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
/// use reinhardt_query::types::ddl::{ColumnDef, ColumnType};
///
/// let query = Query::alter_table()
/// .table("users")
/// .add_column(
/// ColumnDef::new("age")
/// .column_type(ColumnType::Integer)
/// .not_null(false)
/// );
/// ```
pub fn add_column(&mut self, column: ColumnDef) -> &mut Self {
self.operations.push(AlterTableOperation::AddColumn(column));
self
}
/// Drop a column
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .drop_column("age");
/// ```
pub fn drop_column<C>(&mut self, column: C) -> &mut Self
where
C: IntoIden,
{
self.operations.push(AlterTableOperation::DropColumn {
name: column.into_iden(),
if_exists: false,
});
self
}
/// Drop a column with IF EXISTS
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .drop_column_if_exists("age");
/// ```
pub fn drop_column_if_exists<C>(&mut self, column: C) -> &mut Self
where
C: IntoIden,
{
self.operations.push(AlterTableOperation::DropColumn {
name: column.into_iden(),
if_exists: true,
});
self
}
/// Rename a column
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .rename_column("old_name", "new_name");
/// ```
pub fn rename_column<C1, C2>(&mut self, old: C1, new: C2) -> &mut Self
where
C1: IntoIden,
C2: IntoIden,
{
self.operations.push(AlterTableOperation::RenameColumn {
old: old.into_iden(),
new: new.into_iden(),
});
self
}
/// Modify a column (type or constraints)
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
/// use reinhardt_query::types::ddl::{ColumnDef, ColumnType};
///
/// let query = Query::alter_table()
/// .table("users")
/// .modify_column(
/// ColumnDef::new("age")
/// .column_type(ColumnType::BigInteger)
/// );
/// ```
pub fn modify_column(&mut self, column: ColumnDef) -> &mut Self {
self.operations
.push(AlterTableOperation::ModifyColumn(column));
self
}
/// Add a constraint
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
/// use reinhardt_query::types::ddl::TableConstraint;
///
/// let query = Query::alter_table()
/// .table("users")
/// .add_constraint(TableConstraint::Unique {
/// name: Some("uq_email".into()),
/// columns: vec!["email".into()],
/// });
/// ```
pub fn add_constraint(&mut self, constraint: crate::types::TableConstraint) -> &mut Self {
self.operations
.push(AlterTableOperation::AddConstraint(constraint));
self
}
/// Drop a constraint
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .drop_constraint("uq_email");
/// ```
pub fn drop_constraint<C>(&mut self, constraint: C) -> &mut Self
where
C: IntoIden,
{
self.operations.push(AlterTableOperation::DropConstraint {
name: constraint.into_iden(),
if_exists: false,
});
self
}
/// Drop a constraint with IF EXISTS
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .drop_constraint_if_exists("uq_email");
/// ```
pub fn drop_constraint_if_exists<C>(&mut self, constraint: C) -> &mut Self
where
C: IntoIden,
{
self.operations.push(AlterTableOperation::DropConstraint {
name: constraint.into_iden(),
if_exists: true,
});
self
}
/// Rename table
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .rename_table("accounts");
/// ```
pub fn rename_table<T>(&mut self, new_name: T) -> &mut Self
where
T: IntoIden,
{
self.operations
.push(AlterTableOperation::RenameTable(new_name.into_iden()));
self
}
/// Add a primary key constraint
///
/// This is a convenience method for adding a PRIMARY KEY constraint.
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .add_primary_key(vec!["id"]);
/// ```
pub fn add_primary_key<I, C>(&mut self, columns: I) -> &mut Self
where
I: IntoIterator<Item = C>,
C: IntoIden,
{
self.operations.push(AlterTableOperation::AddConstraint(
crate::types::TableConstraint::PrimaryKey {
name: None,
columns: columns.into_iter().map(|c| c.into_iden()).collect(),
},
));
self
}
/// Add a unique constraint
///
/// This is a convenience method for adding a UNIQUE constraint.
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::alter_table()
/// .table("users")
/// .add_unique(vec!["email"]);
/// ```
pub fn add_unique<I, C>(&mut self, columns: I) -> &mut Self
where
I: IntoIterator<Item = C>,
C: IntoIden,
{
self.operations.push(AlterTableOperation::AddConstraint(
crate::types::TableConstraint::Unique {
name: None,
columns: columns.into_iter().map(|c| c.into_iden()).collect(),
},
));
self
}
/// Add a foreign key constraint
///
/// This is a convenience method for adding a FOREIGN KEY constraint.
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
/// use reinhardt_query::types::ddl::ForeignKeyAction;
///
/// let query = Query::alter_table()
/// .table("posts")
/// .add_foreign_key(
/// vec!["user_id"],
/// "users",
/// vec!["id"],
/// Some(ForeignKeyAction::Cascade),
/// None,
/// );
/// ```
pub fn add_foreign_key<I1, C1, T, I2, C2>(
&mut self,
columns: I1,
ref_table: T,
ref_columns: I2,
on_delete: Option<ForeignKeyAction>,
on_update: Option<ForeignKeyAction>,
) -> &mut Self
where
I1: IntoIterator<Item = C1>,
C1: IntoIden,
T: IntoTableRef,
I2: IntoIterator<Item = C2>,
C2: IntoIden,
{
self.operations.push(AlterTableOperation::AddConstraint(
crate::types::TableConstraint::ForeignKey {
name: None,
columns: columns.into_iter().map(|c| c.into_iden()).collect(),
ref_table: Box::new(ref_table.into_table_ref()),
ref_columns: ref_columns.into_iter().map(|c| c.into_iden()).collect(),
on_delete,
on_update,
},
));
self
}
}
impl Default for AlterTableStatement {
fn default() -> Self {
Self::new()
}
}
impl QueryStatementBuilder for AlterTableStatement {
fn build_any(&self, query_builder: &dyn QueryBuilderTrait) -> (String, crate::value::Values) {
// Downcast to concrete QueryBuilder type
use std::any::Any;
if let Some(builder) =
(query_builder as &dyn Any).downcast_ref::<crate::backend::PostgresQueryBuilder>()
{
return builder.build_alter_table(self);
}
if let Some(builder) =
(query_builder as &dyn Any).downcast_ref::<crate::backend::MySqlQueryBuilder>()
{
return builder.build_alter_table(self);
}
if let Some(builder) =
(query_builder as &dyn Any).downcast_ref::<crate::backend::SqliteQueryBuilder>()
{
return builder.build_alter_table(self);
}
panic!("Unsupported query builder type");
}
}
impl QueryStatementWriter for AlterTableStatement {}