Skip to main content

QueryBuilder

Struct QueryBuilder 

Source
pub struct QueryBuilder<M: Model> { /* private fields */ }
Expand description

用于构造 SQL 查询的查询构造器

Implementations§

Source§

impl<M: Model> QueryBuilder<M>

Source

pub fn new(dialect: Box<dyn Dialect>) -> Self

Source

pub fn table(self, table: impl Into<String>) -> Self

Source

pub fn select(self, columns: Vec<&str>) -> Self

设置 SELECT 列。

M-3 安全警告:本方法直接拼接 columns 到 SQL,进行标识符校验或 quote。 调用方必须确保 columns 来自可信来源(硬编码或经 sql_safety::validate_identifier 校验)。若列名可能来自不可信输入,请使用 QueryBuilder::select_quoted

本方法保留原行为以兼容复杂表达式(如 COUNT(*)users.id AS uid)。

Source

pub fn select_quoted(self, columns: Vec<&str>) -> Result<Self, DbError>

M-3 修复:安全的 SELECT 列设置,自动校验每个列名并 quote。

每个 column 必须通过 sql_safety::validate_identifier 校验 (仅允许 ASCII 字母数字 + 下划线,不以数字开头,长度 1-63)。 校验失败时返回 DbError::InvalidInput

对于复杂表达式(如 COUNT(*)users.id AS uid),请使用 QueryBuilder::select 并自行确保安全。

Source

pub fn where_cond(self, condition: impl Into<String>) -> Self

Source

pub fn or_where(self, condition: impl Into<String>) -> Self

Source

pub fn where_in(self, field: impl Into<String>, values: Vec<Value>) -> Self

Source

pub fn where_not_in(self, field: impl Into<String>, values: Vec<Value>) -> Self

Source

pub fn where_between( self, field: impl Into<String>, start: Value, end: Value, ) -> Self

Source

pub fn where_not_between( self, field: impl Into<String>, start: Value, end: Value, ) -> Self

Source

pub fn where_null(self, field: impl Into<String>) -> Self

Source

pub fn where_not_null(self, field: impl Into<String>) -> Self

Source

pub fn order_by(self, field: impl Into<String>) -> Self

Source

pub fn order_desc(self, field: impl Into<String>) -> Self

Source

pub fn group_by(self, field: impl Into<String>) -> Self

Source

pub fn having(self, condition: impl Into<String>) -> Self

Source

pub fn limit(self, limit: usize) -> Self

Source

pub fn offset(self, offset: usize) -> Self

Source

pub fn page(self, page: usize, page_size: usize) -> Self

Source

pub fn join_inner( self, table: impl Into<String>, on_left: impl Into<String>, on_right: impl Into<String>, ) -> Self

Source

pub fn join_left( self, table: impl Into<String>, on_left: impl Into<String>, on_right: impl Into<String>, ) -> Self

Source

pub fn join_right( self, table: impl Into<String>, on_left: impl Into<String>, on_right: impl Into<String>, ) -> Self

Source

pub fn build_select(&self) -> String

构建 SELECT SQL 语句

L-5 修复:补充示例文档

根据 tableselect_columnswhere_conditionsjoinsorder_bygroup_byhavinglimitoffset 等条件拼装最终 SQL。 若未通过 table() 指定表名,则使用 M::table_name()

§示例
use sz_orm_core::query::QueryBuilder;
use sz_orm_core::dialect::MySqlDialect;
use sz_orm_core::model::Model;

#[derive(Default)]
struct User;
impl Model for User {
    type PrimaryKey = i64;
    fn table_name() -> &'static str { "users" }
    fn pk(&self) -> Self::PrimaryKey { 0 }
    fn set_pk(&mut self, _: Self::PrimaryKey) {}
}

let sql = QueryBuilder::<User>::new(Box::new(MySqlDialect))
    .select(vec!["id", "name"])
    .where_cond("age > 18")
    .order_by("id DESC")
    .limit(10)
    .build_select();
// sql => "SELECT id, name FROM `users` WHERE age > 18 ORDER BY id DESC LIMIT 10"
Source

pub fn build_insert(&self, data: &HashMap<String, Value>) -> String

Source

pub fn build_update(&self, data: &HashMap<String, Value>) -> String

Source

pub fn build_delete(&self) -> String

Source

pub fn build_count(&self) -> String

Source

pub fn build_exists(&self) -> String

Source

pub fn build_max(&self, field: &str) -> String

Source

pub fn build_min(&self, field: &str) -> String

Source

pub fn build_sum(&self, field: &str) -> String

Source

pub fn build_avg(&self, field: &str) -> String

Source

pub fn validate(&self) -> Result<(), Vec<SqlValidationError>>

校验生成的 SELECT SQL 语句 检查 SQL 语法、JOIN 列名、表名合法性

Source

pub fn validate_insert( &self, data: &HashMap<String, Value>, ) -> Result<(), Vec<SqlValidationError>>

校验生成的 INSERT SQL 语句 含空数据检测(EmptyInsertData 错误)

Source

pub fn validate_update( &self, data: &HashMap<String, Value>, ) -> Result<(), Vec<SqlValidationError>>

校验生成的 UPDATE SQL 语句 含空数据检测(EmptyUpdateData 错误)

Source

pub fn validate_delete(&self) -> Result<(), Vec<SqlValidationError>>

校验生成的 DELETE SQL 语句

Trait Implementations§

Source§

impl<M: Model> Debug for QueryBuilder<M>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for QueryBuilder<M>

§

impl<M> !UnwindSafe for QueryBuilder<M>

§

impl<M> Freeze for QueryBuilder<M>

§

impl<M> Send for QueryBuilder<M>

§

impl<M> Sync for QueryBuilder<M>

§

impl<M> Unpin for QueryBuilder<M>
where M: Unpin,

§

impl<M> UnsafeUnpin for QueryBuilder<M>

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> 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, 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