Search code examples
mysqlrustrust-rocketrust-sqlx

thread 'main' panicked at 'assertion failed: self.remaining() >= dst.len()' when trying to connect database MYSQL


So when i try to connect mysql database main tread panics it was working fine with sqlite but when i try to use it with mysql it's not working.

cargo check

is also working fine. The error is located at line 20 where i created a database connection.

my main.rs

use dotenv::dotenv;
use roadoxe::data::AppDatabase;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "roadoxe")]
struct Opt {
    #[structopt(default_value = "mysql://root:[email protected]:33060/automate")]
    connection_string: String,
}

fn main() {
    dotenv().ok();
    let opt = Opt::from_args();

    let rt = tokio::runtime::Runtime::new().expect("failed to spawn tokio runtime");

    let handle = rt.handle().clone();

    let database = rt.block_on(async move { AppDatabase::new(&opt.connection_string).await });
    let config = roadoxe::RocketConfig {
        database,
        // maintenance,
    };

    rt.block_on(async move {
        roadoxe::rocket(config)
            .launch()
            .await
            .expect("failed to launch rocket server");
    })
}

and data mod.rs

 use sqlx::MySql;
// use std::str::FromStr;

#[derive(Debug, thiserror::Error)]
pub enum DataError {
    #[error("Database Error: {0}")]
    Database(#[from] sqlx::Error),
}

pub type AppDatabase = Database<MySql>;
pub type DatabasePool = sqlx::mysql::MySqlPool;
pub type Transaction<'a> = sqlx::Transaction<'a, MySql>;
pub type AppDatabaseRow = sqlx::mysql::MySqlRow;
pub type AppQueryResult = sqlx::mysql::MySqlQueryResult;

pub struct Database<D: sqlx::Database>(sqlx::Pool<D>);

impl Database<MySql> {
    pub async fn new(path: &str) -> Self {
        let pool = sqlx::mysql::MySqlPoolOptions::new().connect(path).await;
        match pool {
            Ok(pool) => Self(pool),
            Err(e) => {
                eprintln!("{}\n", e);
                eprintln!(
                    "If the database has not yet been created, run \n    $ sqlx database setup\n"
                );
                panic!("Failed to connect to database");
            }
        }
    }
    pub fn get_pool(&self) -> &DatabasePool {
        &self.0
    }
}

I have no idea what's happening here fairly new to rust. And thanks for your time.


Solution

  • The first issue was the port it is suppose to be

    const PORT = 3306
    

    rather than 33060 and the second issue was the ip address it doesn't work with 127.0.0.1 but localhost seems to work fine just needed to switch

    #[structopt(default_value = "mysql://root:[email protected]:33060/automate")]
    

    with

     #[structopt(default_value = "mysql://root:root@localhost:3306/automate")]