1use clickhouse::Client;
2use error::ClickhouseToolError;
3use url::Url;
4use urlencoding::decode;
5
6pub mod error;
7pub mod migrations;
8pub mod worker;
9
10pub async fn init_client(db_uri: &str) -> Result<Client, ClickhouseToolError> {
11 let endpoint: Url = db_uri
12 .parse()
13 .map_err(|_| ClickhouseToolError::InvaidArgs("Invalid URL".to_string()))?;
14
15 let url = format!(
16 "{}://{}:{}",
17 endpoint.scheme(),
18 endpoint.host().expect("clickhouse must have host"),
19 endpoint.port().expect("clickhouse must have port")
20 );
21 let user = endpoint.username();
22 let password = decode(endpoint.password().unwrap_or(""))
23 .map_err(|_| ClickhouseToolError::InvaidArgs("Invalid password".to_string()))?;
24 let database = endpoint
25 .path()
26 .split('/')
27 .nth(1)
28 .expect("clickhouse ep must have database");
29
30 let mut client = Client::default().with_url(&url);
31 if !user.is_empty() {
32 client = client.with_user(user);
33 }
34
35 if !password.is_empty() {
36 client = client.with_password(password);
37 }
38
39 if !database.is_empty() {
40 client = client.with_database(database);
41 }
42
43 client.query("SELECT 1").execute().await?;
44 Ok(client)
45}