offline_first_core 0.5.0

High-performance LMDB-based local storage library optimized for FFI integration with Flutter and cross-platform applications
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
# ๐Ÿ—ƒ๏ธ Offline First Core

[![Crates.io](https://img.shields.io/crates/v/offline_first_core.svg)](https://crates.io/crates/offline_first_core)
[![Documentation](https://docs.rs/offline_first_core/badge.svg)](https://docs.rs/offline_first_core)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

High-performance LMDB-based local storage library optimized for FFI integration with Flutter and cross-platform applications.

## โœจ Features

- ๐Ÿš€ **LMDB-powered** - Battle-tested database engine used by Bitcoin Core and OpenLDAP
- ๐Ÿ“ฑ **Flutter-ready** - Hot restart compatible FFI interface
- โšก **High performance** - Zero-copy reads and ACID transactions
- ๐Ÿ”„ **Cross-platform** - Works on iOS, Android, Windows, macOS, and Linux
- ๐Ÿ“ฆ **Simple API** - Only 9 functions to learn

## ๐Ÿš€ Quick Start

### Flutter Integration

```dart
import 'dart:ffi';
import 'dart:convert';

// 1. Load the native library
final dylib = DynamicLibrary.open('liboffline_first_core.so');

// 2. Define FFI functions
typedef CreateDbNative = Pointer Function(Pointer<Utf8>);
typedef CreateDb = Pointer Function(Pointer<Utf8>);
final createDb = dylib.lookupFunction<CreateDbNative, CreateDb>('create_db');

// 3. Use the database
final dbPointer = createDb("my_app_database".toNativeUtf8());

final jsonData = jsonEncode({
  "id": "user_123",
  "hash": "content_hash",
  "data": {"name": "John Doe", "email": "john@example.com"}
});

final result = pushData(dbPointer, jsonData.toNativeUtf8());
```

### Rust Direct Usage

```rust
use offline_first_core::{AppDbState, LocalDbModel};
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize database
    let db = AppDbState::init("my_database".to_string())?;

    // Create and store data
    let user = LocalDbModel {
        id: "user_123".to_string(),
        hash: "content_hash".to_string(),
        data: json!({"name": "John Doe", "email": "john@example.com"}),
    };

    db.push(user)?;

    // Retrieve data
    let user = db.get_by_id("user_123")?.unwrap();
    println!("User: {}", user.data["name"]);

    Ok(())
}
```

## ๐Ÿ“š API Reference

### Core Functions

| Function | Rust | FFI | Description |
|----------|------|-----|-------------|
| **Initialize** | `AppDbState::init(name)` | `create_db(name)` | Create or open database |
| **Insert** | `db.push(model)` | `push_data(db, json)` | Add new record |
| **Get by ID** | `db.get_by_id(id)` | `get_by_id(db, id)` | Retrieve specific record |
| **Get All** | `db.get()` | `get_all(db)` | Retrieve all records |
| **Update** | `db.update(model)` | `update_data(db, json)` | Update existing record |
| **Delete** | `db.delete_by_id(id)` | `delete_by_id(db, id)` | Remove record |
| **Clear** | `db.clear_all_records()` | `clear_all_records(db)` | Remove all records |
| **Reset** | `db.reset_database(name)` | `reset_database(db, name)` | Reset database |
| **Close** | `db.close_database()` | `close_database(db)` | Close connection |

### Data Model

```rust
pub struct LocalDbModel {
    pub id: String,      // Unique identifier (cannot be empty)
    pub hash: String,    // Content hash for versioning
    pub data: JsonValue, // Your JSON data
}
```

## ๐ŸŽฏ Usage Examples

### 1. User Preferences

```rust
use offline_first_core::{AppDbState, LocalDbModel};
use serde_json::json;

fn save_preferences() -> Result<(), Box<dyn std::error::Error>> {
    let db = AppDbState::init("user_settings".to_string())?;
    
    let preferences = LocalDbModel {
        id: "app_preferences".to_string(),
        hash: "v1.0".to_string(),
        data: json!({
            "theme": "dark",
            "language": "en",
            "notifications": true
        }),
    };
    
    db.push(preferences)?;
    Ok(())
}
```

### 2. Shopping Cart

```rust
fn add_to_cart(product_id: &str, quantity: i32) -> Result<(), Box<dyn std::error::Error>> {
    let db = AppDbState::init("shopping_cart".to_string())?;
    
    let item = LocalDbModel {
        id: product_id.to_string(),
        hash: format!("cart_{}", chrono::Utc::now().timestamp()),
        data: json!({
            "product_id": product_id,
            "quantity": quantity,
            "price": 29.99
        }),
    };
    
    db.push(item)?;
    Ok(())
}
```

### 3. Offline Cache

```rust
fn cache_article(article_id: &str, content: &str) -> Result<(), Box<dyn std::error::Error>> {
    let db = AppDbState::init("article_cache".to_string())?;
    
    let article = LocalDbModel {
        id: article_id.to_string(),
        hash: format!("article_{}", md5::compute(content)),
        data: json!({
            "title": "Article Title",
            "content": content,
            "cached_at": chrono::Utc::now().to_rfc3339()
        }),
    };
    
    db.push(article)?;
    Ok(())
}
```

## ๐Ÿ”ง Advanced Usage

### Error Handling

```rust
use offline_first_core::{AppDbState, AppResponse};

match db.push(model) {
    Ok(_) => println!("โœ… Success"),
    Err(AppResponse::DatabaseError(msg)) => eprintln!("๐Ÿ’พ Database error: {}", msg),
    Err(AppResponse::SerializationError(msg)) => eprintln!("๐Ÿ“ JSON error: {}", msg),
    Err(AppResponse::NotFound(msg)) => eprintln!("๐Ÿ” Not found: {}", msg),
    Err(other) => eprintln!("๐Ÿ”ฅ Other error: {}", other),
}
```

### Batch Operations

```rust
fn bulk_insert(records: Vec<LocalDbModel>) -> Result<usize, Box<dyn std::error::Error>> {
    let db = AppDbState::init("bulk_data".to_string())?;
    let mut success_count = 0;
    
    for model in records {
        if db.push(model).is_ok() {
            success_count += 1;
        }
    }
    
    Ok(success_count)
}
```

### Hot Restart (Flutter)

```dart
class DatabaseManager {
  static Pointer? _dbPointer;
  
  static void initDatabase() {
    _dbPointer = createDb("my_app_db".toNativeUtf8());
  }
  
  static void closeDatabase() {
    if (_dbPointer != null) {
      closeDatabase(_dbPointer!);
      _dbPointer = null;
    }
  }
}
```

## ๐Ÿ› ๏ธ Setup

### Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
offline_first_core = "0.3.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
```

For FFI projects:

```toml
[lib]
name = "my_storage_lib"
crate-type = ["staticlib", "cdylib"]
```

### Building

```bash
# Debug build
cargo build

# Release build
cargo build --release

# Cross-platform builds
cargo build --target aarch64-apple-ios --release        # iOS
cargo build --target aarch64-linux-android --release    # Android
cargo build --target x86_64-pc-windows-msvc --release   # Windows
```

## โš ๏ธ Important Notes

### LMDB Limitations

```rust
// โŒ Empty IDs not supported
let invalid = LocalDbModel {
    id: "".to_string(), // Will fail!
    // ...
};

// โœ… Always use non-empty IDs
let valid = LocalDbModel {
    id: "user_123".to_string(), // Good!
    // ...
};
```

### Memory Safety (FFI)

```c
// โœ… Always check null pointers
void* db = create_db("my_db");
if (db == NULL) {
    // Handle error
    return;
}

// โœ… Free returned strings
const char* result = get_by_id(db, "user_1");
if (result != NULL) {
    // Use result...
    free((void*)result); // Important!
}
```

### Performance Tips

```rust
// โœ… DO: Reuse connections
let db = AppDbState::init("my_db".to_string())?;
for i in 0..1000 {
    db.push(create_model(i))?; // Efficient
}

// โŒ DON'T: Create new connections
for i in 0..1000 {
    let db = AppDbState::init("my_db".to_string())?; // Slow!
    db.push(create_model(i))?;
}
```

## ๐Ÿงช Testing

```rust
#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_basic_crud() {
        let db = AppDbState::init("test_db".to_string()).unwrap();
        
        let model = LocalDbModel {
            id: "test_1".to_string(),
            hash: "test_hash".to_string(),
            data: json!({"name": "Test User"}),
        };
        
        // Insert
        assert!(db.push(model).is_ok());
        
        // Read
        let retrieved = db.get_by_id("test_1").unwrap();
        assert!(retrieved.is_some());
        
        // Update
        let mut updated = retrieved.unwrap();
        updated.data["name"] = json!("Updated User");
        assert!(db.update(updated).is_ok());
        
        // Delete
        assert!(db.delete_by_id("test_1").unwrap());
    }
}
```

## ๐Ÿ“ฆ Integration Examples

### Flutter Plugin

```dart
// pubspec.yaml
dependencies:
  ffi: ^2.0.0

// lib/database.dart
import 'dart:ffi';
import 'dart:io';

class NativeDatabase {
  late DynamicLibrary _lib;
  
  NativeDatabase() {
    if (Platform.isAndroid) {
      _lib = DynamicLibrary.open('liboffline_first_core.so');
    } else if (Platform.isIOS) {
      _lib = DynamicLibrary.process();
    }
  }
  
  // Define your FFI functions here...
}
```

### React Native

```javascript
// Install react-native-ffi
npm install react-native-ffi

// Use the library
import { NativeModules } from 'react-native';
const { OfflineFirstCore } = NativeModules;

async function saveData(id, data) {
  const result = await OfflineFirstCore.pushData(id, JSON.stringify(data));
  return JSON.parse(result);
}
```

## ๐Ÿ“‹ Changelog

### v0.5.0 - TEST
- Update documentation

### v0.4.0 - TEST
- Improve test cases

### v0.3.0 - LMDB Migration
- โœจ Migrated from redb to LMDB
- โœจ Added `close_database()` function
- ๐Ÿ› Fixed Flutter hot restart issues
- ๐Ÿ”ง Improved error handling
- ๐Ÿ“š Added comprehensive test suite (60+ tests)

### v0.2.0 - Feature Expansion
- โœจ Added `clear_all_records()` and `reset_database()`
- ๐Ÿ”ง Improved error handling
- ๐Ÿ›ก๏ธ Enhanced FFI safety

### v0.1.0 - Initial Release
- โœจ Basic CRUD operations
- ๐Ÿ”Œ FFI interface for cross-platform integration

## ๐Ÿค Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

<div align="center">

**Made with โค๏ธ for developers who need reliable offline storage**

[โญ Star on GitHub](https://github.com/JhonaCodes/offline_first_core) โ€ข [๐Ÿ“ฆ View on Crates.io](https://crates.io/crates/offline_first_core) โ€ข [๐Ÿ“– Read the Docs](https://docs.rs/offline_first_core)

</div>