dart_db 0.1.0 copy "dart_db: ^0.1.0" to clipboard
dart_db: ^0.1.0 copied to clipboard

High-performance embedded key-value database for pure Dart backend applications. Built on LMDB with Rust FFI for persistence.

example/dart_db_example.dart

import 'package:dart_db/dart_db.dart';

void main() async {
  print('=== DartDB Example ===\n');

  // Initialize the database
  print('Opening database...');
  final db = await DartDB.open('example_database');

  try {
    // Basic operations
    print('\n--- Basic Operations ---');
    
    // Store different types of data
    await db.set('string_key', 'Hello, DartDB!');
    await db.set('number_key', 42);
    await db.set('boolean_key', true);
    await db.set('list_key', [1, 2, 3, 'mixed', true]);
    await db.set('map_key', {
      'name': 'John Doe',
      'age': 30,
      'email': 'john@example.com',
      'preferences': {
        'theme': 'dark',
        'notifications': true,
      },
    });

    // Retrieve data
    final stringValue = await db.get('string_key');
    final numberValue = await db.get<int>('number_key');
    final boolValue = await db.get<bool>('boolean_key');
    final listValue = await db.get<List>('list_key');
    final mapValue = await db.get<Map>('map_key');

    print('String: $stringValue');
    print('Number: $numberValue');
    print('Boolean: $boolValue');
    print('List: $listValue');
    print('Map: $mapValue');

    // Check if key exists
    final exists = await db.exists('string_key');
    print('Key "string_key" exists: $exists');

    // Get with default value
    final missingValue = await db.get('missing_key', defaultValue: 'default');
    print('Missing key with default: $missingValue');

    // Get all keys
    final allKeys = await db.keys();
    print('All keys: $allKeys');

    // Batch operations
    print('\n--- Batch Operations ---');
    
    await db.setMultiple({
      'batch_1': 'First batch item',
      'batch_2': 'Second batch item',
      'batch_3': 'Third batch item',
    });

    final batchValues = await db.getMultiple(['batch_1', 'batch_2', 'batch_3']);
    print('Batch values: $batchValues');

    // Advanced operations
    print('\n--- Advanced Operations ---');
    
    // Counter operations
    await db.set('counter', 10);
    await db.increment('counter', by: 5);
    print('Counter after increment: ${await db.get<int>("counter")}');
    
    await db.decrement('counter', by: 3);
    print('Counter after decrement: ${await db.get<int>("counter")}');

    // TTL operations
    print('\n--- TTL Operations ---');
    await db.setWithTTL('temp_key', 'This will expire', Duration(seconds: 2));
    print('Temp value: ${await db.get("temp_key")}');
    
    print('Waiting 3 seconds for TTL expiration...');
    await Future.delayed(Duration(seconds: 3));
    
    final expiredValue = await db.get('temp_key');
    print('Temp value after expiration: $expiredValue');

    // Transactions
    print('\n--- Transactions ---');
    
    await db.transaction((txn) async {
      await txn.set('account_a', 1000);
      await txn.set('account_b', 500);
      
      // Simulate money transfer
      final balanceA = await txn.get<int>('account_a');
      final balanceB = await txn.get<int>('account_b');
      
      final transferAmount = 200;
      await txn.set('account_a', balanceA - transferAmount);
      await txn.set('account_b', balanceB + transferAmount);
      
      print('Transfer of $transferAmount completed in transaction');
    });

    final finalBalanceA = await db.get<int>('account_a');
    final finalBalanceB = await db.get<int>('account_b');
    print('Account A balance: $finalBalanceA');
    print('Account B balance: $finalBalanceB');

    // Read-only transaction
    final accountSummary = await db.readTransaction((txn) async {
      final a = await txn.get<int>('account_a');
      final b = await txn.get<int>('account_b');
      return {'total': a + b, 'accounts': [a, b]};
    });
    
    print('Account summary: $accountSummary');

    // Database statistics
    print('\n--- Database Statistics ---');
    final stats = await db.stats();
    print('Database stats:');
    print('  - Total keys: ${stats.keyCount}');
    print('  - Size: ${stats.sizeBytes} bytes');
    print('  - Memory usage: ${stats.memoryUsage} bytes');

    // Pattern matching
    print('\n--- Pattern Matching ---');
    await db.set('user:1', {'name': 'Alice'});
    await db.set('user:2', {'name': 'Bob'});
    await db.set('user:3', {'name': 'Charlie'});
    await db.set('config:theme', 'dark');
    await db.set('config:language', 'en');

    final userKeys = await db.keys(pattern: 'user:*');
    print('User keys: $userKeys');
    
    final configKeys = await db.keys(pattern: 'config:*');
    print('Config keys: $configKeys');

    // Cleanup - delete some test data
    print('\n--- Cleanup ---');
    await db.deleteMultiple(['batch_1', 'batch_2', 'batch_3']);
    await db.delete('temp_key');
    
    final keysAfterCleanup = await db.keys();
    print('Keys after cleanup: $keysAfterCleanup');

  } catch (e) {
    print('Error: $e');
  } finally {
    // Always close the database
    print('\n--- Closing Database ---');
    await db.close();
    print('Database closed successfully');
  }

  print('\n=== Example Complete ===');
}
1
likes
160
points
29
downloads

Publisher

verified publisherjhonacode.com

Weekly Downloads

High-performance embedded key-value database for pure Dart backend applications. Built on LMDB with Rust FFI for persistence.

Repository (GitHub)
View/report issues

Topics

#embedded #key-value #lmdb #backend #ffi

Documentation

API reference

Funding

Consider supporting this project:

github.com

License

MIT (license)

Dependencies

ffi

More

Packages that depend on dart_db