netabase_store 0.0.8

A type-safe, multi-backend key-value storage library for Rust with support for native (Sled, Redb) and WASM (IndexedDB) environments.
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use crate::error::NetabaseError;
use crate::traits::convert::ToIVec;
use crate::traits::definition::NetabaseDefinitionTrait;
use crate::traits::model::NetabaseModelTrait;
use crate::{MaybeSend, MaybeSync, NetabaseModelTraitKey};
use std::marker::PhantomData;
use std::str::FromStr;
use strum::IntoDiscriminant;

use super::iterator::SledIter;

/// Type-safe wrapper around a sled tree for a specific model type.
///
/// `SledStoreTree` provides CRUD operations for a single model type with:
/// - Automatic bincode serialization/deserialization
/// - Primary key indexing
/// - Secondary key indexing and querying
/// - Type-safe operations (compile-time checking)
///
/// This is the primary interface for interacting with stored models. Each model type
/// gets its own tree, providing isolation and type safety.
///
/// # Type Parameters
///
/// * `'db` - Lifetime parameter that ties the tree to its parent database, ensuring trees cannot outlive their stores
/// * `D` - The definition type (generated by `#[netabase_definition_module]`)
/// * `M` - The model type (annotated with `#[derive(NetabaseModel)]`)
///
/// # Examples
///
/// ## Basic CRUD Operations
///
/// ```rust
/// use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
/// use netabase_store::databases::sled_store::SledStore;
/// use netabase_store::traits::tree::NetabaseTreeSync;
/// use netabase_store::traits::model::NetabaseModelTrait;
///
/// #[netabase_definition_module(StoreDef, StoreKeys)]
/// mod store {
///     use super::*;
/// use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
///     #[derive(NetabaseModel, Clone, Debug, PartialEq,
///              bincode::Encode, bincode::Decode,
///              serde::Serialize, serde::Deserialize)]
///     #[netabase(StoreDef)]
///     pub struct Book {
///         #[primary_key]
///         pub isbn: String,
///         pub title: String,
///         pub author: String,
///         #[secondary_key]
///         pub genre: String,
///     }
/// }
/// use store::*;
///
/// let store = SledStore::<StoreDef>::temp().unwrap();
/// let books = store.open_tree::<Book>();
///
/// // Create
/// let book = Book {
///     isbn: "978-0-12-345678-9".to_string(),
///     title: "Rust Programming".to_string(),
///     author: "Alice".to_string(),
///     genre: "Tech".to_string(),
/// };
/// books.put(book.clone()).unwrap();
///
/// // Read by primary key
/// let retrieved = books.get(book.primary_key()).unwrap();
/// assert_eq!(retrieved, Some(book.clone()));
///
/// // Query by secondary key using convenience function
/// use store::AsBookGenre;
/// let tech_books = books.get_by_secondary_key("Tech".as_book_genre_key()).unwrap();
/// assert_eq!(tech_books.len(), 1);
///
/// // Update (same as put)
/// let mut updated_book = book.clone();
/// updated_book.author = "Alice Smith".to_string();
/// books.put(updated_book.clone()).unwrap();
///
/// // Delete
/// let deleted = books.remove(updated_book.primary_key()).unwrap();
/// assert!(deleted.is_some());
/// ```
///
///
pub struct SledStoreTree<'db, D, M>
where
    D: NetabaseDefinitionTrait,
    M: NetabaseModelTrait<D>,
    <D as IntoDiscriminant>::Discriminant: Clone
        + Copy
        + std::fmt::Debug
        + std::fmt::Display
        + PartialEq
        + Eq
        + std::hash::Hash
        + strum::IntoEnumIterator
        + MaybeSend
        + MaybeSync
        + 'static
        + FromStr,
    <D as strum::IntoDiscriminant>::Discriminant: std::marker::Copy,
    <D as strum::IntoDiscriminant>::Discriminant: std::fmt::Debug,
    <D as strum::IntoDiscriminant>::Discriminant: std::hash::Hash,
    <D as strum::IntoDiscriminant>::Discriminant: std::cmp::Eq,
    <D as strum::IntoDiscriminant>::Discriminant: std::fmt::Display,
    <D as strum::IntoDiscriminant>::Discriminant: FromStr,
    <D as strum::IntoDiscriminant>::Discriminant: MaybeSync,
    <D as strum::IntoDiscriminant>::Discriminant: MaybeSend,
    <D as strum::IntoDiscriminant>::Discriminant: strum::IntoEnumIterator,
    <D as strum::IntoDiscriminant>::Discriminant: std::convert::AsRef<str>,
{
    pub(crate) tree: sled::Tree,
    pub(crate) secondary_tree: sled::Tree,
    pub db: sled::Db,
    pub(crate) _phantom_d: PhantomData<D>,
    pub(crate) _phantom_m: PhantomData<M>,
    pub(crate) _phantom_db: PhantomData<&'db ()>,
}

