manifoldb 0.1.4

A multi-paradigm embedded database for graph, vector, and relational data
Documentation
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Database configuration and builder pattern.
//!
//! This module provides [`DatabaseBuilder`] for configuring and opening a database,
//! and [`Config`] which holds the final configuration values.
//!
//! # Example
//!
//! ```ignore
//! use manifoldb::DatabaseBuilder;
//!
//! let db = DatabaseBuilder::new()
//!     .path("mydb.manifold")
//!     .create_if_missing(true)
//!     .cache_size(64 * 1024 * 1024)  // 64MB cache
//!     .open()?;
//! ```

use std::path::{Path, PathBuf};

use crate::cache::CacheConfig;
use crate::error::Error;
use crate::transaction::{BatchWriterConfig, TransactionManagerConfig, VectorSyncStrategy};

/// Default maximum rows in memory (1 million rows).
pub const DEFAULT_MAX_ROWS_IN_MEMORY: usize = 1_000_000;

/// Configuration for a database.
///
/// This struct holds the validated configuration for opening a database.
/// Use [`DatabaseBuilder`] to construct a `Config` with a fluent API.
#[derive(Debug, Clone)]
pub struct Config {
    /// Path to the database file.
    pub path: PathBuf,

    /// Whether to create the database if it doesn't exist.
    pub create_if_missing: bool,

    /// Cache size in bytes. If `None`, uses the default.
    pub cache_size: Option<usize>,

    /// Maximum database size in bytes. If `None`, grows as needed.
    pub max_size: Option<u64>,

    /// Strategy for vector index synchronization.
    pub vector_sync_strategy: VectorSyncStrategy,

    /// Whether to use an in-memory database (for testing).
    pub in_memory: bool,

    /// Configuration for the query result cache.
    pub query_cache_config: CacheConfig,

    /// Configuration for write batching.
    pub batch_writer_config: BatchWriterConfig,

    /// Maximum rows that operators can materialize in memory.
    ///
    /// This limit applies to blocking operators like sort, join, and aggregate.
    /// When exceeded, queries return a `QueryTooLarge` error.
    ///
    /// Set to 0 to disable the limit (not recommended for production).
    /// Default: 1,000,000 rows.
    pub max_rows_in_memory: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            path: PathBuf::new(),
            create_if_missing: true,
            cache_size: None,
            max_size: None,
            vector_sync_strategy: VectorSyncStrategy::Synchronous,
            in_memory: false,
            query_cache_config: CacheConfig::default(),
            batch_writer_config: BatchWriterConfig::default(),
            max_rows_in_memory: DEFAULT_MAX_ROWS_IN_MEMORY,
        }
    }
}

impl Config {
    /// Create a new configuration with the given path.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into(), ..Default::default() }
    }

    /// Create an in-memory configuration (for testing).
    #[must_use]
    pub fn in_memory() -> Self {
        Self { in_memory: true, ..Default::default() }
    }

    /// Set whether to create the database if it doesn't exist.
    #[must_use]
    pub const fn create_if_missing(mut self, create: bool) -> Self {
        self.create_if_missing = create;
        self
    }

    /// Get the transaction manager configuration.
    #[must_use]
    pub fn transaction_config(&self) -> TransactionManagerConfig {
        TransactionManagerConfig {
            vector_sync_strategy: self.vector_sync_strategy,
            batch_writer_config: self.batch_writer_config.clone(),
        }
    }
}

