Connecting to a database using the r2d2 pool

By tradition, we will use a Pool from the r2d2 crate, but in this example (as in the Redis example), we don't use multiple connections at once. Add all of the necessary dependencies to a new binary crate:

[dependencies]
bson = "0.13"
chrono = { version = "0.4", features = ["serde"] }
clap = "2.32"
failure = "0.1"
mongodb = "0.3"
r2d2 = "0.8"
r2d2-mongodb = "0.1"
serde = "1.0"
serde_derive = "1.0"
url = "1.7"

The list is not small. Besides the crates you already familiar with, we've added the bson, chrono, and url crates. The first crate we need to work with data in the database; the second, to use the Utc type; and the last to split URL strings into pieces.

Import all the necessary types, as follows:

use chrono::offset::Utc;
use clap::{
crate_authors, crate_description, crate_name, crate_version,
App, AppSettings, Arg, SubCommand,
};
use mongodb::Error;
use mongodb::db::{Database, ThreadedDatabase};
use r2d2::Pool;
use r2d2_mongodb::{ConnectionOptionsBuilder, MongodbConnectionManager};
use url::Url;

This user's logging tool will support two commands: add to add a record, and list to print a list of all records. Add the following necessary constants:

const CMD_ADD: &str = "add";
const CMD_LIST: &str = "list";

To set and get structured data, we need to declare an Activity struct that will be used to create a BSON document and to restore it from BSON data, because MongoDB uses this format for data interaction. The Activity struct has three fields, user_id, activity, and datetime:

#[derive(Deserialize, Debug)]
struct Activity {
user_id: String,
activity: String,
datetime: String,
}
..................Content has been hidden....................

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