wtx/database/client/postgres/
config.rs1use crate::{database::client::postgres::PostgresError, misc::UriRef};
2
3#[derive(Debug, PartialEq, Eq)]
5pub struct Config<'data> {
6 pub(crate) application_name: &'data str,
7 pub(crate) channel_binding: ChannelBinding,
8 pub(crate) db: &'data str,
9 pub(crate) password: &'data str,
10 pub(crate) user: &'data str,
11}
12
13impl<'data> Config<'data> {
14 pub fn from_uri(uri: &'data UriRef<'_>) -> crate::Result<Config<'data>> {
16 let db = uri.path().get(1..).unwrap_or_default();
17 let password = uri.password();
18 let user = uri.user();
19 let mut this =
20 Self { application_name: "", channel_binding: ChannelBinding::Prefer, db, password, user };
21 for (key, value) in uri.query_params() {
22 this.set_param(key, value)?;
23 }
24 Ok(this)
25 }
26
27 fn set_param(&mut self, key: &str, value: &'data str) -> crate::Result<()> {
28 match key {
29 "application_name" => {
30 self.application_name = value;
31 }
32 "channel_binding" => {
33 let channel_binding = match value {
34 "disable" => ChannelBinding::Disable,
35 "prefer" => ChannelBinding::Prefer,
36 "require" => ChannelBinding::Require,
37 _ => return Err(PostgresError::UnknownConfigurationParameter.into()),
38 };
39 self.channel_binding = channel_binding;
40 }
41 _ => return Err(PostgresError::UnknownConfigurationParameter.into()),
42 }
43 Ok(())
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub(crate) enum ChannelBinding {
49 Disable,
50 Prefer,
51 Require,
52}
53
54#[cfg(test)]
55mod tests {
56 use crate::database::client::postgres::{Config, config::ChannelBinding};
57
58 #[test]
59 fn from_uri() {
60 let uri = "postgres://ab:cd@ef:5432/gh?application_name=ij&channel_binding=disable".into();
61 let config = Config::from_uri(&uri).unwrap();
62 assert_eq!(config.application_name, "ij");
63 assert_eq!(config.channel_binding, ChannelBinding::Disable);
64 assert_eq!(config.db, "gh");
65 assert_eq!(config.password, "cd");
66 assert_eq!(config.user, "ab");
67 }
68}