impl<'db, D, M> SledStoreTree<'db, D, M>
where
    D: NetabaseDefinitionTrait + TryFrom<M> + ToIVec,
    M: NetabaseModelTrait<D> + TryFrom<D> + Into<D>,
    <D as IntoDiscriminant>::Discriminant: Clone
        + Copy
        + std::fmt::Debug
        + std::fmt::Display
        + PartialEq
        + Eq
        + std::hash::Hash
        + strum::IntoEnumIterator
        + MaybeSend
        + MaybeSync
        + 'static
        + FromStr,
    <D as strum::IntoDiscriminant>::Discriminant: std::marker::Copy,
    <D as strum::IntoDiscriminant>::Discriminant: std::fmt::Debug,
    <D as strum::IntoDiscriminant>::Discriminant: std::hash::Hash,
    <D as strum::IntoDiscriminant>::Discriminant: std::cmp::Eq,
    <D as strum::IntoDiscriminant>::Discriminant: std::fmt::Display,
    <D as strum::IntoDiscriminant>::Discriminant: FromStr,
    <D as strum::IntoDiscriminant>::Discriminant: MaybeSync,
    <D as strum::IntoDiscriminant>::Discriminant: MaybeSend,
    <D as strum::IntoDiscriminant>::Discriminant: strum::IntoEnumIterator,
    <D as strum::IntoDiscriminant>::Discriminant: std::convert::AsRef<str>,
{
    /// Create a new SledStoreTree
    pub(crate) fn new(db: &sled::Db, tree_name: D::Discriminant) -> Self {
        let tree = db
            .open_tree(tree_name.to_string())
            .expect("Failed to open tree");
        let sec_tree_name = format!("{}_secondary", M::discriminant_name());
        let secondary_tree = db
            .open_tree(sec_tree_name)
            .expect("Failed to open secondary tree");
        Self {
            tree,
            secondary_tree,
            db: db.clone(),
            _phantom_d: PhantomData,
            _phantom_m: PhantomData,
            _phantom_db: PhantomData,
        }
    }

    /// Insert or update a model in the tree.
    ///
    /// If a model with the same primary key already exists, it will be overwritten.
    /// This method automatically:
    /// - Serializes the model using bincode
    /// - Updates secondary key indexes atomically using batching
    /// - Persists the data to disk (eventually, via sled's write-ahead log)
    ///
    /// # Arguments
    ///
    /// * `model` - The model instance to insert or update (consumed)
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Model successfully stored
    /// * `Err(NetabaseError)` - Serialization or I/O error
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # use netabase_store::traits::model::NetabaseModelTrait;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, PartialEq, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Task { #[primary_key] pub id: u64, pub title: String, pub done: bool }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let tasks = store.open_tree::<Task>();
    ///
    /// // Insert a new task
    /// let task = Task { id: 1, title: "Learn Rust".to_string(), done: false };
    /// tasks.put(task).unwrap();
    ///
    /// // Update the task (same primary key)
    /// let updated_task = Task { id: 1, title: "Learn Rust".to_string(), done: true };
    /// tasks.put(updated_task).unwrap();
    ///
    /// // Verify update
    /// let retrieved_task = Task { id: 1, title: "".to_string(), done: false };
    /// let retrieved = tasks.get(retrieved_task.primary_key()).unwrap().unwrap();
    /// assert_eq!(retrieved.done, true);
    /// ```
    pub fn put(&self, model: M) -> Result<(), NetabaseError>
    where
        D: From<M>,
    {
        let primary_key = model.primary_key();
        let secondary_keys = model.secondary_keys();

        let key_bytes = bincode::encode_to_vec(&primary_key, bincode::config::standard())
            .map_err(crate::error::EncodingDecodingError::from)?;

        let definition: D = model.into();
        let value_bytes = definition.to_ivec()?;

        // Use batch for atomic operations
        let mut batch = sled::Batch::default();
        batch.insert(key_bytes, value_bytes.as_ref());
        self.tree.apply_batch(batch)?;

        // Batch secondary key inserts
        if !secondary_keys.is_empty() {
            let mut sec_batch = sled::Batch::default();
            for sec_key in secondary_keys.values() {
                let composite_key = self.build_composite_key(sec_key, &primary_key)?;
                sec_batch.insert(composite_key, &[] as &[u8]);
            }
            self.secondary_tree.apply_batch(sec_batch)?;
        }

        Ok(())
    }

    /// Get a model by its primary key.
    ///
    /// Retrieves a model from the tree using its primary key. Returns `None` if no
    /// model with the given key exists.
    ///
    /// # Arguments
    ///
    /// * `key` - The primary key of the model to retrieve
    ///
    /// # Returns
    ///
    /// * `Ok(Some(model))` - Model found and deserialized successfully
    /// * `Ok(None)` - No model with this key exists
    /// * `Err(NetabaseError)` - Deserialization or I/O error
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # use netabase_store::traits::model::NetabaseModelTrait;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, PartialEq, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct User { #[primary_key] pub id: u64, pub name: String }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let users = store.open_tree::<User>();
    ///
    /// let user = User { id: 42, name: "Bob".to_string() };
    /// users.put(user.clone()).unwrap();
    ///
    /// // Get existing user
    /// let found = users.get(user.primary_key()).unwrap();
    /// assert_eq!(found, Some(user));
    ///
    /// // Get non-existent user
    /// let not_found = users.get(User { id: 999, name: "Nobody".to_string() }.primary_key()).unwrap();
    /// assert_eq!(not_found, None);
    /// ```
    pub fn get(
        &self,
        key: <M::Keys as NetabaseModelTraitKey<D>>::PrimaryKey,
    ) -> Result<Option<M>, NetabaseError> {
        let key_bytes = bincode::encode_to_vec(&key, bincode::config::standard())
            .map_err(crate::error::EncodingDecodingError::from)?;

        match self.tree.get(key_bytes)? {
            Some(ivec) => {
                let definition = D::from_ivec(&ivec)?;
                match M::try_from(definition) {
                    Ok(model) => Ok(Some(model)),
                    Err(_) => Ok(None),
                }
            }
            None => Ok(None),
        }
    }

    /// Delete a model by its primary key.
    ///
    /// Removes the model and all its secondary key indexes. Returns the deleted model
    /// if it existed, or `None` if no model with the given key was found.
    ///
    /// # Arguments
    ///
    /// * `key` - The primary key of the model to delete
    ///
    /// # Returns
    ///
    /// * `Ok(Some(model))` - Model was deleted (returns the deleted model)
    /// * `Ok(None)` - No model with this key existed
    /// * `Err(NetabaseError)` - Deserialization or I/O error
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # use netabase_store::traits::model::NetabaseModelTrait;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, PartialEq, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Article { #[primary_key] pub id: u64, pub title: String }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let articles = store.open_tree::<Article>();
    ///
    /// let article = Article { id: 1, title: "Hello".to_string() };
    /// articles.put(article.clone()).unwrap();  // Clone needed since we use article later
    ///
    /// // Delete and get the deleted model
    /// let deleted = articles.remove(article.primary_key()).unwrap();
    /// assert_eq!(deleted, Some(article.clone()));
    ///
    /// // Verify it's gone
    /// let gone = articles.get(article.primary_key()).unwrap();
    /// assert_eq!(gone, None);
    /// ```
    pub fn remove(
        &self,
        key: <M::Keys as NetabaseModelTraitKey<D>>::PrimaryKey,
    ) -> Result<Option<M>, NetabaseError> {
        let key_bytes = bincode::encode_to_vec(&key, bincode::config::standard())
            .map_err(crate::error::EncodingDecodingError::from)?;

        match self.tree.remove(key_bytes)? {
            Some(ivec) => {
                let definition = D::from_ivec(&ivec)?;
                match M::try_from(definition) {
                    Ok(model) => {
                        // Clean up secondary keys using batch
                        let secondary_keys = model.secondary_keys();
                        if !secondary_keys.is_empty() {
                            let mut sec_batch = sled::Batch::default();
                            for sec_key in secondary_keys.values() {
                                let composite_key = self.build_composite_key(sec_key, &key)?;
                                sec_batch.remove(composite_key);
                            }
                            self.secondary_tree.apply_batch(sec_batch)?;
                        }
                        Ok(Some(model))
                    }
                    Err(_) => Ok(None),
                }
            }
            None => Ok(None),
        }
    }

    /// Get the total number of models in the tree.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Counter { #[primary_key] pub id: u64 }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let counters = store.open_tree::<Counter>();
    ///
    /// assert_eq!(counters.len(), 0);
    /// counters.put(Counter { id: 1 }).unwrap();
    /// assert_eq!(counters.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.tree.len()
    }

    /// Check if the tree contains no models.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Record { #[primary_key] pub id: u64 }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let records = store.open_tree::<Record>();
    ///
    /// assert!(records.is_empty());
    /// records.put(Record { id: 1 }).unwrap();
    /// assert!(!records.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.tree.is_empty()
    }

    /// Clear all models from the tree.
    ///
    /// Removes all models and their secondary key indexes from the tree.
    /// This is more efficient than removing models one-by-one.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Temp { #[primary_key] pub id: u64 }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let temps = store.open_tree::<Temp>();
    ///
    /// temps.put(Temp { id: 1 }).unwrap();
    /// temps.put(Temp { id: 2 }).unwrap();
    /// assert_eq!(temps.len(), 2);
    ///
    /// temps.clear().unwrap();
    /// assert_eq!(temps.len(), 0);
    /// ```
    pub fn clear(&self) -> Result<(), NetabaseError> {
        self.tree.clear()?;
        Ok(())
    }

    /// Find all models matching a secondary key value.
    ///
    /// Queries the secondary key index to find all models with the given secondary key value.
    /// Multiple models can have the same secondary key value, so this returns a vector.
    ///
    /// # Performance
    ///
    /// Secondary key queries are O(m) where m is the number of matching records.
    /// Each match requires a primary key lookup to retrieve the full model.
    ///
    /// # Arguments
    ///
    /// * `secondary_key` - The secondary key variant and value to search for
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<M>)` - All models matching the secondary key (may be empty)
    /// * `Err(NetabaseError)` - I/O or deserialization error
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # use netabase_store::traits::model::NetabaseModelTrait;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, PartialEq, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Person {
    /// #         #[primary_key] pub id: u64,
    /// #         pub name: String,
    /// #         #[secondary_key] pub city: String,
    /// #         #[secondary_key] pub age: u32,
    /// #     }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let people = store.open_tree::<Person>();
    ///
    /// // Add multiple people in the same city
    /// people.put(Person { id: 1, name: "Alice".into(), city: "NYC".into(), age: 30 }).unwrap();
    /// people.put(Person { id: 2, name: "Bob".into(), city: "NYC".into(), age: 25 }).unwrap();
    /// people.put(Person { id: 3, name: "Carol".into(), city: "LA".into(), age: 30 }).unwrap();
    ///
    /// // Query by city using convenience function
    /// use app::AsPersonCity;
    /// let nyc_people = people.get_by_secondary_key("NYC".as_person_city_key()).unwrap();
    /// assert_eq!(nyc_people.len(), 2);
    ///
    /// // Query by age (another secondary key) using convenience function
    /// use app::AsPersonAge;
    /// let age_30 = people.get_by_secondary_key(30u32.as_person_age_key()).unwrap();
    /// assert_eq!(age_30.len(), 2);
    /// ```
    pub fn get_by_secondary_key(
        &self,
        secondary_key: <M::Keys as crate::traits::model::NetabaseModelTraitKey<D>>::SecondaryKey,
    ) -> Result<Vec<M>, NetabaseError>
    where
        <M::Keys as NetabaseModelTraitKey<D>>::PrimaryKey: bincode::Decode<()>,
    {
        let sec_key_bytes = bincode::encode_to_vec(&secondary_key, bincode::config::standard())
            .map_err(crate::error::EncodingDecodingError::from)?;

        let mut results = Vec::new();
        for item in self.secondary_tree.scan_prefix(&sec_key_bytes) {
            let (composite_key, _) = item?;
            // Extract primary key from composite key (skip secondary key bytes)
            let prim_key_start = sec_key_bytes.len();
            if composite_key.len() > prim_key_start {
                let (primary_key, _) = bincode::decode_from_slice::<
                    <M::Keys as NetabaseModelTraitKey<D>>::PrimaryKey,
                    _,
                >(
                    &composite_key[prim_key_start..],
                    bincode::config::standard(),
                )
                .map_err(crate::error::EncodingDecodingError::from)?;

                if let Some(model) = self.get(primary_key)? {
                    results.push(model);
                }
            }
        }

        Ok(results)
    }

    /// Iterate over all models in the tree.
    ///
    /// Returns an iterator that yields `(primary_key, model)` pairs for all models in the tree.
    /// The iteration order is determined by the underlying sled tree (lexicographically by key bytes).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// # use netabase_store::databases::sled_store::SledStore;
    /// # #[netabase_definition_module(AppDef, AppKeys)]
    /// # mod app {
    /// #     use super::*;
    /// # use netabase_store::{netabase_definition_module, NetabaseModel, netabase};
    /// #     #[derive(NetabaseModel, Clone, Debug, bincode::Encode, bincode::Decode,
    /// #              serde::Serialize, serde::Deserialize)]
    /// #     #[netabase(AppDef)]
    /// #     pub struct Item { #[primary_key] pub id: u64, pub value: String }
    /// # }
    /// # use app::*;
    /// let store = SledStore::<AppDef>::temp().unwrap();
    /// let items = store.open_tree::<Item>();
    ///
    /// items.put(Item { id: 1, value: "first".into() }).unwrap();
    /// items.put(Item { id: 2, value: "second".into() }).unwrap();
    ///
    /// // Iterate over all items
    /// for result in items.iter() {
    ///     let (key, item) = result.unwrap();
    ///     println!("Item {}: {}", key.0, item.value);
    /// }
    /// ```
    pub fn iter(&self) -> SledIter<D, M> {
        SledIter {
            inner: self.tree.iter(),
            _phantom_d: PhantomData,
            _phantom_m: PhantomData,
        }
    }

    /// Build a composite key from secondary key + primary key
    pub(crate) fn build_composite_key(
        &self,
        secondary_key: &<M::Keys as NetabaseModelTraitKey<D>>::SecondaryKey,
        primary_key: &<M::Keys as NetabaseModelTraitKey<D>>::PrimaryKey,
    ) -> Result<Vec<u8>, NetabaseError> {
        let mut composite_key = bincode::encode_to_vec(secondary_key, bincode::config::standard())
            .map_err(crate::error::EncodingDecodingError::from)?;
        let prim_key_bytes = bincode::encode_to_vec(primary_key, bincode::config::standard())
            .map_err(crate::error::EncodingDecodingError::from)?;

        // Append primary key to secondary key to create composite key
        composite_key.extend_from_slice(&prim_key_bytes);
        Ok(composite_key)
    }
}