Skip to main content

InsertQuery

Struct InsertQuery 

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

INSERT 查询构造器

Implementations§

Source§

impl InsertQuery

Source

pub fn new() -> Self

创建空的 INSERT 查询

Source

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

设置目标表

Source

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

添加列值对(值应为已转义的 SQL 字面量)

Source

pub fn values(self, pairs: &[(&str, &str)]) -> Self

批量添加列值对

Source

pub fn on_conflict_do_nothing(self, conflict_cols: &[&str]) -> Self

PostgreSQL/SQLite:ON CONFLICT (cols) DO NOTHING

冲突时忽略插入。适用于 PostgreSQL、SQLite 方言。 MySQL 方言下此设置被忽略(MySQL 不支持 ON CONFLICT 语法)。

§示例
use sz_orm_core::DbType;
use sz_orm_query_builder::Query;

let sql = Query::insert()
    .into_table("users")
    .value("id", "1")
    .value("name", "'Alice'")
    .on_conflict_do_nothing(&["id"])
    .build_with_dialect(DbType::PostgreSQL);
// INSERT INTO "users" ("id", "name") VALUES (1, 'Alice') ON CONFLICT ("id") DO NOTHING
Source

pub fn on_conflict_do_update( self, conflict_cols: &[&str], assignments: &[(&str, &str)], ) -> Self

PostgreSQL/SQLite:ON CONFLICT (cols) DO UPDATE SET col = expr, ...

冲突时更新指定列。assignments(列名, 表达式) 对。 表达式中可使用 EXCLUDED.col 引用待插入的值(PG/SQLite 标准)。

§示例
use sz_orm_core::DbType;
use sz_orm_query_builder::Query;

let sql = Query::insert()
    .into_table("users")
    .value("id", "1")
    .value("name", "'Alice'")
    .value("count", "1")
    .on_conflict_do_update(
        &["id"],
        &[("name", "EXCLUDED.name"), ("count", "users.count + 1")],
    )
    .build_with_dialect(DbType::PostgreSQL);
// INSERT INTO "users" (...) VALUES (...) ON CONFLICT ("id") DO UPDATE SET
//   "name" = EXCLUDED.name, "count" = users.count + 1
Source

pub fn on_duplicate_key_update(self, assignments: &[(&str, &str)]) -> Self

MySQL:ON DUPLICATE KEY UPDATE col = expr, ...

主键/唯一键冲突时更新指定列。assignments(列名, 表达式) 对。 表达式中可使用 VALUES(col) 引用待插入的值(MySQL 语法)。

§示例
use sz_orm_core::DbType;
use sz_orm_query_builder::Query;

let sql = Query::insert()
    .into_table("users")
    .value("id", "1")
    .value("name", "'Alice'")
    .value("count", "1")
    .on_duplicate_key_update(&[("name", "VALUES(name)"), ("count", "count + 1")])
    .build_with_dialect(DbType::MySQL);
// INSERT INTO `users` (`id`, `name`, `count`) VALUES (1, 'Alice', 1)
//   ON DUPLICATE KEY UPDATE `name` = VALUES(name), `count` = count + 1
Source

pub fn replace(self) -> Self

MySQL:使用 REPLACE INTO 代替 INSERT INTO

主键/唯一键冲突时先删除旧行再插入新行。 适用于 MySQL/MariaDB/TiDB 方言。

Source

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

设置 RETURNING 子句(PostgreSQL/SQLite 3.35+ 支持)

在 INSERT 后返回指定列的值,常用于获取自增主键或默认值。 MySQL 不支持 RETURNING,在 build()(MySQL 风格)中会被忽略; 在 build_with_dialect() 中仅 PostgreSQL/SQLite 方言渲染。

§示例
use sz_orm_core::DbType;
use sz_orm_query_builder::Query;

let sql = Query::insert()
    .into_table("users")
    .value("name", "'Alice'")
    .returning(&["id", "created_at"])
    .build_with_dialect(DbType::PostgreSQL);
// INSERT INTO "users" ("name") VALUES ('Alice') RETURNING "id", "created_at"
Source

pub fn returning_all(self) -> Self

设置 RETURNING *(返回所有列)

Source

pub fn build(self) -> String

构建 INSERT SQL(无方言,硬编码反引号,MySQL 风格)

§安全性(门禁 9 修复)

标识符经 quote_ident() 转义后包裹反引号,防止含 ` 的恶意标识符逃逸。

§Upsert 行为
  • Replace:生成 REPLACE INTO 代替 INSERT INTO
  • OnDuplicateKeyUpdate:追加 ON DUPLICATE KEY UPDATE 子句
  • OnConflictDoNothing/OnConflictDoUpdate:跳过(MySQL 不支持)
Source

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

按指定方言生成 SQL

§Upsert 方言兼容性
  • MySQL 家族:支持 OnDuplicateKeyUpdateReplace
  • PostgreSQL/SQLite:支持 OnConflictDoNothingOnConflictDoUpdate
  • 不兼容的组合会跳过 upsert 子句(不报错)

Trait Implementations§

Source§

impl Clone for InsertQuery

Source§

fn clone(&self) -> InsertQuery

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 InsertQuery

Source§

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

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

impl Default for InsertQuery

Source§

fn default() -> InsertQuery

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