opendal_service_postgresql/
backend.rs1use std::sync::Arc;
19
20use asyncband::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 type Composer = ();
191
192 fn info(&self) -> ServiceInfo {
193 self.info.clone()
194 }
195
196 fn capability(&self) -> Capability {
197 self.capability
198 }
199
200 async fn create_dir(
201 &self,
202 _ctx: &OperationContext,
203 _path: &str,
204 _args: OpCreateDir,
205 ) -> Result<RpCreateDir> {
206 Err(Error::new(
207 ErrorKind::Unsupported,
208 "operation is not supported",
209 ))
210 }
211
212 async fn stat(&self, _ctx: &OperationContext, path: &str, _: OpStat) -> Result<RpStat> {
213 let p = build_abs_path(&self.root, path);
214
215 if p == build_abs_path(&self.root, "") {
216 Ok(RpStat::new(MetadataBuilder::dir().build()))
217 } else {
218 match self.core.get_length(&p).await? {
219 Some(length) => Ok(RpStat::new({
220 let metadata = MetadataBuilder::file(length as u64);
221 metadata.build()
222 })),
223 None => Err(Error::new(
224 ErrorKind::NotFound,
225 "kv not found in postgresql",
226 )),
227 }
228 }
229 }
230 fn read(&self, _ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
231 let output: oio::StreamReader<PostgresqlReader> = {
232 Ok(oio::StreamReader::new(PostgresqlReader::new(
233 self.clone(),
234 path,
235 args,
236 )))
237 }?;
238
239 Ok(output)
240 }
241
242 fn write(&self, _ctx: &OperationContext, path: &str, _: OpWrite) -> Result<Self::Writer> {
243 let output: PostgresqlWriter = {
244 let p = build_abs_path(&self.root, path);
245 Ok(PostgresqlWriter::new(self.core.clone(), p))
246 }?;
247
248 Ok(output)
249 }
250
251 fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
252 let output: oio::OneShotDeleter<PostgresqlDeleter> = {
253 Ok(oio::OneShotDeleter::new(PostgresqlDeleter::new(
254 self.core.clone(),
255 self.root.clone(),
256 )))
257 }?;
258
259 Ok(output)
260 }
261
262 fn list(&self, _ctx: &OperationContext, _path: &str, _args: OpList) -> Result<Self::Lister> {
263 Err(Error::new(
264 ErrorKind::Unsupported,
265 "operation is not supported",
266 ))
267 }
268
269 fn copy(
270 &self,
271 _ctx: &OperationContext,
272 _from: &str,
273 _to: &str,
274 _args: OpCopy,
275 ) -> Result<Self::Copier> {
276 Err(Error::new(
277 ErrorKind::Unsupported,
278 "operation is not supported",
279 ))
280 }
281
282 async fn rename(
283 &self,
284 _ctx: &OperationContext,
285 _from: &str,
286 _to: &str,
287 _args: OpRename,
288 ) -> Result<RpRename> {
289 Err(Error::new(
290 ErrorKind::Unsupported,
291 "operation is not supported",
292 ))
293 }
294
295 async fn presign(
296 &self,
297 _ctx: &OperationContext,
298 _path: &str,
299 _args: OpPresign,
300 ) -> Result<RpPresign> {
301 Err(Error::new(
302 ErrorKind::Unsupported,
303 "operation is not supported",
304 ))
305 }
306}