opendal_core/services/rocksdb/
core.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19use std::sync::Arc;
20
21use rocksdb::DB;
22
23use crate::*;
24
25#[derive(Clone)]
26pub struct RocksdbCore {
27    pub db: Arc<DB>,
28}
29
30impl Debug for RocksdbCore {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("RocksdbCore")
33            .field("path", &self.db.path())
34            .finish()
35    }
36}
37
38impl RocksdbCore {
39    pub fn get(&self, path: &str) -> Result<Option<Buffer>> {
40        let result = self.db.get(path).map_err(parse_rocksdb_error)?;
41        Ok(result.map(Buffer::from))
42    }
43
44    pub fn set(&self, path: &str, value: Buffer) -> Result<()> {
45        self.db
46            .put(path, value.to_vec())
47            .map_err(parse_rocksdb_error)
48    }
49
50    pub fn delete(&self, path: &str) -> Result<()> {
51        self.db.delete(path).map_err(parse_rocksdb_error)
52    }
53
54    pub fn list(&self, path: &str) -> Result<Vec<String>> {
55        let it = self.db.prefix_iterator(path).map(|r| r.map(|(k, _)| k));
56        let mut res = Vec::default();
57
58        for key in it {
59            let key = key.map_err(parse_rocksdb_error)?;
60            let key = String::from_utf8_lossy(&key);
61            if !key.starts_with(path) {
62                break;
63            }
64            res.push(key.to_string());
65        }
66
67        Ok(res)
68    }
69}
70
71fn parse_rocksdb_error(e: rocksdb::Error) -> Error {
72    Error::new(ErrorKind::Unexpected, "got rocksdb error").set_source(e)
73}