use keelson_core::clause::{HasSet, HasTableRef, HasValues, Set, TableRef, Values};
use keelson_core::expr::{Expr, IntoExpr, IntoExprList};
use keelson_core::{Dialect, Error, Expression, Mod, Query, QueryExtensions, QueryType, SqlWriter};
use super::insert::write_target_and_row_source;
use super::write_hints_and_modifiers;
use crate::Mysql;
use crate::extras::{HasHints, HasModifiers, Hints, Modifiers};
#[derive(Debug, Clone, Default)]
pub struct ReplaceQuery {
pub hints: Hints,
pub modifiers: Modifiers,
pub table: TableRef,
pub values: Values,
pub set: Set,
}
impl ReplaceQuery {
pub fn new() -> ReplaceQuery {
ReplaceQuery::default()
}
pub fn apply(&mut self, mods: impl Mod<ReplaceQuery>) {
mods.apply(self);
}
}
impl Expression for ReplaceQuery {
fn write_sql(&self, w: &mut SqlWriter<'_>) {
if self.table.is_empty() {
w.record_error(Error::Incomplete("the target table of a REPLACE"));
return;
}
w.push_str("REPLACE ");
write_hints_and_modifiers(w, &self.hints, &self.modifiers);
w.push_str("INTO ");
write_target_and_row_source(w, &self.table, &self.set, &self.values);
}
}
impl Query for ReplaceQuery {
fn query_type(&self) -> QueryType {
QueryType::Insert
}
fn dialect(&self) -> &dyn Dialect {
&Mysql
}
}
impl<H, L, M> QueryExtensions<H, L, M> for ReplaceQuery {}
impl IntoExpr for ReplaceQuery {
fn into_expr(self) -> Expr {
crate::query(self)
}
}
impl IntoExprList for ReplaceQuery {
fn into_expr_list(self) -> Vec<Expr> {
vec![self.into_expr()]
}
}
impl HasHints for ReplaceQuery {
fn hints_mut(&mut self) -> &mut Hints {
&mut self.hints
}
}
impl HasModifiers for ReplaceQuery {
fn modifiers_mut(&mut self) -> &mut Modifiers {
&mut self.modifiers
}
}
impl HasTableRef for ReplaceQuery {
fn table_ref_mut(&mut self) -> &mut TableRef {
&mut self.table
}
}
impl HasValues for ReplaceQuery {
fn values_mut(&mut self) -> &mut Values {
&mut self.values
}
}
impl HasSet for ReplaceQuery {
fn set_mut(&mut self) -> &mut Set {
&mut self.set
}
}