Most applications fall into a category called “CRUD” apps. CRUD stands for “Create, Read, Update, Delete”. Diesel provides support for all four pieces, but in this guide we’re going to look at the different ways to go about creating INSERT statements.

The examples for this guide are going to be shown for PostgreSQL, but you can follow along with any backend. The full code examples for all backends are linked at the bottom of this guide.

An insert statement always starts with insert_into. The first argument to this function is the table you’re inserting into.

For this guide, our schema will look like this:

src/lib.rs

  1. table! {
  2. users {
  3. id -> Integer,
  4. name -> Text,
  5. hair_color -> Nullable<Text>,
  6. created_at -> Timestamp,
  7. updated_at -> Timestamp,
  8. }
  9. }

Since our functions are going to only operate on the users table, we can put use schema::users::dsl::*; at the top of our function, which will let us write insert_into(users) instead of insert_into(users::table). If you’re importing table::dsl::*, make sure it’s always inside a function, not the top of your module.

If all of the columns on a table have a default, the simplest thing we can do is call .default_values. We could write a function that ran that query like this:

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users).default_values().execute(conn)

It’s worth noting that this code will still compile, even if you don’t have default values on all of your columns. Diesel will ensure that the value you’re assigning has the right type, but it can’t validate whether the column has a default, any constraints that could fail, or any triggers that could fire.

We can use debug_query to inspect the generated SQL. The exact SQL that is generated may differ depending on the backend you’re using. If we run println!("{}", debug_query::<Pg, _>(&our_query));, we’ll see the following:

src/lib.rs

  1. INSERT INTO "users" DEFAULT VALUES -- binds: []

If we want to actually provide values, we can call .values instead. There are a lot of different arguments we can provide here. The simplest is a single column/value pair using .eq.

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users).values(name.eq("Sean")).execute(conn)

This will generate the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name") VALUES ($1)
  2. -- binds ["Sean"]

If we want to provide values for more than one column, we can pass a tuple.

src/lib.rs

  1. insert_into(users)
  2. .values((name.eq("Tess"), hair_color.eq("Brown")))
  3. .execute(conn)

This will generate the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name", "hair_color")
  2. VALUES ($1, $2) -- binds: ["Tess", "Brown"]

Insertable

Working with tuples is the typical way to do an insert if you just have some values that you want to stick in the database. But what if your data is coming from another source, like a web form deserialized by Serde? It’d be annoying to have to write (name.eq(user.name), hair_color.eq(user.hair_color)).

Diesel provides the Insertable trait for this case. Insertable maps your struct to columns in the database. We can derive this automatically by adding #[derive(Insertable)] to our type.

src/lib.rs

  1. use schema::users;
  2. #[derive(Deserialize, Insertable)]
  3. #[table_name = "users"]
  4. pub struct UserForm<'a> {
  5. name: &'a str,
  6. hair_color: Option<&'a str>,
  7. }

src/lib.rs

  1. use schema::users::dsl::*;
  2. let json = r#"{ "name": "Sean", "hair_color": "Black" }"#;
  3. let user_form = serde_json::from_str::<UserForm>(json)?;
  4. insert_into(users).values(&user_form).execute(conn)?;
  5. Ok(())

This will generate the same SQL as if we had used a tuple.

src/lib.rs

  1. INSERT INTO "users" ("name", "hair_color")
  2. VALUES ($1, $2) -- binds: ["Sean", "Black"]

If one of the fields is None, the default value will be inserted for that field.

src/lib.rs

  1. use schema::users::dsl::*;
  2. let json = r#"{ "name": "Ruby", "hair_color": null }"#;
  3. let user_form = serde_json::from_str::<UserForm>(json)?;
  4. insert_into(users).values(&user_form).execute(conn)?;
  5. Ok(())

That will generate the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name", "hair_color")
  2. VALUES ($1, DEFAULT) -- binds: ["Ruby"]

Batch Insert

If we want to insert more than one row at a time, we can do that by passing a &Vec or slice of any of the forms used above. Keep in mind that you’re always passing a reference here. As of Diesel 1.0, Rust will generate a very opaque error message about overflow if you try to pass Vec instead of &Vec.

On backends that support the DEFAULT keyword (all backends except SQLite), the data will be inserted in a single query. On SQLite, one query will be performed per row.

For example, if we wanted to insert two rows with a single value, we can just use a Vec.

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users)
  3. .values(&vec![name.eq("Sean"), name.eq("Tess")])
  4. .execute(conn)

Which generates the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name") VALUES ($1), ($2)
  2. -- binds ["Sean", "Tess"]

Note that on SQLite, you won’t be able to use debug_query for this, since it doesn’t map to a single query. You can inspect each row like this:

src/lib.rs

  1. for row in &values {
  2. let query = insert_into(users).values(row);
  3. println!("{}", debug_query::<Sqlite, _>(&query));
  4. }

If we wanted to use DEFAULT for some of our rows, we can use an option here.

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users)
  3. .values(&vec![Some(name.eq("Sean")), None])
  4. .execute(conn)

Note that the type here is Option<Eq<Column, Value>> not Eq<Column, Option<Value>>. Doing column.eq(None) would insert NULL not DEFAULT. This generates the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name") VALUES ($1), (DEFAULT)
  2. -- binds ["Sean"]

We can do the same thing with tuples.

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users)
  3. .values(&vec![
  4. (name.eq("Sean"), hair_color.eq("Black")),
  5. (name.eq("Tess"), hair_color.eq("Brown")),
  6. ])
  7. .execute(conn)