/// Builder for opening a database with custom configuration.
///
/// `DatabaseBuilder` provides a fluent API for configuring and opening a
/// `ManifoldDB` database.
///
/// # Examples
///
/// Open or create a database at a path:
///
/// ```ignore
/// use manifoldb::DatabaseBuilder;
///
/// let db = DatabaseBuilder::new()
///     .path("mydb.manifold")
///     .open()?;
/// ```
///
/// Configure cache size and vector sync strategy:
///
/// ```ignore
/// use manifoldb::{DatabaseBuilder, VectorSyncStrategy};
///
/// let db = DatabaseBuilder::new()
///     .path("mydb.manifold")
///     .cache_size(128 * 1024 * 1024)  // 128MB
///     .vector_sync_strategy(VectorSyncStrategy::Async)
///     .open()?;
/// ```
///
/// Create an in-memory database for testing:
///
/// ```ignore
/// use manifoldb::DatabaseBuilder;
///
/// let db = DatabaseBuilder::in_memory().open()?;
/// ```
#[derive(Debug, Clone, Default)]
pub struct DatabaseBuilder {
    config: Config,
}

impl DatabaseBuilder {
    /// Create a new builder with default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for an in-memory database.
    ///
    /// In-memory databases are useful for testing and temporary data.
    /// The data will be lost when the database is closed.
    #[must_use]
    pub fn in_memory() -> Self {
        Self { config: Config::in_memory() }
    }

    /// Set the path to the database file.
    ///
    /// The path should end with `.manifold` or `.redb` by convention.
    #[must_use]
    pub fn path(mut self, path: impl AsRef<Path>) -> Self {
        self.config.path = path.as_ref().to_path_buf();
        self.config.in_memory = false;
        self
    }

    /// Set whether to create the database if it doesn't exist.
    ///
    /// Defaults to `true`.
    #[must_use]
    pub const fn create_if_missing(mut self, create: bool) -> Self {
        self.config.create_if_missing = create;
        self
    }

    /// Set the cache size in bytes.
    ///
    /// A larger cache can improve read performance for frequently accessed data.
    /// If not set, the storage engine's default cache size is used.
    #[must_use]
    pub const fn cache_size(mut self, size: usize) -> Self {
        self.config.cache_size = Some(size);
        self
    }

    /// Set the maximum database size in bytes.
    ///
    /// If not set, the database will grow as needed.
    #[must_use]
    pub const fn max_size(mut self, size: u64) -> Self {
        self.config.max_size = Some(size);
        self
    }

    /// Set the vector synchronization strategy.
    ///
    /// This controls how vector index updates are synchronized with transactions:
    ///
    /// - [`VectorSyncStrategy::Synchronous`] - Strong consistency, slower writes
    /// - [`VectorSyncStrategy::Async`] - Eventual consistency, faster writes
    /// - [`VectorSyncStrategy::Hybrid`] - Adaptive based on batch size
    ///
    /// Defaults to [`VectorSyncStrategy::Synchronous`].
    #[must_use]
    pub const fn vector_sync_strategy(mut self, strategy: VectorSyncStrategy) -> Self {
        self.config.vector_sync_strategy = strategy;
        self
    }

    /// Set the query cache configuration.
    ///
    /// The query cache stores the results of SELECT queries to avoid
    /// repeated execution of identical queries.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{DatabaseBuilder, cache::CacheConfig};
    /// use std::time::Duration;
    ///
    /// let db = DatabaseBuilder::new()
    ///     .path("mydb.manifold")
    ///     .query_cache_config(
    ///         CacheConfig::new()
    ///             .max_entries(5000)
    ///             .ttl(Some(Duration::from_secs(600)))
    ///     )
    ///     .open()?;
    /// ```
    #[must_use]
    pub fn query_cache_config(mut self, config: CacheConfig) -> Self {
        self.config.query_cache_config = config;
        self
    }

    /// Disable the query cache.
    ///
    /// Equivalent to `query_cache_config(CacheConfig::disabled())`.
    #[must_use]
    pub fn disable_query_cache(mut self) -> Self {
        self.config.query_cache_config = CacheConfig::disabled();
        self
    }

