Skip to main content

SelectQuery

Struct SelectQuery 

Source
pub struct SelectQuery { /* private fields */ }
Expand description

SELECT query builder

Implementations§

Source§

impl SelectQuery

Source

pub fn new() -> Self

Create an empty SELECT query

Source

pub fn distinct(self) -> Self

Set DISTINCT

Source

pub fn column(self, name: &str) -> Self

Add a column

Source

pub fn columns(self, names: &[&str]) -> Self

Add multiple columns

Source

pub fn all_columns(self) -> Self

Add a * column

Source

pub fn from(self, table: &str) -> Self

Set FROM table

Source

pub fn from_subquery(self, subquery_sql: &str, alias: &str) -> Self

Set FROM subquery: FROM (<subquery_sql>) AS <alias>

Mutually exclusive with from; later caller overrides earlier. The subquery SQL is constructed by the caller (may be generated by another SelectQuery::build), and the alias is escaped via dialect.quote() to prevent identifier escape.

§Example
use sz_orm_core::DbType;
use sz_orm_query_builder::Query;

let inner = Query::select()
    .column("id")
    .column("amount")
    .from("orders")
    .build(DbType::MySQL);
let sql = Query::select()
    .column("id")
    .from_subquery(&inner, "t")
    .build(DbType::MySQL);
assert!(sql.contains("FROM (SELECT `id`, `amount` FROM `orders`) AS `t`"));
Source

pub fn inner_join(self, table: &str, on: &str) -> Self

Add an INNER JOIN

§Security (gate 9 fix)

The table name is escaped via quote_ident(). The on condition is an expression; the caller should ensure it is not constructed with malicious input.

Source

pub fn left_join(self, table: &str, on: &str) -> Self

Add a LEFT JOIN

§Security (gate 9 fix)

Same as inner_join; the table name is escaped via quote_ident().

Source

pub fn right_join(self, table: &str, on: &str) -> Self

Add a RIGHT JOIN

§Security (gate 9 fix)

Same as inner_join; the table name is escaped via quote_ident().

Source

pub fn inner_join_on(self, table: &str, left_col: &str, right_col: &str) -> Self

Add an INNER JOIN with a column-to-column equality ON condition (left_col = right_col)

§Security

Column names are escaped per dialect via quote_column_dialect, preventing identifier escape. No parameter values; pure identifier join, the most common and safest JOIN form.

Source

pub fn left_join_on(self, table: &str, left_col: &str, right_col: &str) -> Self

Add a LEFT JOIN with a column-to-column equality ON condition

Source

pub fn right_join_on(self, table: &str, left_col: &str, right_col: &str) -> Self

Add a RIGHT JOIN with a column-to-column equality ON condition

Source

pub fn inner_join_param( self, table: &str, left_col: &str, op_expr: &str, value: Value, ) -> Self

Add an INNER JOIN with a parameterized expression ON condition (left_col op ?)

§Parameters
  • table: JOIN table name (supports alias orders o)
  • left_col: left column name (already escaped)
  • op_expr: operator + placeholder part (e.g., = ?, > ?, IN (?, ?))
  • value: single parameter value
Source

pub fn left_join_param( self, table: &str, left_col: &str, op_expr: &str, value: Value, ) -> Self

Add a LEFT JOIN with a parameterized expression ON condition

Source

pub fn right_join_param( self, table: &str, left_col: &str, op_expr: &str, value: Value, ) -> Self

Add a RIGHT JOIN with a parameterized expression ON condition

Source

pub fn where_clause(self, condition: &str) -> Self

Add a WHERE condition (AND joined)

§Security (v0.2.2 fix C-6)

Calls check_where_injection to detect high-risk patterns (semicolon + SQL keyword, line comments, block comments). Complex WHERE conditions should use the parameterized query API to avoid direct string concatenation.

Source

pub fn where_eq(self, column: &str, value: Value) -> Self

Add a column = ? AND condition

Source

pub fn where_ne(self, column: &str, value: Value) -> Self

Add a column <> ? AND condition

Source

pub fn where_gt(self, column: &str, value: Value) -> Self

Add a column > ? AND condition

Source

pub fn where_ge(self, column: &str, value: Value) -> Self

Add a column >= ? AND condition

Source

pub fn where_lt(self, column: &str, value: Value) -> Self

Add a column < ? AND condition

Source

pub fn where_le(self, column: &str, value: Value) -> Self

Add a column <= ? AND condition

Source

pub fn where_like(self, column: &str, pattern: Value) -> Self

Add a column LIKE ? AND condition

Source

pub fn where_in(self, column: &str, values: Vec<Value>) -> Self

Add a column IN (?, ?, ...) AND condition

An empty list produces 1 = 0 (always false), avoiding an invalid IN ().

Source

pub fn where_not_in(self, column: &str, values: Vec<Value>) -> Self

Add a column NOT IN (?, ?, ...) AND condition

An empty list produces 1 = 1 (always true), avoiding an invalid NOT IN ().

Source

pub fn where_between(self, column: &str, low: Value, high: Value) -> Self

Add a column BETWEEN ? AND ? AND condition

Source

pub fn where_null(self, column: &str) -> Self

Add a column IS NULL AND condition

Source

pub fn where_not_null(self, column: &str) -> Self

Add a column IS NOT NULL AND condition

Source

pub fn or_where_eq(self, column: &str, value: Value) -> Self

Add a column = ? OR condition

Source

pub fn or_where_ne(self, column: &str, value: Value) -> Self

Add a column <> ? OR condition

Source

pub fn or_where_gt(self, column: &str, value: Value) -> Self

Add a column > ? OR condition

Source

pub fn or_where_ge(self, column: &str, value: Value) -> Self