Which generates the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name", "hair_color")
  2. VALUES ($1, $2), ($3, $4)
  3. -- binds: ["Sean", "Black", "Tess", "Brown"]

Once again, we can use an Option for any of the fields to insert DEFAULT.

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users)
  3. .values(&vec![
  4. (name.eq("Sean"), Some(hair_color.eq("Black"))),
  5. (name.eq("Ruby"), None),
  6. ])
  7. .execute(conn)

Which generates the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name", "hair_color")
  2. VALUES ($1, $2), ($3, DEFAULT)
  3. -- binds: ["Sean", "Black", "Ruby"]

Finally, Insertable structs can be used for batch insert as well.

src/lib.rs

  1. use schema::users::dsl::*;
  2. let json = r#"[
  3. { "name": "Sean", "hair_color": "Black" },
  4. { "name": "Tess", "hair_color": "Brown" }
  5. ]"#;
  6. let user_form = serde_json::from_str::<Vec<UserForm>>(json)?;
  7. insert_into(users).values(&user_form).execute(conn)?;
  8. Ok(())

This generates the same SQL as if we had used a tuple:

src/lib.rs

  1. INSERT INTO "users" ("name", "hair_color")
  2. VALUES ($1, $2), ($3, $4)
  3. -- binds: ["Sean", "Black", "Tess", "Brown"]

The RETURNING Clause

On backends that support the RETURNING clause (such as PostgreSQL), we can get data back from our insert as well. MySQL and SQLite do not support RETURNING clauses. To get back all of the inserted rows, we can call .get_results instead of .execute.

Given this struct:

src/lib.rs

  1. #[derive(Queryable, PartialEq, Debug)]
  2. struct User {
  3. id: i32,
  4. name: String,
  5. hair_color: Option<String>,
  6. created_at: SystemTime,
  7. updated_at: SystemTime,
  8. }

We can use get_results with this test:

src/lib.rs

  1. use diesel::select;
  2. use schema::users::dsl::*;
  3. let now = select(diesel::dsl::now).get_result::<SystemTime>(&conn)?;
  4. let inserted_users = insert_into(users)
  5. .values(&vec![
  6. (id.eq(1), name.eq("Sean")),
  7. (id.eq(2), name.eq("Tess")),
  8. ])
  9. .get_results(&conn)?;
  10. let expected_users = vec![
  11. User {
  12. id: 1,
  13. name: "Sean".into(),
  14. hair_color: None,
  15. created_at: now,
  16. updated_at: now,
  17. },
  18. User {
  19. id: 2,
  20. name: "Tess".into(),
  21. hair_color: None,
  22. created_at: now,
  23. updated_at: now,
  24. },
  25. ];
  26. assert_eq!(expected_users, inserted_users);

To inspect the SQL generated by .get_results or .get_result, we will need to call .as_query before passing it to debug_query. The query in the last test generates the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("id", "name")
  2. VALUES ($1, $2), ($3, $4)
  3. RETURNING "users"."id", "users"."name", "users"."hair_color",
  4. "users"."created_at", "users"."updated_at"
  5. -- binds: [1, "Sean", 2, "Tess"]

You’ll notice that we’ve never given an explicit value for created_at and updated_at in any of our examples. With Diesel, you typically won’t set those values in Rust. Typically these columns get set with DEFAULT CURRENT_TIMESTAMP, and a trigger is used to change updated_at on updates. If you’re using PostgreSQL, you can use a built-in trigger by running SELECT diesel_manage_updated_at('users'); in a migration.

If we expect one row instead of multiple, we can call .get_result instead of .get_results.

src/lib.rs

  1. use diesel::select;
  2. use schema::users::dsl::*;
  3. let now = select(diesel::dsl::now).get_result::<SystemTime>(&conn)?;
  4. let inserted_user = insert_into(users)
  5. .values((id.eq(3), name.eq("Ruby")))
  6. .get_result(&conn)?;
  7. let expected_user = User {
  8. id: 3,
  9. name: "Ruby".into(),
  10. hair_color: None,
  11. created_at: now,
  12. updated_at: now,
  13. };
  14. assert_eq!(expected_user, inserted_user);

This generates the same SQL as get_results:

src/lib.rs

  1. INSERT INTO "users" ("id", "name") VALUES ($1, $2)
  2. RETURNING "users"."id", "users"."name", "users"."hair_color",
  3. "users"."created_at", "users"."updated_at"
  4. -- binds: [3, "Ruby"]

Finally, if we only want a single column back, we can call .returning explicitly. This code would return the inserted ID:

src/lib.rs

  1. use schema::users::dsl::*;
  2. insert_into(users)
  3. .values(name.eq("Ruby"))
  4. .returning(id)
  5. .get_result(conn)

Which generates the following SQL:

src/lib.rs

  1. INSERT INTO "users" ("name") VALUES ($1)
  2. RETURNING "users"."id"
  3. -- binds: ["Ruby"]

“Upsert”

Every type of insert statement covered in this guide can also be used for “insert or update” queries, also known as “upsert”. The specifics of upsert are covered extensively in the API documentation.

For PostgreSQL, see the pg::upsert module. For MySQL and SQLite, upsert is done via REPLACE. See replace_into for details.

Diesel does not have support for MySQL’s ON DUPLICATE KEY conflict, as its results are non-deterministic, and unsafe with replication.

Conclusion

While there are a lot of examples in this guide, ultimately the only difference between various kinds of insert statements is the argument passed to .values.

All examples in this guide are run as part of Diesel’s test suite. You can find the full code examples for each backend at these links:

View More Guides