ic-nosql 0.1.3

A flexible NoSQL database library for Internet Computer canisters
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use candid::CandidType;
use ic_stable_structures::{StableBTreeMap, Storable};
use serde::{Deserialize, Serialize};
use std::cell::RefCell;

use super::types::{CompositeKey, CompositeKeys, Document, QueryResponse};
use crate::memory::stable_memory::Memory;

/// Database implementation with support for primary and secondary indexes
pub struct Database<T, SecondaryKey = ()>
where
    T: CandidType + Serialize + for<'de> Deserialize<'de> + Clone,
    SecondaryKey: Clone + Ord + Storable,
{
    map: RefCell<StableBTreeMap<CompositeKey, Document<T>, Memory>>, // Primary map
    secondary_index: Option<RefCell<StableBTreeMap<SecondaryKey, CompositeKeys, Memory>>>, // Optional secondary index
    get_secondary_key: Option<Box<dyn Fn(&T) -> Option<SecondaryKey>>>, // Function to derive secondary index key
}

impl<T, SecondaryKey> Database<T, SecondaryKey>
where
    T: CandidType + Serialize + for<'de> Deserialize<'de> + Clone,
    SecondaryKey: Storable + Ord + Clone,
{
    /// Constructor to initialize the NoSQL database with an optional secondary index
    pub fn new(
        map: RefCell<StableBTreeMap<CompositeKey, Document<T>, Memory>>,
        secondary_index: Option<RefCell<StableBTreeMap<SecondaryKey, CompositeKeys, Memory>>>,
        get_secondary_key: Option<Box<dyn Fn(&T) -> Option<SecondaryKey>>>,
    ) -> Self {
        Database {
            map,
            secondary_index,
            get_secondary_key,
        }
    }

    /// Insert a document and update secondary index if applicable
    pub fn insert(
        &self,
        partition_key: String,
        sort_key: Option<String>,
        data: T,
    ) -> Result<Document<T>, String> {
        let document = Document {
            partition_key: partition_key.clone(),
            sort_key: sort_key.clone(),
            data: data.clone(),
        };

        let key = CompositeKey {
            partition_key: partition_key.clone(),
            sort_key: sort_key.clone(),
        };

        // To avoid borrowing conflicts, check and remove existing documents in separate scopes
        let old_secondary_key = {
            // Check if the key already exists in the primary map
            if let Some(existing_document) = self.map.borrow().get(&key) {
                // If the document exists, check if there is an old secondary key
                if let (Some(_), Some(get_secondary_key)) =
                    (&self.secondary_index, &self.get_secondary_key)
                {
                    get_secondary_key(&existing_document.data)
                } else {
                    None
                }
            } else {
                None
            }
        };

        // If an old secondary key exists, update the secondary index
        if let Some(old_key) = old_secondary_key {
            if let (Some(secondary_index), _) = (&self.secondary_index, &self.get_secondary_key) {
                let mut index_map = secondary_index.borrow_mut();
                if let Some(mut composite_keys) = index_map.get(&old_key) {
                    // Remove the stale key from the secondary index
                    composite_keys.0.retain(|k| k != &key);

                    // If no keys remain, remove the secondary key entry
                    if composite_keys.0.is_empty() {
                        index_map.remove(&old_key);
                    } else {
                        index_map.insert(old_key, composite_keys);
                    }
                }
            }
        }

        // Remove the old document
        {
            let mut map = self.map.borrow_mut();
            // Explicitly remove the old document from the primary map to free memory
            map.remove(&key);
            // Insert into the primary map
            map.insert(key.clone(), document.clone());
        }

        // Update the secondary index if a key function is provided
        if let (Some(secondary_index), Some(get_secondary_key)) =
            (&self.secondary_index, &self.get_secondary_key)
        {
            if let Some(new_secondary_key) = get_secondary_key(&data) {
                let mut index_map = secondary_index.borrow_mut();

                // Check if the secondary key already exists
                if let Some(mut composite_keys) = index_map.get(&new_secondary_key) {
                    // If it exists, append the new key
                    composite_keys.0.push(key.clone());
                    index_map.insert(new_secondary_key.clone(), composite_keys);
                } else {
                    // If it doesn't exist, create a new CompositeKeys entry
                    index_map.insert(new_secondary_key, CompositeKeys(vec![key.clone()]));
                }
            }
        }

        Ok(document)
    }

    /// Get a single document by partition key and optional sort key
    pub fn get(
        &self,
        partition_key: &str,
        sort_key: Option<String>,
    ) -> Result<Document<T>, String> {
        let key = CompositeKey {
            partition_key: partition_key.to_string(),
            sort_key,
        };

        // Attempt to retrieve the document from the primary map
        self.map
            .borrow()
            .get(&key)
            .ok_or("Document not found.".to_string())
    }

    /// Query by either partition key or secondary index with pagination
    pub fn query(
        &self,
        partition_key: Option<&str>,
        secondary_key: Option<SecondaryKey>,
        page_size: usize,
        page_number: usize,
    ) -> Result<QueryResponse<T>, String> {
        // Validate page params
        if page_size == 0 {
            return Err("Page size must be greater than 0.".to_string());
        }
        if page_number == 0 {
            return Err("Page number must be greater than 0.".to_string());
        }

        match (partition_key, secondary_key) {
            (Some(partition_key), None) => {
                self.query_by_partition_key(partition_key, page_size, page_number)
            }
            (None, Some(secondary_key)) => {
                self.query_by_secondary_key(secondary_key, page_size, page_number)
            }
            (Some(partition_key), Some(secondary_key)) => self
                .query_by_partition_and_secondary_key(
                    partition_key,
                    secondary_key,
                    page_size,
                    page_number,
                ),
            (None, None) => {
                Err("At least one of partition key or secondary key must be provided.".to_string())
            }
        }
    }

    // Helper method for querying by partition key
    fn query_by_partition_key(
        &self,
        partition_key: &str,
        page_size: usize,
        page_number: usize,
    ) -> Result<QueryResponse<T>, String> {
        // Get all entries from the primary map
        let map = self.map.borrow();

        // Create a range for the given partition key to find all matching entries
        let range_start = CompositeKey {
            partition_key: partition_key.to_string(),
            sort_key: None,
        };
        let range_end = CompositeKey {
            partition_key: partition_key.to_string(),
            sort_key: Some(String::from("\u{10FFFF}")), // Maximum Unicode value as range end
        };

        // Collect matching documents within the range
        let matching_documents: Vec<Document<T>> = map
            .range(range_start..=range_end)
            .map(|(_, doc)| doc.clone())
            .collect();

        // Check if any documents were found
        if matching_documents.is_empty() {
            return Err(format!(
                "No documents found for partition key '{}'",
                partition_key
            ));
        }

        // Apply pagination
        let start_index = (page_number - 1) * page_size;

        // Check if the requested page exists
        if start_index >= matching_documents.len() {
            return Err(format!(
                "Page {} does not exist. Total documents: {}, Page size: {}",
                page_number,
                matching_documents.len(),
                page_size
            ));
        }

        // Calculate total pages
        let total_pages = (matching_documents.len() + page_size - 1) / page_size;

        // Return the paginated subset
        Ok(QueryResponse {
            page_number,
            page_size,
            total_pages,
            results: matching_documents
                .into_iter()
                .skip(start_index)
                .take(page_size)
                .collect(),
        })
    }

    // Helper method for querying by secondary key
    fn query_by_secondary_key(
        &self,
        secondary_key: SecondaryKey,
        page_size: usize,
        page_number: usize,
    ) -> Result<QueryResponse<T>, String> {
        // Query by secondary key
        let secondary_index = match &self.secondary_index {
            Some(index) => index,
            None => return Err("Secondary index not configured.".to_string()),
        };

        // Retrieve keys matching the secondary index
        let keys = secondary_index
            .borrow()
            .get(&secondary_key)
            .ok_or("No entries found for the given secondary key.".to_string())?;

        // Get all matching documents
        let matching_documents: Vec<Document<T>> = keys
            .0
            .iter()
            .filter_map(|key| self.map.borrow().get(key))
            .collect();

        // Calculate pagination indices
        let start_index = (page_number - 1) * page_size;

        // Check if the requested page exists
        if start_index >= matching_documents.len() {
            return Err(format!(
                "Page {} does not exist. Total documents: {}, Page size: {}",
                page_number,
                matching_documents.len(),
                page_size
            ));
        }

        // Calculate total pages
        let total_pages = (matching_documents.len() + page_size - 1) / page_size;

        // Return the paginated subset
        Ok(QueryResponse {
            page_number,
            page_size,
            total_pages,
            results: matching_documents
                .into_iter()
                .skip(start_index)
                .take(page_size)
                .collect(),
        })
    }

    // Helper method for querying by both partition key and secondary key
    fn query_by_partition_and_secondary_key(
        &self,
        partition_key: &str,
        secondary_key: SecondaryKey,
        page_size: usize,
        page_number: usize,
    ) -> Result<QueryResponse<T>, String> {
        // Query by both partition key and secondary key
        let secondary_index = match &self.secondary_index {
            Some(index) => index,
            None => return Err("Secondary index not configured.".to_string()),
        };

        let keys = secondary_index
            .borrow()
            .get(&secondary_key)
            .ok_or_else(|| {
                format!(
                    "No entries found for partition key '{}' and secondary key.",
                    partition_key
                )
            })?;

        // Get all matching documents filtered by partition key
        let matching_documents: Vec<Document<T>> = keys
            .0
            .iter()
            .filter(|key| key.partition_key == partition_key)
            .filter_map(|key| self.map.borrow().get(key))
            .collect();

        if matching_documents.is_empty() {
            return Err(format!(
                "No entries found for partition key '{}' and secondary key.",
                partition_key
            ));
        }

        // Calculate pagination indices
        let start_index = (page_number - 1) * page_size;

        // Check if the requested page exists
        if start_index >= matching_documents.len() {
            return Err(format!(
                "Page {} does not exist. Total documents: {}, Page size: {}",
                page_number,
                matching_documents.len(),
                page_size
            ));
        }

        // Calculate total pages
        let total_pages = (matching_documents.len() + page_size - 1) / page_size;

        // Return the paginated subset
        Ok(QueryResponse {
            page_number,
            page_size,
            total_pages,
            results: matching_documents
                .into_iter()
                .skip(start_index)
                .take(page_size)
                .collect(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use candid::Principal;
    use candid::{CandidType, Decode, Encode};
    use ic_stable_structures::memory_manager::{MemoryId, MemoryManager};
    use ic_stable_structures::{storable::Bound, DefaultMemoryImpl, StableBTreeMap, Storable};
    use std::borrow::Cow;
    use std::cell::RefCell;

    // Define a sample Account struct for testing
    #[derive(Clone, Debug, Serialize, Deserialize, CandidType, PartialEq, Eq, PartialOrd, Ord)]
    pub enum AccountStatus {
        Active,
        Inactive,
        Suspended,
    }

    impl Storable for AccountStatus {
        fn to_bytes(&self) -> Cow<[u8]> {
            Cow::Owned(Encode!(self).unwrap())
        }

        fn from_bytes(bytes: Cow<[u8]>) -> Self {
            Decode!(bytes.as_ref(), AccountStatus).unwrap()
        }

        const BOUND: Bound = Bound::Unbounded;
    }

    #[derive(Clone, Debug, Serialize, Deserialize, CandidType, PartialEq)]
    pub struct TestAccountStruct {
        pub id: String,
        pub owner: Principal,
        pub balance: u64,
        pub status: AccountStatus,
    }

    thread_local! {
        static MEMORY_MANAGER: RefCell<MemoryManager<DefaultMemoryImpl>> =
            RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()));
    }

    // Helper function to create a Database instance without a secondary index
    fn create_test_db() -> Database<TestAccountStruct> {
        let map = RefCell::new(StableBTreeMap::init(
            MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0))),
        ));
        Database::new(map, None, None)
    }

    // Helper function to create a Database instance with a secondary index on the `status` field
    fn create_test_db_with_secondary_index() -> Database<TestAccountStruct, AccountStatus> {
        let map = RefCell::new(StableBTreeMap::init(
            MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0))),
        ));
        let secondary_index = RefCell::new(StableBTreeMap::init(
            MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(1))),
        ));

        let get_secondary_key =
            Box::new(|account: &TestAccountStruct| Some(account.status.clone()));

        Database::new(map, Some(secondary_index), Some(get_secondary_key))
    }

    #[test]
    fn test_insert_and_get_document() {
        let db = create_test_db();

        let account = TestAccountStruct {
            id: "1".to_string(),
            owner: Principal::anonymous(),
            balance: 1000,
            status: AccountStatus::Active,
        };

        let result = db.insert("user_1".to_string(), Some("1".to_string()), account.clone());
        assert!(result.is_ok());

        let retrieved = db.get("user_1", Some("1".to_string()));
        assert!(retrieved.is_ok());

        let retrieved_account = retrieved.unwrap();
        assert_eq!(retrieved_account.data, account);
    }

    #[test]
    fn test_query_by_secondary_key() {
        let db = create_test_db_with_secondary_index();

        let accounts = vec![
            TestAccountStruct {
                id: "1".to_string(),
                owner: Principal::anonymous(),
                balance: 1000,
                status: AccountStatus::Active,
            },
            TestAccountStruct {
                id: "2".to_string(),
                owner: Principal::anonymous(),
                balance: 2000,
                status: AccountStatus::Inactive,
            },
        ];

        for account in &accounts {
            db.insert(
                "user".to_string(),
                Some(account.id.clone()),
                account.clone(),
            )
            .unwrap();
        }

        let results = db
            .query(None, Some(AccountStatus::Active), 10, 1)
            .unwrap()
            .results;
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].data.id, "1");
    }
}