|
| 1 | +use std::collections::BTreeMap; |
| 2 | + |
| 3 | +use schemars::JsonSchema; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | +use snafu::{ResultExt, Snafu}; |
| 6 | + |
| 7 | +use crate::{ |
| 8 | + commons::networking::HostName, |
| 9 | + crd::database::{ |
| 10 | + drivers::jdbc::{JDBCDatabaseConnection, JDBCDatabaseConnectionDetails}, |
| 11 | + helpers::{connection_parameters_as_url_query_parameters, username_and_password_envs}, |
| 12 | + }, |
| 13 | +}; |
| 14 | + |
| 15 | +#[derive(Debug, Snafu)] |
| 16 | +pub enum Error { |
| 17 | + #[snafu(display("failed to parse connection URL"))] |
| 18 | + ParseConnectionUrl { source: url::ParseError }, |
| 19 | +} |
| 20 | + |
| 21 | +/// TODO docs |
| 22 | +#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)] |
| 23 | +#[serde(rename_all = "camelCase")] |
| 24 | +pub struct MysqlConnection { |
| 25 | + /// TODO docs |
| 26 | + pub host: HostName, |
| 27 | + |
| 28 | + /// TODO docs |
| 29 | + #[serde(default = "MysqlConnection::default_port")] |
| 30 | + pub port: u16, |
| 31 | + |
| 32 | + /// TODO docs |
| 33 | + pub database: String, |
| 34 | + |
| 35 | + /// TODO docs |
| 36 | + pub credentials_secret: String, |
| 37 | + |
| 38 | + /// TODO docs |
| 39 | + #[serde(default)] |
| 40 | + pub parameters: BTreeMap<String, String>, |
| 41 | +} |
| 42 | + |
| 43 | +impl MysqlConnection { |
| 44 | + fn default_port() -> u16 { |
| 45 | + 3306 |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl JDBCDatabaseConnection for MysqlConnection { |
| 50 | + fn jdbc_connection_details( |
| 51 | + &self, |
| 52 | + unique_database_name: &str, |
| 53 | + ) -> Result<JDBCDatabaseConnectionDetails, crate::crd::database::Error> { |
| 54 | + let Self { |
| 55 | + host, |
| 56 | + port, |
| 57 | + database, |
| 58 | + credentials_secret, |
| 59 | + parameters, |
| 60 | + } = self; |
| 61 | + let (username_env, password_env) = |
| 62 | + username_and_password_envs(unique_database_name, credentials_secret); |
| 63 | + |
| 64 | + let connection_uri = format!( |
| 65 | + "jdbc:mysql://{host}:{port}/{database}{parameters}", |
| 66 | + parameters = connection_parameters_as_url_query_parameters(parameters) |
| 67 | + ); |
| 68 | + let connection_uri = connection_uri.parse().context(ParseConnectionUrlSnafu)?; |
| 69 | + |
| 70 | + Ok(JDBCDatabaseConnectionDetails { |
| 71 | + driver: "com.mysql.jdbc.Driver".to_owned(), |
| 72 | + connection_uri, |
| 73 | + username_env: Some(username_env), |
| 74 | + password_env: Some(password_env), |
| 75 | + }) |
| 76 | + } |
| 77 | +} |
0 commit comments