opendal_service_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 opendal_core::Configurator for D1Config {
60 type Builder = D1Builder;
61
62 fn from_uri(uri: &opendal_core::OperatorUri) -> opendal_core::Result<Self> {
63 let account_id = uri.name().ok_or_else(|| {
64 opendal_core::Error::new(
65 opendal_core::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 opendal_core::Error::new(
73 opendal_core::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 opendal_core::Error::new(
82 opendal_core::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 && !rest.is_empty()
94 {
95 map.insert("root".to_string(), rest.to_string());
96 }
97
98 Self::from_iter(map)
99 }
100
101 fn into_builder(self) -> Self::Builder {
102 D1Builder { config: self }
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109 use opendal_core::Configurator;
110 use opendal_core::OperatorUri;
111
112 #[test]
113 fn from_uri_sets_account_database_and_root() {
114 let uri =
115 OperatorUri::new("d1://acc123/db456/cache", Vec::<(String, String)>::new()).unwrap();
116
117 let cfg = D1Config::from_uri(&uri).unwrap();
118 assert_eq!(cfg.account_id.as_deref(), Some("acc123"));
119 assert_eq!(cfg.database_id.as_deref(), Some("db456"));
120 assert_eq!(cfg.root.as_deref(), Some("cache"));
121 }
122}