Skip to main content

SelectQuery

Struct SelectQuery 

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

SELECT 查询构造器

Implementations§

Source§

impl SelectQuery

Source

pub fn new() -> Self

创建空的 SELECT 查询

Source

pub fn distinct(self) -> Self

设置 DISTINCT

Source

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

添加列

Source

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

添加多个列

Source

pub fn all_columns(self) -> Self

添加 *

Source

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

设置 FROM 表

Source

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

设置 FROM 子查询:FROM (<subquery_sql>) AS <alias>

from 互斥,后调用者覆盖前者。 子查询 SQL 由调用方负责构造(可由另一个 SelectQuery::build 生成), 别名经 dialect.quote() 转义,防止标识符逃逸。

§示例
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

添加 INNER JOIN

§安全性(门禁 9 修复)

表名经 quote_ident() 转义。on 条件为表达式,调用方应确保不使用恶意输入构造。

Source

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

添加 LEFT JOIN

§安全性(门禁 9 修复)

inner_join,表名经 quote_ident() 转义。

Source

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

添加 RIGHT JOIN

§安全性(门禁 9 修复)

inner_join,表名经 quote_ident() 转义。

Source

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

添加 INNER JOIN,ON 条件为列对列等值连接(left_col = right_col

§安全性

列名经 quote_column_dialect 按方言转义,防止标识符逃逸。 无参数值,纯标识符连接,最常见且最安全的 JOIN 形式。

Source

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

添加 LEFT JOIN,ON 条件为列对列等值连接

Source

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

添加 RIGHT JOIN,ON 条件为列对列等值连接

Source

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

添加 INNER JOIN,ON 条件为参数化表达式(left_col op ?

§参数
  • table: JOIN 的表名(支持别名 orders o
  • left_col: 左侧列名(已转义)
  • op_expr: 运算符 + 占位符部分(如 = ? > ? IN (?, ?)
  • value: 单个参数值
Source

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

添加 LEFT JOIN,ON 条件为参数化表达式

Source

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

添加 RIGHT JOIN,ON 条件为参数化表达式

Source

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

添加 WHERE 条件(AND 连接)

§安全性(v0.2.2 修复 C-6)

调用 check_where_injection 检测高危模式(分号+SQL 关键字、行注释、块注释)。 复杂 WHERE 条件应使用参数化查询 API,避免直接拼接字符串。

Source

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

添加 OR WHERE 条件

§安全性(v0.2.2 修复 C-6)

where_clause,调用 check_where_injection 检测高危模式。

Source

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

添加 column = ? AND 条件

Source

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

添加 column <> ? AND 条件

Source

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

添加 column > ? AND 条件

Source

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

添加 column >= ? AND 条件

Source

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

添加 column < ? AND 条件

Source

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

添加 column <= ? AND 条件

Source

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

添加 column LIKE ? AND 条件

Source

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

添加 column IN (?, ?, ...) AND 条件

空列表生成 1 = 0(恒假),避免生成非法的 IN ()

Source

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

添加 column NOT IN (?, ?, ...) AND 条件

空列表生成 1 = 1(恒真),避免生成非法的 NOT IN ()

Source

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

添加 column BETWEEN ? AND ? AND 条件

Source

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

添加 column IS NULL AND 条件

Source

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

添加 column IS NOT NULL AND 条件

Source

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

添加 column = ? OR 条件

Source

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

添加 column <> ? OR 条件

Source

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

添加 column > ? OR 条件

Source

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

添加 column >= ? OR 条件

Source

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

添加 column < ? OR 条件

Source

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

添加 column <= ? OR 条件

Source

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

添加 column LIKE ? OR 条件

Source

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

添加 column IN (?, ?, ...) OR 条件

Source

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

添加 column BETWEEN ? AND ? OR 条件

Source

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

添加 column IS NULL OR 条件

Source

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

添加 column IS NOT NULL OR 条件

Source

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

添加 GROUP BY

Source

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

添加 HAVING

Source

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

添加 ORDER BY

§参数
  • column: 列名
  • asc: true=ASC, false=DESC
Source

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

设置 LIMIT

Source

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

设置 OFFSET

Source

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

生成分页(同时设置 LIMIT 和 OFFSET)

§参数
  • page: 页码(从 1 开始)
  • size: 每页大小
Source

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

添加 CTE(Common Table Expression / WITH 子句)。

生成形如 WITH name AS (subquery) SELECT ... 的 SQL。

§参数
  • name: CTE 名称
  • subquery: 子查询 SQL(完整的 SELECT 语句)
Source

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

添加递归 CTE(WITH RECURSIVE name AS (...) SELECT ...)。

§参数
  • name: CTE 名称
  • subquery: 递归子查询 SQL
Source

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

添加窗口函数列(作为 SELECT 列表的原始表达式)。

调用方负责构造完整的窗口函数表达式,例如:

  • 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)
§参数
  • expr: 完整的窗口函数表达式
Source

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

添加 ROW_NUMBER() 窗口函数列。

§参数
  • partition_by: PARTITION BY 列(可为空)
  • order_by: ORDER BY 列(如 salary DESC
  • alias: 结果列别名(如 row_num
Source

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

添加 RANK() 窗口函数列。

§参数
  • partition_by: PARTITION BY 列(可为空)
  • order_by: ORDER BY 列
  • alias: 结果列别名
Source

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

添加 DENSE_RANK() 窗口函数列。

§参数
  • partition_by: PARTITION BY 列(可为空)
  • order_by: ORDER BY 列
  • alias: 结果列别名
Source

pub fn for_update(self) -> Self

设置 FOR UPDATE 行锁。

在生成的 SQL 末尾追加 FOR UPDATE,用于悲观锁。

Source

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

设置 FOR UPDATE 并附带选项(如 NOWAITSKIP LOCKED)。

§参数
  • options: 选项字符串,如 "NOWAIT""SKIP LOCKED"
Source

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

将当前查询与另一个查询进行 UNION 集合运算。

返回一个 SetQuery,可通过 build() 生成最终 SQL。

Source

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

将当前查询与另一个查询进行 UNION ALL 集合运算。

Source

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

将当前查询与另一个查询进行 INTERSECT 集合运算。

Source

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

将当前查询与另一个查询进行 EXCEPT 集合运算。

Source

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

生成 SQL

§参数
  • db_type: 数据库类型,用于选择方言
Source

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

生成带参数的 SQL(参数化查询,P0 修复:SQL 注入防护)

返回 BuiltQuery,包含带 ? 占位符的 SQL 与按序绑定的参数列表。 与 build 的区别:

  • WHERE 条件可来自 where_eq/where_in/where_between 等参数化 API
  • 用户输入作为参数绑定,而非字符串拼接到 SQL 中
§混合使用规则

当同时使用原始 where_clause(&str) 与参数化 where_eq(column, value) 时:

  • 原始条件先渲染(无参数)
  • 参数化条件后渲染(按顺序收集参数)
  • 两者均按调用顺序保持 AND/OR 连接语义
§示例
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<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> 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<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