opendal_service_postgresql/
backend.rs1use std::sync::Arc;
19
20use mea::once::OnceCell;
21use sqlx::postgres::PgConnectOptions;
22
23use super::POSTGRESQL_SCHEME;
24use super::config::PostgresqlConfig;
25use super::core::*;
26use super::deleter::PostgresqlDeleter;
27use super::reader::*;
28use super::writer::PostgresqlWriter;
29use opendal_core::raw::*;
30use opendal_core::*;
31
32#[doc = include_str!("docs.md")]
34#[derive(Debug, Default)]
35pub struct PostgresqlBuilder {
36 pub(super) config: PostgresqlConfig,
37}
38
39impl PostgresqlBuilder {
40 pub fn connection_string(mut self, v: &str) -> Self {
51 if !v.is_empty() {
52 self.config.connection_string = Some(v.to_string());
53 }
54 self
55 }
56
57 pub fn root(mut self, root: &str) -> Self {
61 self.config.root = if root.is_empty() {
62 None
63 } else {
64 Some(root.to_string())
65 };
66
67 self
68 }
69
70 pub fn table(mut self, table: &str) -> Self {
72 if !table.is_empty() {
73 self.config.table = Some(table.to_string());
74 }
75 self
76 }
77
78 pub fn key_field(mut self, key_field: &str) -> Self {
82 if !key_field.is_empty() {
83 self.config.key_field = Some(key_field.to_string());
84 }
85 self
86 }
87
88 pub fn value_field(mut self, value_field: &str) -> Self {
92 if !value_field.is_empty() {
93 self.config.value_field = Some(value_field.to_string());
94 }
95 self
96 }
97}
98
99impl Builder for PostgresqlBuilder {
100 type Config = PostgresqlConfig;
101
102 fn build(self) -> Result<impl Service> {
103 let conn = match self.config.connection_string {
104 Some(v) => v,
105 None => {
106 return Err(
107 Error::new(ErrorKind::ConfigInvalid, "connection_string is empty")
108 .with_context("service", POSTGRESQL_SCHEME),
109 );
110 }
111 };
112
113 let config = conn.parse::<PgConnectOptions>().map_err(|err| {
114 Error::new(ErrorKind::ConfigInvalid, "connection_string is invalid")
115 .with_context("service", POSTGRESQL_SCHEME)
116 .set_source(err)
117 })?;
118
119 let table = match self.config.table {
120 Some(v) => v,
121 None => {
122 return Err(Error::new(ErrorKind::ConfigInvalid, "table is empty")
123 .with_context("service", POSTGRESQL_SCHEME));
124 }
125 };
126
127 let key_field = self.config.key_field.unwrap_or_else(|| "key".to_string());
128
129 let value_field = self
130 .config
131 .value_field
132 .unwrap_or_else(|| "value".to_string());
133
134 let root = normalize_root(self.config.root.unwrap_or_else(|| "/".to_string()).as_str());
135
136 Ok(PostgresqlBackend::new(PostgresqlCore {
137 pool: OnceCell::new(),
138 config,
139 table,
140 key_field,
141 value_field,
142 })
143 .with_normalized_root(root))
144 }
145}
146
147#[derive(Clone, Debug)]
149pub struct PostgresqlBackend {
150 pub(crate) core: Arc<PostgresqlCore>,
151 pub(crate) root: String,
152 pub(crate) info: ServiceInfo,
153 pub(crate) capability: Capability,
154}
155
156impl PostgresqlBackend {
157 pub fn new(core: PostgresqlCore) -> Self {
158 let info = ServiceInfo::new(POSTGRESQL_SCHEME, "/", &core.table);
159 let capability = Capability {
160 read: true,
161 stat: true,
162 write: true,
163 write_can_empty: true,
164 delete: true,
165 shared: true,
166 ..Default::default()
167 };
168
169 Self {
170 core: Arc::new(core),
171 root: "/".to_string(),
172 info,
173 capability,
174 }
175 }
176
177 fn with_normalized_root(mut self, root: String) -> Self {
178 self.info = self.info.with_root(&root);
179 self.root = root;
180 self
181 }
182}
183
184impl Service for PostgresqlBackend {
185 type Reader = oio::StreamReader<PostgresqlReader>;
186 type Writer = PostgresqlWriter;
187 type Lister = ();
188 type Deleter = oio::OneShotDeleter<PostgresqlDeleter>;
189 type Copier = ();
190
191 fn info(&self) -> ServiceInfo {
192 self.info.clone()
193 }
194
195 fn capability(&self) -> Capability {
196 self.capability
197 }
198
199 async fn create_dir(
200 &self,
201 _ctx: &OperationContext,
202 _path: &str,
203 _args: OpCreateDir,
204 ) -> Result<RpCreateDir> {
205 Err(Error::new(
206 ErrorKind::Unsupported,
207 "operation is not supported",
208 ))
209 }
210
211 async fn stat(&self, _ctx: &OperationContext, path: &str, _: OpStat) -> Result<RpStat> {
212 let p = build_abs_path(&self.root, path);
213
214 if p == build_abs_path(&self.root, "") {
215 Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
216 } else {
217 match self.core.get_length(&p).await? {
218 Some(length) => Ok(RpStat::new(
219 Metadata::new(EntryMode::FILE).with_content_length(length as u64),
220 )),
221 None => Err(Error::new(
222 ErrorKind::NotFound,
223 "kv not found in postgresql",
224 )),
225 }
226 }
227 }
228 fn read(&self, _ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
229 let output: oio::StreamReader<PostgresqlReader> = {
230 Ok(oio::StreamReader::new(PostgresqlReader::new(
231 self.clone(),
232 path,
233 args,
234 )))
235 }?;
236
237 Ok(output)
238 }
239
240 fn write(&self, _ctx: &OperationContext, path: &str, _: OpWrite) -> Result<Self::Writer> {
241 let output: PostgresqlWriter = {
242 let p = build_abs_path(&self.root, path);
243 Ok(PostgresqlWriter::new(self.core.clone(), p))
244 }?;
245
246 Ok(output)
247 }
248
249 fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
250 let output: oio::OneShotDeleter<PostgresqlDeleter> = {
251 Ok(oio::OneShotDeleter::new(PostgresqlDeleter::new(
252 self.core.clone(),
253 self.root.clone(),
254 )))
255 }?;
256
257 Ok(output)
258 }
259
260 fn list(&self, _ctx: &OperationContext, _path: &str, _args: OpList) -> Result<Self::Lister> {
261 Err(Error::new(
262 ErrorKind::Unsupported,
263 "operation is not supported",
264 ))
265 }
266
267 fn copy(
268 &self,
269 _ctx: &OperationContext,
270 _from: &str,
271 _to: &str,
272 _args: OpCopy,
273 _opts: OpCopier,
274 ) -> Result<Self::Copier> {
275 Err(Error::new(
276 ErrorKind::Unsupported,
277 "operation is not supported",
278 ))
279 }
280
281 async fn rename(
282 &self,
283 _ctx: &OperationContext,
284 _from: &str,
285 _to: &str,
286 _args: OpRename,
287 ) -> Result<RpRename> {
288 Err(Error::new(
289 ErrorKind::Unsupported,
290 "operation is not supported",
291 ))
292 }
293
294 async fn presign(
295 &self,
296 _ctx: &OperationContext,
297 _path: &str,
298 _args: OpPresign,
299 ) -> Result<RpPresign> {
300 Err(Error::new(
301 ErrorKind::Unsupported,
302 "operation is not supported",
303 ))
304 }
305}