Database interaction functions

Now, we can replace our Connection instance from the postgres crate with Conn from the mysql crate to provide our interaction functions. The first function, create_table, uses a mutable reference to a Conn instance:

fn create_table(conn: &mut Conn) -> Result<(), Error> {
conn.query("CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
)")
.map(drop)
}

Also, we used the query method of the Conn connection object to send a query. This method doesn't expect parameters. We still ignore the successful result of a query and drop it with map.

The next function, create_user, has transformed into the following form:

fn create_user(conn: &mut Conn, user: &User) -> Result<(), Error> {
conn.prep_exec("INSERT INTO users (name, email) VALUES (?, ?)",
(&user.name, &user.email))
.map(drop)
}

We use the prep_exec method of Conn, which expects a tuple of parameters that we have extracted from User struct fields. As you can see, we used the ? char to specify where to insert the value.

The last function, list_users, collects users from a query. It's more complex than the version for PostgreSQL. We used the query method which returns a QueryResult type that implements the Iterator trait. We use this property to convert the result in to an iterator, and try to fold values to a vector in the try_fold method of the Iterator implementation:

fn list_users(conn: &mut Conn) -> Result<Vec<User>, Error> {
conn.query("SELECT name, email FROM users")?
.into_iter()
.try_fold(Vec::new(), |mut vec, row| {
let row = row?;
let user = User {
name: row.get_opt(0).unwrap()?,
email: row.get_opt(1).unwrap()?,
};
vec.push(user);
Ok(vec)
})
}

For the try_fold method call, we provide a closure that expects two arguments: the first is a vector that we pass with the try_fold call, while the second is a Row instance. We use try_fold to return Error if any row conversion to user fails.

We use the get_opt method of the Row object to get a value of a corresponding type, and use the ? operator to extract it from a result, or return Error with try_fold. In every iteration, we return a vector with a new, appended value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.38.176