1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Copyright 2019 Xuejie Xiao
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use crate::ffi;
use crate::ffi_util;

use crate::{
    db_iterator::DBRawIterator,
    db_options::{OptionsMustOutliveDB, ReadOptions},
    handle::Handle,
    open_raw::{OpenRaw, OpenRawFFI},
    ops, ColumnFamily, Error,
};

use std::collections::BTreeMap;
use std::fmt;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};

pub struct SecondaryDB {
    pub(crate) inner: *mut ffi::rocksdb_t,
    cfs: BTreeMap<String, ColumnFamily>,
    path: PathBuf,
    _outlive: Vec<OptionsMustOutliveDB>,
}

impl SecondaryDB {
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    pub fn try_catch_up_with_primary(&self) -> Result<(), Error> {
        unsafe { ffi_try!(ffi::rocksdb_try_catch_up_with_primary(self.inner,)) };
        Ok(())
    }
}

pub struct SecondaryOpenDescriptor {
    secondary_path: String,
}

impl Default for SecondaryOpenDescriptor {
    fn default() -> Self {
        SecondaryOpenDescriptor {
            secondary_path: "".to_string(),
        }
    }
}

impl SecondaryOpenDescriptor {
    pub fn new(secondary_path: String) -> Self {
        Self { secondary_path }
    }
}

impl ops::Open for SecondaryDB {}
impl ops::OpenCF for SecondaryDB {}

impl OpenRaw for SecondaryDB {
    type Pointer = ffi::rocksdb_t;
    type Descriptor = SecondaryOpenDescriptor;

    fn open_ffi(input: OpenRawFFI<'_, Self::Descriptor>) -> Result<*mut Self::Pointer, Error> {
        if input.open_descriptor.secondary_path.is_empty() {
            return Err(Error::new(
                "Secondary DB must have secondary path provided!".to_string(),
            ));
        }
        let secondary_path = ffi_util::to_cpath(
            &input.open_descriptor.secondary_path,
            "Failed to convert path to CString when opening database.",
        )?;
        let pointer = unsafe {
            if input.num_column_families <= 0 {
                ffi_try!(ffi::rocksdb_open_as_secondary(
                    input.options,
                    input.path,
                    secondary_path.as_ptr(),
                ))
            } else {
                ffi_try!(ffi::rocksdb_open_as_secondary_column_families(
                    input.options,
                    input.path,
                    secondary_path.as_ptr(),
                    input.num_column_families,
                    input.column_family_names,
                    input.column_family_options,
                    input.column_family_handles,
                ))
            }
        };

        Ok(pointer)
    }

    fn build<I>(
        path: PathBuf,
        _open_descriptor: Self::Descriptor,
        pointer: *mut Self::Pointer,
        column_families: I,
        outlive: Vec<OptionsMustOutliveDB>,
    ) -> Result<Self, Error>
    where
        I: IntoIterator<Item = (String, *mut ffi::rocksdb_column_family_handle_t)>,
    {
        let cfs: BTreeMap<_, _> = column_families
            .into_iter()
            .map(|(k, h)| (k, ColumnFamily::new(h)))
            .collect();
        Ok(SecondaryDB {
            inner: pointer,
            cfs,
            path,
            _outlive: outlive,
        })
    }
}

impl Handle<ffi::rocksdb_t> for SecondaryDB {
    fn handle(&self) -> *mut ffi::rocksdb_t {
        self.inner
    }
}

impl ops::Iterate for SecondaryDB {
    fn get_raw_iter<'a: 'b, 'b>(&'a self, readopts: &ReadOptions) -> DBRawIterator<'b> {
        unsafe {
            DBRawIterator {
                inner: ffi::rocksdb_create_iterator(self.inner, readopts.handle()),
                db: PhantomData,
            }
        }
    }
}

impl ops::IterateCF for SecondaryDB {
    fn get_raw_iter_cf<'a: 'b, 'b>(
        &'a self,
        cf_handle: &ColumnFamily,
        readopts: &ReadOptions,
    ) -> Result<DBRawIterator<'b>, Error> {
        unsafe {
            Ok(DBRawIterator {
                inner: ffi::rocksdb_create_iterator_cf(
                    self.inner,
                    readopts.handle(),
                    cf_handle.inner,
                ),
                db: PhantomData,
            })
        }
    }
}

impl ops::GetColumnFamilys for SecondaryDB {
    fn get_cfs(&self) -> &BTreeMap<String, ColumnFamily> {
        &self.cfs
    }
    fn get_mut_cfs(&mut self) -> &mut BTreeMap<String, ColumnFamily> {
        &mut self.cfs
    }
}

impl ops::Read for SecondaryDB {}

unsafe impl Send for SecondaryDB {}
unsafe impl Sync for SecondaryDB {}

impl Drop for SecondaryDB {
    fn drop(&mut self) {
        unsafe {
            for cf in self.cfs.values() {
                ffi::rocksdb_column_family_handle_destroy(cf.inner);
            }
            ffi::rocksdb_close(self.inner);
        }
    }
}

impl fmt::Debug for SecondaryDB {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Read-only RocksDB {{ path: {:?} }}", self.path())
    }
}