use crate::SqlWriterValues;
use crate::types::DropBehavior;
use crate::types::TableName;
use crate::types::write_table_name;
use crate::writer::SqlWriter;
#[derive(Default, Debug, Clone)]
pub struct DropIndex {
indexes: Vec<TableName>,
concurrently: bool,
if_exists: bool,
behavior: Option<DropBehavior>,
}
impl DropIndex {
pub fn new() -> Self {
Self::default()
}
pub fn to_values(&self) -> SqlWriterValues {
let mut w = SqlWriterValues::new();
write_drop_index(&mut w, self);
w
}
pub fn to_sql(&self) -> String {
let mut sql = String::new();
write_drop_index(&mut sql, self);
sql
}
pub fn index<N>(mut self, index: N) -> Self
where
N: Into<TableName>,
{
self.indexes.push(index.into());
self
}
pub fn indexes<I, N>(mut self, indexes: I) -> Self
where
I: IntoIterator<Item = N>,
N: Into<TableName>,
{
self.indexes.extend(indexes.into_iter().map(Into::into));
self
}
pub fn if_exists(mut self) -> Self {
self.if_exists = true;
self
}
pub fn concurrently(mut self) -> Self {
self.concurrently = true;
self
}
pub fn cascade(mut self) -> Self {
self.behavior = Some(DropBehavior::Cascade);
self
}
pub fn restrict(mut self) -> Self {
self.behavior = Some(DropBehavior::Restrict);
self
}
}
fn write_drop_index<W: SqlWriter>(w: &mut W, drop_index: &DropIndex) {
w.push_str("DROP INDEX ");
if drop_index.concurrently {
w.push_str("CONCURRENTLY ");
}
if drop_index.if_exists {
w.push_str("IF EXISTS ");
}
for (i, index) in drop_index.indexes.iter().enumerate() {
if i > 0 {
w.push_str(", ");
}
write_table_name(w, index);
}
if let Some(behavior) = drop_index.behavior {
w.push_char(' ');
match behavior {
DropBehavior::Cascade => w.push_str("CASCADE"),
DropBehavior::Restrict => w.push_str("RESTRICT"),
}
}
}