Skip to main content

InsertQuery

Struct InsertQuery 

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

INSERT query builder

Implementations§

Source§

impl InsertQuery

Source

pub fn new() -> Self

Create an empty INSERT query

Source

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

Set the target table

Source

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

Add a column-value pair (value should be an already-escaped SQL literal)

Source

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

Batch add column-value pairs

Source

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

PostgreSQL/SQLite: ON CONFLICT (cols) DO NOTHING

Ignore insertion on conflict. Applicable to PostgreSQL and SQLite dialects. Under MySQL dialect this setting is ignored (MySQL does not support ON CONFLICT syntax).

§Example
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, ...

Update specified columns on conflict. assignments is a list of (column, expression) pairs. Expressions may use EXCLUDED.col to reference the to-be-inserted value (PG/SQLite standard).

§Example
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, ...

Update specified columns on primary/unique key conflict. assignments is a list of (column, expression) pairs. Expressions may use VALUES(col) to reference the to-be-inserted value (MySQL syntax).

§Example
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: use REPLACE INTO instead of INSERT INTO

On primary/unique key conflict, delete the old row first then insert the new row. Applicable to MySQL/MariaDB/TiDB dialects.

Source

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

Set the RETURNING clause (supported by PostgreSQL/SQLite 3.35+)

Returns the values of specified columns after INSERT, commonly used to obtain auto-increment primary keys or default values. MySQL does not support RETURNING; it is ignored in build() (MySQL style) and only rendered for PostgreSQL/SQLite dialects in build_with_dialect().

§Example
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

Set RETURNING * (return all columns)

Source

pub fn build(self) -> String

Build INSERT SQL (no dialect, hard-coded backticks, MySQL style)

§Security (gate 9 fix)

Identifiers are escaped via quote_ident() and wrapped in backticks, preventing malicious identifiers containing ` from breaking out.

§Upsert behavior
  • Replace: generates REPLACE INTO instead of INSERT INTO
  • OnDuplicateKeyUpdate: appends ON DUPLICATE KEY UPDATE clause
  • OnConflictDoNothing/OnConflictDoUpdate: skipped (MySQL does not support)
Source

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

Generate SQL for the specified dialect

§Upsert dialect compatibility
  • MySQL family: supports OnDuplicateKeyUpdate, Replace
  • PostgreSQL/SQLite: supports OnConflictDoNothing, OnConflictDoUpdate
  • Incompatible combinations skip the upsert clause (no error)

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