    /// Set the batch writer configuration for concurrent write optimization.
    ///
    /// Write batching groups multiple concurrent transactions into a single
    /// commit, improving throughput under concurrent load.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::{DatabaseBuilder, BatchWriterConfig};
    /// use std::time::Duration;
    ///
    /// let db = DatabaseBuilder::new()
    ///     .path("mydb.manifold")
    ///     .batch_writer_config(
    ///         BatchWriterConfig::new()
    ///             .max_batch_size(50)
    ///             .flush_interval(Duration::from_millis(5))
    ///     )
    ///     .open()?;
    /// ```
    #[must_use]
    pub fn batch_writer_config(mut self, config: BatchWriterConfig) -> Self {
        self.config.batch_writer_config = config;
        self
    }

    /// Disable write batching (use immediate commits).
    ///
    /// This can be useful for debugging or when write latency is more
    /// important than throughput.
    #[must_use]
    pub fn disable_write_batching(mut self) -> Self {
        self.config.batch_writer_config = BatchWriterConfig::disabled();
        self
    }

    /// Set the maximum rows that operators can materialize in memory.
    ///
    /// This limit applies to blocking operators like sort, join, and aggregate.
    /// When exceeded, queries return a `QueryTooLarge` error instead of consuming
    /// unbounded memory.
    ///
    /// Set to 0 to disable the limit (not recommended for production).
    /// Default: 1,000,000 rows.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use manifoldb::DatabaseBuilder;
    ///
    /// let db = DatabaseBuilder::new()
    ///     .path("mydb.manifold")
    ///     .max_rows_in_memory(500_000)  // 500K row limit
    ///     .open()?;
    /// ```
    #[must_use]
    pub const fn max_rows_in_memory(mut self, limit: usize) -> Self {
        self.config.max_rows_in_memory = limit;
        self
    }

    /// Get the current configuration.
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Build and validate the configuration.
    ///
    /// This validates the configuration before opening the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration is invalid (e.g., no path specified
    /// for a non-in-memory database).
    pub fn build(self) -> Result<Config, Error> {
        if !self.config.in_memory && self.config.path.as_os_str().is_empty() {
            return Err(Error::Config("database path is required".to_string()));
        }
        Ok(self.config)
    }

    /// Open the database with the configured options.
    ///
    /// This is a convenience method equivalent to calling `build()` followed
    /// by `Database::open_with_config()`.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration is invalid or the database
    /// cannot be opened.
    pub fn open(self) -> Result<crate::database::Database, Error> {
        let config = self.build()?;
        crate::database::Database::open_with_config(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_config_new() {
        let config = Config::new("/tmp/test.manifold");
        assert_eq!(config.path, PathBuf::from("/tmp/test.manifold"));
        assert!(config.create_if_missing);
        assert!(!config.in_memory);
    }

    #[test]
    fn test_config_in_memory() {
        let config = Config::in_memory();
        assert!(config.in_memory);
        assert!(config.path.as_os_str().is_empty());
    }

    #[test]
    fn test_builder_path() {
        let builder = DatabaseBuilder::new().path("/tmp/test.manifold");
        assert_eq!(builder.config.path, PathBuf::from("/tmp/test.manifold"));
        assert!(!builder.config.in_memory);
    }

    #[test]
    fn test_builder_in_memory() {
        let builder = DatabaseBuilder::in_memory();
        assert!(builder.config.in_memory);
    }

    #[test]
    fn test_builder_cache_size() {
        let builder = DatabaseBuilder::new().cache_size(1024 * 1024);
        assert_eq!(builder.config.cache_size, Some(1024 * 1024));
    }

    #[test]
    fn test_builder_vector_sync_strategy() {
        let builder = DatabaseBuilder::new().vector_sync_strategy(VectorSyncStrategy::Async);
        assert_eq!(builder.config.vector_sync_strategy, VectorSyncStrategy::Async);
    }

    #[test]
    fn test_builder_build_requires_path() {
        let result = DatabaseBuilder::new().build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_build_with_path() {
        let result = DatabaseBuilder::new().path("/tmp/test.manifold").build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_build_in_memory() {
        let result = DatabaseBuilder::in_memory().build();
        assert!(result.is_ok());
    }
}