Function diesel::insert [] [src]

pub fn insert<T: ?Sized>(
    records: &T
) -> DeprecatedIncompleteInsertStatement<&T, Insert>
Deprecated since 0.99.0

: use insert_into instead

Creates an INSERT statement.

Will add the given data to a table. Backends that support the RETURNING clause, such as PostgreSQL, can return the inserted rows by calling .get_results instead of .execute.

Examples

let rows_inserted = diesel::insert(&name.eq("Sean"))
    .into(users)
    .execute(&connection);

assert_eq!(Ok(1), rows_inserted);

let new_users = vec![
    name.eq("Tess"),
    name.eq("Jim"),
];

let rows_inserted = diesel::insert(&new_users)
    .into(users)
    .execute(&connection);

assert_eq!(Ok(2), rows_inserted);

Using a tuple for values

let new_user = (id.eq(1), name.eq("Sean"));
let rows_inserted = diesel::insert(&new_user)
    .into(users)
    .execute(&connection);

assert_eq!(Ok(1), rows_inserted);

let new_users = vec![
    (id.eq(2), name.eq("Tess")),
    (id.eq(2), name.eq("Jim")),
];

let rows_inserted = diesel::insert(&new_users)
    .into(users)
    .execute(&connection);

// assert_eq!(Ok(2), rows_inserted);

Using struct for values

// Insert one record at a time

let new_user = NewUser { name: "Ruby Rhod".to_string() };

diesel::insert(&new_user)
    .into(users)
    .execute(&connection)
    .unwrap();

// Insert many records

let new_users = vec![
    NewUser { name: "Leeloo Multipass".to_string(), },
    NewUser { name: "Korben Dallas".to_string(), },
];

let inserted_names = diesel::insert(&new_users)
    .into(users)
    .execute(&connection)
    .unwrap();

With return value

// postgres only
let new_users = vec![
    NewUser { name: "Diva Plavalaguna".to_string(), },
    NewUser { name: "Father Vito Cornelius".to_string(), },
];

let inserted_names = diesel::insert(&new_users)
    .into(users)
    .returning(name)
    .get_results(&connection);
assert_eq!(Ok(vec!["Diva Plavalaguna".to_string(), "Father Vito Cornelius".to_string()]), inserted_names);