Creating a connection pool

We will reuse the arguments parser from the previous example, but will rewrite the code that establish a connection, because we're using MySQL instead of PostgreSQL now. First, we replaced the database link with the mysql scheme. We will use the same parameters for the connection as those that we used to bootstrap the MySQL server instance.

We convert the address string to the Opts - options of a connections, the type of mysql crate that's used to set parameters for connections. But MysqlConnectionManager expects us to provide an OptsBuilder object. Look at the following code:

let addr = matches.value_of("database")
.unwrap_or("mysql://root:password@localhost:3306/test");
let opts = Opts::from_url(addr)?;
let builder = OptsBuilder::from_opts(opts);
let manager = MysqlConnectionManager::new(builder);
let pool = r2d2::Pool::new(manager)?;
let mut conn = pool.get()?;

Now, we can create MysqlConnectionManager using builder, and we can create r2d2::Pool with a manager instance. We also get a mutable conn reference to a connection to provide it for subcommands.

The good news is that it's enough to start. We don't need to change anything in our branches, except the type of reference. Now, we have to pass a mutable reference to the connection:

(CMD_CRATE, _) => {
create_table(&mut conn)?;
}

Try to start and check how the tool works. We will provide it a CSV file with content in the following format:

name,email
user01,[email protected]
user02,[email protected]
user03,[email protected]

If you want to check whether the database has really changed, try importing user data from our CSV file:

cargo run -- import < users.csv

You can use the mysql client to print the users table:

mysql> SELECT * FROM users;
+----+--------+--------------------+
| id | name | email |
+----+--------+--------------------+
| 1 | user01 | [email protected] |
| 2 | user03 | [email protected] |
| 3 | user08 | [email protected] |
| 4 | user06 | [email protected] |
| 5 | user02 | [email protected] |
| 6 | user07 | [email protected] |
| 7 | user04 | [email protected] |
| 8 | user09 | [email protected] |
| 9 | user10 | [email protected] |
| 10 | user05 | [email protected] |
+----+--------+--------------------+
10 rows in set (0.00 sec)

It works! As you can see, users were added in an unpredictable order, because we used multiple connections and real concurrency. Now you have knowledge of how to use SQL databases. It's time to look at interacting with NoSQL databases through the r2d2 crate.

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

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