The first subcommand of our users management tool is add. This command extracts the NAME and EMAIL of the user from the arguments and generates a new user identifier using the uuid crate. We will use this type across all our microservices. Look at the following code:
(CMD_ADD, Some(matches)) => {
let conn = pool.get()?;
let name = matches.value_of("NAME").unwrap();
let email = matches.value_of("EMAIL").unwrap();
let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: &name,
email: &email,
};
diesel::insert_into(schema::users::table)
.values(&new_user)
.execute(&conn)?;
}
After we have extracted all the parameters, we create a NewUser instance from the models module. It requires references to values, and we don't need to pass ownership to values and reuse them in multiple requests.
The last line uses the insert_into function, which generates an INSERT INTO statement for the provided tables, but instead of textual names of tables, such as "users", we use the table type from the users module of schema. It helps you to see all the mistypes at compile time. We set the value for this request with the values function call. As a value, we use a reference to the NewUser instance because this map is already mapped to the users table in the struct declaration. To execute a statement, we call the execute function of the InsertStatement instance which is generated by the values method call.
The execute method expects a reference to a connection that we have already extracted from a pool.