Reputation: 10243
I'm trying to learn Diesel following this tutorial. This is the demo program I've created using Diesel:
#![recursion_limit = "128"]
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_infer_schema;
extern crate dotenv;
use diesel::mysql::MysqlConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use std::env;
pub fn establish_connection() -> MysqlConnection {
dotenv().ok();
let db_url: String = String::from(env::var("DB_URL").expect("DB_URL must be set"));
let db_connection =
MysqlConnection::establish(&db_url).expect(&format!("Error connecting to {}", &db_url));
return db_connection;
}
pub mod schema {
infer_schema!("dotenv:DB_URL");
}
use schema::*;
table! {
tag {
id -> SmallInt,
tag_name -> Varchar,
}
}
#[derive(Queryable, Insertable)]
#[table_name = "tag"]
pub struct Tag {
pub id: i16,
pub tag_name: String,
}
fn read_and_output(db_connection: &MysqlConnection) {
let results = tag::table.load::<Tag>(&db_connection).expect("problem");
println!("Returned results: {}", results.len());
for r in results {
println!("{} {}", r.id, r.tag_name);
}
}
pub fn insert_tag(db_connection: &MysqlConnection, tag_id_val: i16, tag_name_val: String) {
let new_tag = Tag {
id: tag_id_val,
tag_name: tag_name_val,
};
diesel::insert_into(tag::table)
.values(&new_tag)
.execute(db_connection)
.expect("Error inserting");
}
fn main() {
println!("Hello, world!");
let db_connection = establish_connection();
// 1. query data from the table
//read_and_output(&db_connection);
// 2. insert new data into the table
let tag_id: i16 = 778;
let tag_name: String = String::from("educational");
insert_tag(&db_connection, tag_id, tag_name);
//read_and_output(&db_connection);
}
The complete code is available in my GitHub repository.
When I compile the program using cargo build
, I get this error:
error[E0277]: the trait bound `&diesel::MysqlConnection: diesel::Connection` is not satisfied
--> src/main.rs:45:30
|
45 | let results = tag::table.load::<Tag>(&db_connection)
| ^^^^ the trait `diesel::Connection` is not implemented for `&diesel::MysqlConnection`
|
= help: the following implementations were found:
<diesel::MysqlConnection as diesel::Connection>
= note: required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<&diesel::MysqlConnection, Tag>` for `tag::table`
When I comment out the read_and_output
function and its invocation, the code compiles and the records are inserted into database.
I'm not sure how to resolve this error; it looks like I need to implement some trait but not sure how can I do that.
Upvotes: 3
Views: 2115
Reputation: 81
In your code db_connection
is already a reference to a MysqlConnection
, i.e. of type &MysqlConnection
, so just pass db_connection
and not &db_connection
like so
let results = tag::table.load::<Tag>(db_connection);
Upvotes: 1