Add a column >= ? OR condition

Source

pub fn or_where_lt(self, column: &str, value: Value) -> Self

Add a column < ? OR condition

Source

pub fn or_where_le(self, column: &str, value: Value) -> Self

Add a column <= ? OR condition

Source

pub fn or_where_like(self, column: &str, pattern: Value) -> Self

Add a column LIKE ? OR condition

Source

pub fn or_where_in(self, column: &str, values: Vec<Value>) -> Self

Add a column IN (?, ?, ...) OR condition

Source

pub fn or_where_between(self, column: &str, low: Value, high: Value) -> Self

Add a column BETWEEN ? AND ? OR condition

Source

pub fn or_where_null(self, column: &str) -> Self

Add a column IS NULL OR condition

Source

pub fn or_where_not_null(self, column: &str) -> Self

Add a column IS NOT NULL OR condition

Source

pub fn group_by(self, column: &str) -> Self

Add GROUP BY

Source

pub fn having(self, condition: &str) -> Self

Add HAVING

Source

pub fn order_by(self, column: &str, asc: bool) -> Self

Add ORDER BY

§Parameters
  • column: column name
  • asc: true=ASC, false=DESC
Source

pub fn limit(self, n: u64) -> Self

Set LIMIT

Source

pub fn offset(self, n: u64) -> Self

Set OFFSET

Source

pub fn paginate(self, page: u64, size: u64) -> Self

Generate pagination (sets both LIMIT and OFFSET)

§Parameters
  • page: page number (1-based)
  • size: page size
Source

pub fn with_cte(self, name: &str, subquery: &str) -> Self

Add a CTE (Common Table Expression / WITH clause).

Generates SQL of the form WITH name AS (subquery) SELECT ....

§Parameters
  • name: CTE name
  • subquery: subquery SQL (a complete SELECT statement)
Source

pub fn with_recursive_cte(self, name: &str, subquery: &str) -> Self

Add a recursive CTE (WITH RECURSIVE name AS (...) SELECT ...).

§Parameters
  • name: CTE name
  • subquery: recursive subquery SQL
Source

pub fn window_function(self, expr: &str) -> Self

Add a window function column (as a raw expression in the SELECT list).

The caller is responsible for constructing the complete window function expression, e.g.:

  • ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC)
  • RANK() OVER (ORDER BY score DESC)
  • SUM(amount) OVER (PARTITION BY user_id ORDER BY created_at)
§Parameters
  • expr: complete window function expression
Source

pub fn row_number(self, partition_by: &str, order_by: &str, alias: &str) -> Self

Add a ROW_NUMBER() window function column.

§Parameters
  • partition_by: PARTITION BY column (may be empty)
  • order_by: ORDER BY column (e.g., salary DESC)
  • alias: result column alias (e.g., row_num)
Source

pub fn rank(self, partition_by: &str, order_by: &str, alias: &str) -> Self

Add a RANK() window function column.

§Parameters
  • partition_by: PARTITION BY column (may be empty)
  • order_by: ORDER BY column
  • alias: result column alias
Source

pub fn dense_rank(self, partition_by: &str, order_by: &str, alias: &str) -> Self

Add a DENSE_RANK() window function column.

§Parameters
  • partition_by: PARTITION BY column (may be empty)
  • order_by: ORDER BY column
  • alias: result column alias
Source

pub fn for_update(self) -> Self

Set FOR UPDATE row lock.

Appends FOR UPDATE to the end of the generated SQL, used for pessimistic lock.

Source

pub fn for_update_with_options(self, options: &str) -> Self

Set FOR UPDATE with options (e.g., NOWAIT, SKIP LOCKED).

§Parameters
  • options: options string, e.g., "NOWAIT" or "SKIP LOCKED"
Source

pub fn union(self, other: SelectQuery) -> SetQuery

Combine the current query with another query using UNION set operation.

Returns a SetQuery, which can be turned into the final SQL via build().

Source

pub fn union_all(self, other: SelectQuery) -> SetQuery

Combine the current query with another query using UNION ALL set operation.

Source

pub fn intersect(self, other: SelectQuery) -> SetQuery

Combine the current query with another query using INTERSECT set operation.

Source

pub fn except(self, other: SelectQuery) -> SetQuery

Combine the current query with another query using EXCEPT set operation.

Source

pub fn build(self, db_type: DbType) -> String

Generate SQL

§Parameters
  • db_type: database type, used to select the dialect
Source

pub fn build_with_params(self, db_type: DbType) -> BuiltQuery

Generate parameterized SQL (parameterized query, P0 fix: SQL injection prevention)

Returns a BuiltQuery, containing a SQL string with ? placeholders and a list of parameters bound in order. Differences from build:

  • WHERE conditions can come from parameterized APIs like where_eq/where_in/where_between
  • User input is bound as parameters rather than concatenated into the SQL string
§Mixed usage rules

When using both raw where_clause(&str) and parameterized where_eq(column, value):

  • Raw conditions render first (no parameters)
  • Parameterized conditions render after (parameters collected in order)
  • Both preserve AND/OR conjunction semantics in call order
§Example
use sz_orm_core::{DbType, Value};
use sz_orm_query_builder::Query;

let built = Query::select()
    .column("id")
    .from("users")
    .where_eq("age", Value::I32(18))
    .or_where_eq("role", Value::String("admin".into()))
    .build_with_params(DbType::MySQL);
assert!(built.sql.contains("WHERE `age` = ? OR `role` = ?"));
assert_eq!(built.params.len(), 2);

Trait Implementations§

Source§

impl Clone for SelectQuery

Source§

fn clone(&self) -> SelectQuery

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SelectQuery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SelectQuery

Source§

fn default() -> SelectQuery

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more