Function diesel::insert_into [] [src]

pub fn insert_into<T>(target: T) -> IncompleteInsertStatement<T, Insert>

Creates an INSERT statement for the target table.

You may add data by calling values() or default_values() as shown in the examples.

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_into(users)
    .values(&name.eq("Sean"))
    .execute(&connection);

assert_eq!(Ok(1), rows_inserted);

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

let rows_inserted = diesel::insert_into(users)
    .values(&new_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_into(users)
    .values(&new_user)
    .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_into(users)
    .values(&new_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_into(users)
    .values(&new_user)
    .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_into(users)
    .values(&new_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_into(users)
    .values(&new_users)
    .returning(name)
    .get_results(&connection);
assert_eq!(Ok(vec!["Diva Plavalaguna".to_string(), "Father Vito Cornelius".to_string()]), inserted_names);