Skip to main content

Insert

Derive Macro Insert 

Source
#[derive(Insert)]
{
    // Attributes available to this derive:
    #[sql]
}
Expand description

Defines insertable data for a table.

Implements Insert for the Struct and &Struct, for use in query! and query_lazy!. Field names map to table columns, and you can provide a subset of columns as long as the missing ones are declared as defaults.

§Basic usage

#[derive(Insert)]
#[sql(table = ExampleTable)]
struct ExampleInsert {
    id: i32,
    name: String,
    role: String,
    active: bool,
    nickname: Option<String>,
}

let data = ExampleInsert {
    id: 4,
    name: "sam".to_string(),
    role: "admin".to_string(),
    active: true,
    nickname: None,
};

query!(&mut conn, INSERT INTO ExampleTable VALUES {data}).await?;

§Defaults for omitted columns

Use #[sql(default = field1, field2)] to declare table columns that are not present in the insert struct (for example, auto-increment primary keys or columns with SQL defaults). All omitted columns must be listed so the macro can validate the table schema at compile time.

#[derive(Insert)]
#[sql(table = ExampleTable)]
#[sql(default = id, role)]
struct ExampleInsert {
    name: String,
    active: bool,
    nickname: Option<String>,
}

let data = ExampleInsert {
    name: "pat".to_string(),
    active: false,
    nickname: Some("Pat".to_string()),
};

query!(&mut conn, INSERT INTO ExampleTable VALUES {&data}).await?;

§Field attributes

  • #[sql(bytes)] must match #[sql(bytes)] on table struct, stores the field as a binary blob using bincode + serde.

§Notes

  • #[sql(table = TableStruct)] is required and must point to a Table type.
  • You can insert a single value, borrow or a collection (&T, Vec<T>, &Vec<T>, &[T]).