opendal/services/d1/
config.rs1use std::fmt::Debug;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use super::D1_SCHEME;
24use super::backend::D1Builder;
25
26#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
28#[serde(default)]
29#[non_exhaustive]
30pub struct D1Config {
31 pub token: Option<String>,
33 pub account_id: Option<String>,
35 pub database_id: Option<String>,
37
38 pub root: Option<String>,
40 pub table: Option<String>,
42 pub key_field: Option<String>,
44 pub value_field: Option<String>,
46}
47
48impl Debug for D1Config {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 f.debug_struct("D1Config")
51 .field("root", &self.root)
52 .field("table", &self.table)
53 .field("key_field", &self.key_field)
54 .field("value_field", &self.value_field)
55 .finish_non_exhaustive()
56 }
57}
58
59impl crate::Configurator for D1Config {
60 type Builder = D1Builder;
61
62 fn from_uri(uri: &crate::types::OperatorUri) -> crate::Result<Self> {
63 let account_id = uri.name().ok_or_else(|| {
64 crate::Error::new(
65 crate::ErrorKind::ConfigInvalid,
66 "uri host must contain account id",
67 )
68 .with_context("service", D1_SCHEME)
69 })?;
70
71 let database_and_root = uri.root().ok_or_else(|| {
72 crate::Error::new(
73 crate::ErrorKind::ConfigInvalid,
74 "uri path must contain database id",
75 )
76 .with_context("service", D1_SCHEME)
77 })?;
78
79 let mut segments = database_and_root.splitn(2, '/');
80 let database_id = segments.next().filter(|s| !s.is_empty()).ok_or_else(|| {
81 crate::Error::new(
82 crate::ErrorKind::ConfigInvalid,
83 "database id is required in uri path",
84 )
85 .with_context("service", D1_SCHEME)
86 })?;
87
88 let mut map = uri.options().clone();
89 map.insert("account_id".to_string(), account_id.to_string());
90 map.insert("database_id".to_string(), database_id.to_string());
91
92 if let Some(rest) = segments.next() {
93 if !rest.is_empty() {
94 map.insert("root".to_string(), rest.to_string());
95 }
96 }
97
98 Self::from_iter(map)
99 }
100
101 #[allow(deprecated)]
102 fn into_builder(self) -> Self::Builder {
103 D1Builder {
104 config: self,
105 http_client: None,
106 }
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113 use crate::Configurator;
114 use crate::types::OperatorUri;
115
116 #[test]
117 fn from_uri_sets_account_database_and_root() {
118 let uri =
119 OperatorUri::new("d1://acc123/db456/cache", Vec::<(String, String)>::new()).unwrap();
120
121 let cfg = D1Config::from_uri(&uri).unwrap();
122 assert_eq!(cfg.account_id.as_deref(), Some("acc123"));
123 assert_eq!(cfg.database_id.as_deref(), Some("db456"));
124 assert_eq!(cfg.root.as_deref(), Some("cache"));
125 }
126}