0

I am new to Rust lang. I am creating a Config class that has a config element of type tiberius.config and a client element of type tiberius.client. I have a new function that creates an instance of the class and sets the connection properties (config). I also have a start function that creates the client element and assigns it to the client property of the class.

I am currently getting an error when trying to declare the client property as empty in the new function, as I want to assign its value later in the start function. The Ok(Client::new()) approach doesn't exist, I don't want to use the unsafe mode. and I want client property to be of type Client not Option<Client>. How can I fix this?

My code is the following:

use std::error;
use config::Config;
use tokio::net::TcpStream;
use tokio_util::compat::{TokioAsyncWriteCompatExt, Compat};
use tiberius::{Client, Config as TibConfig, AuthMethod, EncryptionLevel};

pub struct Psql {
    config: TibConfig,
    client: Client<Compat<tokio::net::TcpStream>>,
    query: String
}

impl Psql {
    pub fn new(self: &Psql, configuration: Config) -> Result<Psql, Box<dyn std::error::Error>>{
        let mut config: TibConfig = TibConfig::new();
        config.host(configuration.get::<String>("database.host")?);
        config.port(configuration.get("database.port")?);
        config.database(configuration.get::<String>("database.name")?);
        config.authentication(
            AuthMethod::sql_server(
                configuration.get::<String>("database.user")?,
                configuration.get::<String>("database.password")?,
            ),
        );
        config.trust_cert();
        config.encryption(EncryptionLevel::NotSupported);

        Ok(Psql {
            config: config,
            client: Client::new(),
            query: String::new(),
        })
    }

    pub async fn start(self: &mut Psql){
        let tcp: TcpStream = (TcpStream::connect(self.config.get_addr()).await).unwrap_or_else(op);
        tcp.set_nodelay(true).unwrap();
        let local_config: TibConfig = self.config.clone();
        self.client = Client::connect(local_config, tcp.compat_write()).await;
    }
}
Fahed
  • 195
  • 2
  • 10

0 Answers0