Skip to content

clearing/resetting fields in SelectStatement #1005

@chungwong

Description

@chungwong

Motivation

From time to time, it is convenient to modify SelectStatment,

let mut query: SelectStatment = todo!();
query
// this exists already
.clear_selects()
.columns(..)
// non-existent
.clear_group_by()
// adding new group by
.add_group_by(..)
// non-existent
.clear_having()

Proposed Solutions

Naively, I was trying

--- a/src/query/select.rs
+++ b/src/query/select.rs
@@ -356,6 +356,12 @@ impl SelectStatement {
         self
     }
 
+    /// Clear the WHERE clause
+    pub fn clear_where(&mut self) -> &mut Self {
+        self.r#where = Vec::new();
+        self
+    }
+
     /// Add an expression to the select expression list.
     ///
     /// # Examples
@@ -1945,6 +1951,12 @@ impl SelectStatement {
         self
     }
 
+    /// Clear the group by
+    pub fn clear_group_by<I>(&mut self) -> &mut Self {
+        self.selects = Vec::new();
+        self
+    }
+

But soon I realised,

  1. the methods use both clear and reset in the names, does clear and reset have special meaning where limit and offset have to use reset?
  2. There are a lot fields in SelectStatement and it is hard to manage with the above changes. If the idea generalise to other *Statement then I don't even know where to start.
pub struct SelectStatement {
    pub(crate) distinct: Option<SelectDistinct>,
    pub(crate) selects: Vec<SelectExpr>,
    pub(crate) from: Vec<TableRef>,
    pub(crate) join: Vec<JoinExpr>,
    pub(crate) r#where: ConditionHolder,
    pub(crate) groups: Vec<Expr>,
    pub(crate) having: ConditionHolder,
    pub(crate) unions: Vec<(UnionType, SelectStatement)>,
    pub(crate) orders: Vec<OrderExpr>,
    pub(crate) limit: Option<Value>,
    pub(crate) offset: Option<Value>,
    pub(crate) lock: Option<LockClause>,
    pub(crate) window: Option<(DynIden, WindowStatement)>,
    pub(crate) with: Option<Box<WithClause>>,
    #[cfg(feature = "backend-postgres")]
    pub(crate) table_sample: Option<crate::extension::postgres::TableSample>,
    #[cfg(feature = "backend-mysql")]
    pub(crate) index_hints:
        HashMap<index_hint::IndexHintKey, Vec<crate::extension::mysql::IndexHint>>,
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions