Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What or, is best used with Rouille? #256

Closed
jhjacobs81 opened this issue May 13, 2022 · 7 comments
Closed

What or, is best used with Rouille? #256

jhjacobs81 opened this issue May 13, 2022 · 7 comments

Comments

@jhjacobs81
Copy link

I am at a point where i can use rouille for a basic web app, but whatever i try i can not get mysql to work. I keep getting errors after error, even though it works in other examples.

so what would be the best way to make rouille work with a database? Obviously the example isn’t good for me as it only handles one connection at a time.

@bradfier
Copy link
Collaborator

Hey @jhjacobs81, could you post an example of what you're trying and which isn't working for you?

The most basic setup that should work with Rouille would be to use MySQL.

This slightly contrived example should get you started:

use std::net::{IpAddr, SocketAddr};
use mysql::*;
use mysql::prelude::*;
use rouille::router;

fn main() {
    let socket = SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 3306);
    let opts = OptsBuilder::new().db_name(Some("my_db")).bind_address(Some(socket));
    let pool = Pool::new(opts).unwrap();
    rouille::start_server("127.0.0.1:5000", move |request| {
        router!(request,
           (GET) (/) => {
                let mut conn = pool.clone().get_conn().unwrap();
                let value: Option<i64> = conn.query_first("SELECT COUNT(*) FROM my_table").unwrap();
                rouille::Response::text(format!("Total: {}", value.unwrap_or(0)))
            },
            _ => rouille::Response::empty_404()
        )
    });
}

@jhjacobs81
Copy link
Author

jhjacobs81 commented May 20, 2022

Hello @bradfier thanks for responding!

I had something along the lines of this:

use mysql::*;
use mysql::prelude::*;
use rouille::router;

pub struct Pagedata {
    pub id: u64,
    pub title: String,
    pub body: String
}


fn main() {
    let mysqladdress = "mysql://user:password@127.0.0.1:3306/database";
    let opts = Opts::from_url(mysqladdress).unwrap();
    let pool = Pool::new(opts).unwrap();
    let mut conn = pool.get_conn().unwrap();

    rouille::start_server("127.0.0.1:8000", move |request| {
        router!(request,
           (GET) (/pageid) => {
                let p = conn
                .exec_map(
                "SELECT id, title, body FROM pages WHERE id = ?;",
                (&pageid,),
                |(id, title, body)| {
                Pagedata { id, title, body }
                },
                ).unwrap();

                rouille::Response::text(format!("ID: {} - Title: {} - Body: {}", p.id, p.title, p.body); 
            },
            _ => rouille::Response::empty_404()
        )
    });
} 

i tried moving around the mysql related let's to inside the routes etc etc. i would always get an error saying that a field did not exist for p.id, p.title, p.body even though it exists in the struct and in the database

What works for me now is this:

use mysql::*;
use mysql::prelude::*;
use rouille::router;

fn main() {
    let mysqladdress = "mysql://user:password@127.0.0.1:3306/database";
    let opts = Opts::from_url(mysqladdress).unwrap();
    let pool = Pool::new(opts).unwrap();

    rouille::start_server("127.0.0.1:8000", move |request| {
        router!(request,
           (GET) (/) => {
            let mut conn = pool.get_conn().unwrap();
                let value: Option<i64> = conn.query_first("SELECT COUNT(*) FROM pages").unwrap();
                rouille::Response::text(format!("Total: {}", value.unwrap_or(0)))
            },
            _ => rouille::Response::empty_404()
        )
    });
} 

at the very least this returns the amount of rows. now i need to get the data still ;-) i'll keep you posted!

-- EDIT:
unfortunatly, this doesnt work either..

use mysql::*;
use mysql::prelude::*;
use rouille::router;

//// STRUCTS ////
pub struct Pagedata {
    pub id: u64,
    pub title: String,
    pub body: String,
}

//// FUNCTIONS ////

//// MAIN FUCTION ////
fn main() {
    let mysqladdress = "<URL>";
    let opts = Opts::from_url(mysqladdress).unwrap();
    let pool = Pool::new(opts).unwrap();

    rouille::start_server("127.0.0.1:8000", move |request| {
        router!(request,
           (GET) (/) => {
            let mut conn = pool.get_conn().unwrap();
               //  let value: Option<i64> = conn.query_first("SELECT COUNT(*) FROM pages").unwrap();
               //// MYSQL ROUTINE
               let page: Vec<Pagedata> =
                pool.prep_exec("SELECT id, title, body from pages", ())
                .map(|result| {
                result.map(|x| x.unwrap()).map(|row| {
                    let (id, title, body) = mysql::from_row(row);
 
                    Pagedata {
                        id,
                        title,
                        body
                    }
                }).collect()
                }).unwrap(); // Unwrap `Vec<Pagedata>`
               //// END MYSQL ROUTINE
               //  rouille::Response::text(format!("Total: {}", value.unwrap_or(0)))
               rouille::Response::text(format!("Total: {} - {} - {}", page.id, page.title, page.body))
            },
            _ => rouille::Response::empty_404()
        )
    });
} 

at first i get this error:

^^^^^^^^^ method not found in `mysql::Pool`

followed by:

error[E0609]: no field `id` on type `Vec<Pagedata>`
  --> src/main.rs:42:76
     |
42 |                rouille::Response::text(format!("Total: {} - {} - {}", page.id, page.title, page.body))
     |                                                                                           ^^ unknown field (page.id)

error[E0609]: no field `title` on type `Vec<Pagedata>`
   --> src/main.rs:42:85
     |
42 |                rouille::Response::text(format!("Total: {} - {} - {}", page.id, page.title, page.body))
     |                                                                                            ^^^^^ unknown field (page.title)

error[E0609]: no field `body` on type `Vec<Pagedata>`
  --> src/main.rs:42:97
     |
42 |                rouille::Response::text(format!("Total: {} - {} - {}", page.id, page.title, page.body))
     |                                                                                            ^^^^ unknown field (page.body)

which is odd, since the table contains rows with filled data, the vec has the corect fields, AND these mysql codes work when i use them in a different project :(

This may very well be an error on my part :) im trying to learn Rut by writing a web app, thats how i found Rouille in the first place :)

@bradfier
Copy link
Collaborator

Well, at least with regard to your latest error, that's because page is actually a Vec<Pagedata>, I.e. it could contain none, one, or many Pagedata. You need to act on them individually (perhaps by accessing page[0].title) or collectively, perhaps using map() like below:

Try instead:

let response_text = page.into_iter().map(|p| format!("{} - {} - {}", p.id, p.title, p.body)).join("\n");
rouille::Response::text(response_text)

@jhjacobs81
Copy link
Author

Thank you foryour response :)

unfortunatly, that throws out a whole new error :) As a resut, i believe i am not ready yet to work with Rouille so i have dropped it for now :(

Will keep an eye on it though ;-)

@bradfier
Copy link
Collaborator

bradfier commented Jun 3, 2022

Please do come back when you're interested again 🙂

@bradfier bradfier closed this as completed Jun 3, 2022
@jhjacobs81
Copy link
Author

which would be now :)

interest was never a problem, i very much like Rouille. i gotten further with it then with other frameworks, just not the mysql part. This is all on me, im a noob programmer stil :)

@jhjacobs81
Copy link
Author

i thought an ORM would be better, but that throws errors too :(

Perhaps someone could create an example with an ORM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants