Skip to content

Commit e551690

Browse files
committed
fix the action ADD and DROP to override the previous value
1 parent 9ddd716 commit e551690

File tree

4 files changed

+329
-209
lines changed

4 files changed

+329
-209
lines changed

src/alter_table/alter_table.rs

Lines changed: 62 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,51 @@ use crate::{
99
impl TransactionQuery for AlterTable {}
1010

1111
impl AlterTable {
12-
/// Adds columns or table constraints.
13-
/// Multiples call of this method will build the SQL respecting the order of the calls
12+
/// Adds columns or table constraints, this method overrides the previous value
1413
///
1514
/// ### Example
1615
///
1716
/// ```
1817
/// # use sql_query_builder as sql;
1918
/// let query = sql::AlterTable::new()
2019
/// .add("COLUMN age int not null")
21-
/// .add("CONSTRAINT age check(age >= 0)")
2220
/// .as_string();
2321
///
24-
/// # let expected = "\
25-
/// # ADD COLUMN age int not null, \
26-
/// # ADD CONSTRAINT age check(age >= 0)\
27-
/// # ";
22+
/// # let expected = "ADD COLUMN age int not null";
2823
/// # assert_eq!(expected, query);
2924
/// ```
3025
///
3126
/// Outputs
3227
///
3328
/// ```sql
34-
/// ADD COLUMN age int not null,
35-
/// ADD CONSTRAINT age check(age >= 0)
29+
/// ADD COLUMN age int not null
30+
/// ```
31+
///
32+
///
33+
/// Available on crate feature `postgresql` only.
34+
/// Multiples call of this method will build the SQL respecting the order of the calls
35+
///
36+
/// ### Example
37+
///
38+
/// ```
39+
/// # #[cfg(any(feature = "postgresql"))]
40+
/// # {
41+
/// # use sql_query_builder as sql;
42+
/// let query = sql::AlterTable::new()
43+
/// .add("COLUMN login varchar not null")
44+
/// .add("CONSTRAINT login_unique unique(login)")
45+
/// .as_string();
46+
///
47+
/// # let expected = "ADD COLUMN login varchar not null, ADD CONSTRAINT login_unique unique(login)";
48+
/// # assert_eq!(expected, query);
49+
/// # }
50+
/// ```
51+
///
52+
/// Outputs
53+
///
54+
/// ```sql
55+
/// ADD COLUMN login varchar not null,
56+
/// ADD CONSTRAINT login_unique unique(login)
3657
/// ```
3758
pub fn add(mut self, add_exp: &str) -> Self {
3859
let action = AlterTableActionItem(AlterTableOrderedAction::Add, add_exp.trim().to_string());
@@ -102,8 +123,6 @@ impl AlterTable {
102123
/// let query = sql::AlterTable::new()
103124
/// .alter_table("users")
104125
/// .add("name varchar(100) not null")
105-
/// .add("login varchar(40) not null")
106-
/// .add("constraint users_login_key unique(login)")
107126
/// .debug()
108127
/// .as_string();
109128
/// ```
@@ -113,9 +132,7 @@ impl AlterTable {
113132
/// ```sql
114133
/// -- ------------------------------------------------------------------------------
115134
/// ALTER TABLE users
116-
/// ADD name varchar(100) not null,
117-
/// ADD login varchar(40) not null,
118-
/// ADD constraint users_login_key unique(login)
135+
/// ADD name varchar(100) not null
119136
/// -- ------------------------------------------------------------------------------
120137
/// ```
121138
pub fn debug(self) -> Self {
@@ -124,8 +141,7 @@ impl AlterTable {
124141
self
125142
}
126143

127-
/// Drops columns or table constraints.
128-
/// Multiples call of this method will build the SQL respecting the order of the calls
144+
/// Drops columns or table constraints, this method overrides the previous value.
129145
///
130146
/// ### Example
131147
///
@@ -144,6 +160,31 @@ impl AlterTable {
144160
/// ```sql
145161
/// DROP column login
146162
/// ```
163+
///
164+
/// Available on crate feature `postgresql` only.
165+
/// Multiples call of this method will build the SQL respecting the order of the calls
166+
///
167+
/// ### Example
168+
///
169+
/// ```
170+
/// # #[cfg(any(feature = "postgresql"))]
171+
/// # {
172+
/// # use sql_query_builder as sql;
173+
/// let query = sql::AlterTable::new()
174+
/// .drop("column login")
175+
/// .drop("constraint login_unique")
176+
/// .as_string();
177+
///
178+
/// # let expected = "DROP column login, DROP constraint login_unique";
179+
/// # assert_eq!(expected, query);
180+
/// # }
181+
/// ```
182+
///
183+
/// Outputs
184+
///
185+
/// ```sql
186+
/// DROP column login, DROP constraint login_unique
187+
/// ```
147188
pub fn drop(mut self, drop_exp: &str) -> Self {
148189
let action = AlterTableActionItem(AlterTableOrderedAction::Drop, drop_exp.trim().to_string());
149190
push_unique(&mut self._ordered_actions, action);
@@ -163,7 +204,7 @@ impl AlterTable {
163204
self
164205
}
165206

166-
/// Adds at the beginning a raw SQL query. Is useful to create a more complex alter table signature like the example below.
207+
/// Adds at the beginning a raw SQL query. Is useful to create a more complex alter table signature.
167208
///
168209
/// ### Example
169210
///
@@ -221,21 +262,21 @@ impl AlterTable {
221262
///
222263
/// ```
223264
/// # use sql_query_builder as sql;
224-
/// let raw = "ALTER TABLE users";
265+
/// let raw = "/* alter table command */";
225266
///
226267
/// let query = sql::AlterTable::new()
227268
/// .raw_before(sql::AlterTableAction::AlterTable, raw)
228-
/// .add("COLUMN id")
269+
/// .alter_table("users")
229270
/// .as_string();
230271
///
231-
/// # let expected = "ALTER TABLE users ADD COLUMN id";
272+
/// # let expected = "/* alter table command */ ALTER TABLE users";
232273
/// # assert_eq!(expected, query);
233274
/// ```
234275
///
235276
/// Output
236277
///
237278
/// ```sql
238-
/// ALTER TABLE users RENAME TO users_old
279+
/// /* alter table command */ ALTER TABLE users
239280
/// ```
240281
pub fn raw_before(mut self, action: AlterTableAction, raw_sql: &str) -> Self {
241282
self._raw_before.push((action, raw_sql.trim().to_string()));

src/alter_table/alter_table_internal.rs

Lines changed: 49 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
concat::{concat_raw_before_after, Concat},
33
fmt,
4-
structure::{AlterTable, AlterTableAction, AlterTableActionItem, AlterTableOrderedAction},
4+
structure::{AlterTable, AlterTableAction, AlterTableOrderedAction},
55
};
66

77
impl Concat for AlterTable {
@@ -43,32 +43,52 @@ impl AlterTable {
4343
}
4444

4545
fn concat_ordered_actions(&self, query: String, fmts: &fmt::Formatter) -> String {
46-
let fmt::Formatter {
47-
comma,
48-
lb,
49-
indent,
50-
space,
51-
..
52-
} = fmts;
53-
54-
let actions = self
55-
._ordered_actions
56-
.iter()
57-
.filter(|item| item.1.is_empty() == false)
58-
.map(|item| {
59-
let AlterTableActionItem(action, content) = item;
60-
match action {
61-
AlterTableOrderedAction::Add => format!("{lb}{indent}ADD {content}"),
62-
AlterTableOrderedAction::Drop => format!("{lb}{indent}DROP {content}"),
63-
#[cfg(any(feature = "postgresql"))]
64-
AlterTableOrderedAction::Alter => format!("{lb}{indent}ALTER {content}"),
65-
}
66-
})
67-
.collect::<Vec<_>>()
68-
.join(comma)
69-
.to_string();
70-
71-
format!("{query}{actions}{space}")
46+
let actions = self._ordered_actions.iter().filter(|item| item.1.is_empty() == false);
47+
48+
#[cfg(any(feature = "postgresql"))]
49+
{
50+
use crate::structure::AlterTableActionItem;
51+
52+
let fmt::Formatter {
53+
comma,
54+
lb,
55+
indent,
56+
space,
57+
..
58+
} = fmts;
59+
60+
let sql = actions
61+
.map(|item| {
62+
let AlterTableActionItem(action, content) = item;
63+
match action {
64+
AlterTableOrderedAction::Add => format!("{lb}{indent}ADD{space}{content}"),
65+
AlterTableOrderedAction::Drop => format!("{lb}{indent}DROP{space}{content}"),
66+
#[cfg(any(feature = "postgresql"))]
67+
AlterTableOrderedAction::Alter => format!("{lb}{indent}ALTER{space}{content}"),
68+
}
69+
})
70+
.collect::<Vec<_>>()
71+
.join(comma)
72+
.to_string();
73+
74+
format!("{query}{sql}{space}")
75+
}
76+
77+
#[cfg(not(any(feature = "postgresql")))]
78+
{
79+
let fmt::Formatter { lb, space, .. } = fmts;
80+
81+
if let Some(item) = actions.last() {
82+
let (sql, clause) = match item.0 {
83+
AlterTableOrderedAction::Add => (format!("ADD{space}{}{space}{lb}", item.1), AlterTableAction::Add),
84+
AlterTableOrderedAction::Drop => (format!("DROP{space}{}{space}{lb}", item.1), AlterTableAction::Drop),
85+
};
86+
87+
return concat_raw_before_after(&self._raw_before, &self._raw_after, query, fmts, clause, sql);
88+
}
89+
90+
query
91+
}
7292
}
7393

7494
#[cfg(any(feature = "postgresql", feature = "sqlite"))]
@@ -94,12 +114,11 @@ impl AlterTable {
94114

95115
#[cfg(any(feature = "postgresql", feature = "sqlite"))]
96116
fn concat_rename_to(&self, query: String, fmts: &fmt::Formatter) -> String {
97-
let fmt::Formatter { space, comma, .. } = fmts;
117+
let fmt::Formatter { lb, space, .. } = fmts;
98118
let sql = if self._rename_to.is_empty() == false {
99119
let table_name = &self._rename_to;
100-
let space_or_comma = if self._ordered_actions.is_empty() { space } else { comma };
101120

102-
format!("RENAME TO{space}{table_name}{space_or_comma}")
121+
format!("RENAME TO{space}{table_name}{space}{lb}")
103122
} else {
104123
"".to_string()
105124
};

src/structure.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,16 @@ use std::sync::Arc;
1616
/// let query = sql::AlterTable::new()
1717
/// .alter_table("users")
1818
/// .add("COLUMN id serial primary key")
19-
/// .add("COLUMN login varchar(40) not null")
20-
/// .drop("CONSTRAINT users_login_key")
2119
/// .as_string();
2220
///
23-
/// # let expected = "\
24-
/// # ALTER TABLE users \
25-
/// # ADD COLUMN id serial primary key, \
26-
/// # ADD COLUMN login varchar(40) not null, \
27-
/// # DROP CONSTRAINT users_login_key\
28-
/// # ";
21+
/// # let expected = "ALTER TABLE users ADD COLUMN id serial primary key";
2922
/// # assert_eq!(expected, query);
3023
/// ```
3124
///
32-
/// Output (indented for readability)
25+
/// Output
3326
///
3427
/// ```sql
35-
/// ALTER TABLE users
36-
/// ADD COLUMN id serial primary key,
37-
/// ADD COLUMN login varchar(40) not null,
38-
/// DROP CONSTRAINT users_login_key
28+
/// ALTER TABLE users ADD COLUMN id serial primary key
3929
/// ```
4030
#[derive(Default, Clone)]
4131
pub struct AlterTable {
@@ -79,6 +69,12 @@ pub enum AlterTableAction {
7969
#[cfg_attr(docsrs, doc(cfg(feature = "postgresql")))]
8070
#[cfg_attr(docsrs, doc(cfg(feature = "sqlite")))]
8171
RenameTo,
72+
73+
#[cfg(not(any(feature = "postgresql")))]
74+
Add,
75+
76+
#[cfg(not(any(feature = "postgresql")))]
77+
Drop,
8278
}
8379

8480
#[cfg(any(feature = "postgresql", feature = "sqlite"))]

0 commit comments

Comments
 (0)