stoolap_flutter 2.0.0
stoolap_flutter: ^2.0.0 copied to clipboard
High-performance, pure Rust embedded SQL database for Flutter with native Vector Search, MVCC transactions, and reactive Streams.
Stoolap Flutter SDK #
The high-performance SQL database that ships with your app.
What's New in 2.0.0 ๐ #
- Prepared Statements: Parse once, execute many times with zero parse overhead.
- Named Parameters: Use
:namesyntax for readable, maintainable queries. - Query Timeouts: Cancel queries that exceed time limits.
- Snapshot Isolation: Full MVCC transaction isolation levels.
- Semantic Search: Built-in EMBED() function for AI-powered search โ no external APIs.
- Semantic Cache: Query result caching with stats and control.
- Performance: Fixed redundant FFI matching and wrapped batch execution in transactions.
- Full API Parity: 100% coverage of the Stoolap Rust API v0.4.0.
What is Stoolap? #
Stoolap is a modern embedded SQL database that provides full ACID transactions with MVCC, a sophisticated cost-based query optimizer, and features that rival established databases like PostgreSQL and DuckDB. Built entirely in Rust with minimal unsafe code (only for FFI and performance-critical hot paths), Stoolap features multiple index types (B-tree, Hash, Bitmap, HNSW), native vector search with semantic search support, parallel query execution, and comprehensive SQL support including window functions, CTEs, and temporal queries.
Official Reference: https://stoolap.io/ Pub.dev: https://pub.dev/packages/stoolap_flutter
Features ๐ฆ #
- ๐ฆ Pure Rust Core: Memory-safe and lightning-fast database engine.
- ๐ Native Vector Search:
VECTORtype and HNSW indexes for sub-linear semantic search. - ๐ง Built-in Semantic Search:
EMBED()function converts text to vectors inside Rust โ no external APIs needed. - โก Parallel Execution: Automatically parallelizes joins, sorts, and aggregations across all CPU cores.
- ๐ก๏ธ MVCC Transactions: Full ACID compliance with snapshot isolation. Readers never block writers.
- ๐ฐ๏ธ Time-Travel Queries: Query your data exactly as it existed in the past using the
AS OFsyntax. - ๐ Reactive API: Built-in support for "Live Queries" using Dart Streams.
- ๐๏ธ Advanced SQL: Supports CTEs (including Recursive), Window Functions, and standard SQL joins.
- ๐ฑ Mobile Optimized: Optimized with SIMD for ARM64 (M1/M2 and modern Android chips).
- ๐ Prepared Statements: Parse SQL once, execute many times with zero parse overhead.
- ๐ท๏ธ Named Parameters: Use
:namesyntax for readable, maintainable queries. - โฑ๏ธ Query Timeouts: Cancel queries that exceed time limits.
- ๐ Isolation Levels: Choose between Read Committed and Snapshot isolation.
Quick Start ๐ #
1. Installation #
Add stoolap_flutter to your pubspec.yaml:
dependencies:
stoolap_flutter: ^2.0.0
2. Initialization #
import 'package:stoolap_flutter/stoolap_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await StoolapDatabase.init();
runApp(const MyApp());
}
3. Basic Usage #
final db = StoolapDatabase();
await db.open('my_app_data.db');
// Execute DDL
await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
// Insert with positional parameters
await db.execute('INSERT INTO users (name, email) VALUES (?, ?)', params: ['Alice', 'alice@example.com']);
// Insert with named parameters
await db.executeNamed(
'INSERT INTO users (name, email) VALUES (:name, :email)',
namedParams: {'name': 'Bob', 'email': 'bob@example.com'},
);
// Query
final rows = await db.query('SELECT * FROM users');
for (var row in rows) {
print('User: ${row.values[1]}');
}
Advanced Features ๐ ๏ธ #
Prepared Statements #
Parse SQL once and execute many times with zero parse overhead:
final stmt = await db.prepare('INSERT INTO logs (level, message) VALUES (?, ?)');
// Execute many times โ no parsing, no cache lookup
for (var entry in logEntries) {
await stmt.execute(params: [entry.level, entry.message]);
}
Named Parameters #
Use readable :name placeholders:
await db.executeNamed(
'INSERT INTO users (name, email, age) VALUES (:name, :email, :age)',
namedParams: {'name': 'Charlie', 'email': 'charlie@example.com', 'age': 25},
);
Query Timeouts #
Cancel queries that exceed time limits:
final results = await db.queryWithTimeout(
'SELECT * FROM large_table WHERE complex_condition',
timeout: Duration(seconds: 5),
);
Snapshot Isolation #
Choose between isolation levels:
// Read Committed (default) โ each statement sees committed data
await db.begin();
// Snapshot โ entire transaction sees consistent snapshot from BEGIN
await db.begin(isolation: 'snapshot');
await db.execute('SELECT * FROM accounts'); // Sees data as of BEGIN
await db.commit();
Semantic Vector Search #
Stoolap handles embeddings natively with built-in EMBED():
// Create table with vector support
await db.execute('''
CREATE TABLE items (
id INTEGER PRIMARY KEY,
description TEXT,
embedding VECTOR(384)
)
''');
// Insert with auto-generated embedding
await db.execute(
"INSERT INTO items (description, embedding) VALUES (?, EMBED(?))",
params: ['high-performance database', 'high-performance database'],
);
// Semantic search using the convenience method
final results = await db.semanticSearch(
table: 'items',
embeddingColumn: 'embedding',
query: 'fast SQL engine',
limit: 5,
);
Reactive Live Queries #
StreamBuilder<List<StoolapRow>>(
stream: db.watch('SELECT * FROM users ORDER BY id DESC'),
builder: (context, snapshot) {
if (!snapshot.hasData) return const CircularProgressIndicator();
final users = snapshot.data!;
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) => ListTile(
title: Text(users[index].values[1].toString()),
),
);
},
);
Table Utilities #
// Check if a table exists
if (await db.tableExists('users')) {
// Table exists
}
// Create a point-in-time snapshot
await db.createSnapshot();
// Get engine version
final version = await StoolapDatabase.version();
// Semantic cache stats
final stats = await db.semanticCacheStats();
await db.clearSemanticCache();
Performance & Benchmarks โก #
Stoolap is engineered for high-performance mobile and edge workloads. Unlike single-threaded databases, it leverages Rayon for automatic query parallelization and SIMD (NEON/AVX) for lightning-fast vector math.
Real-World Performance (vs SQLite & DuckDB) #
Official benchmarks performed on Apple M1 Pro (16GB RAM, macOS 15) using identical 10k row workloads with Stoolap v0.4.0, SQLite 3.45.0, and DuckDB 0.10.0. Source: Stoolap Official Benchmarks.
| Operation | Stoolap | SQLite | DuckDB | Speedup (vs SQLite) |
|---|---|---|---|---|
| COUNT DISTINCT | 0.37 ยตs | 105.98 ยตs | 219.91 ยตs | 286x |
| Subquery Compare | 5.52 ยตs | 1424.07 ยตs | 293.51 ยตs | 258x |
| Aggregation (GROUP BY) | 48.81 ยตs | 1403.39 ยตs | 104.32 ยตs | 29x |
| SELECT by ID | 0.12 ยตs | 0.21 ยตs | 145.55 ยตs | 1.7x |
| Vector Search (k-NN) | 4ms | N/A | N/A | Native |
Mobile Performance Comparison #
| Feature | Stoolap (Rust) | SQLite (C) | Hive (Dart) | Isar (Dart) |
|---|---|---|---|---|
| Parallelism | Automatic (Multi-core) | Single-threaded | Single-threaded | Single-threaded |
| Concurrency | MVCC (Readers don't block) | Lock-based | Lock-based | Lock-based |
| Vector Index | Native HNSW | โ | โ | โ |
| Optimizer | Cost-Based (PostgreSQL-style) | Rule-Based | โ | โ |
| Prepared Statements | Parse-once, execute-many | โ | โ | โ |
| Named Parameters | :name syntax | โ | โ | โ |
| Reactive Queries | Built-in Streams | โ | โ | โ |
| Semantic Search | Built-in EMBED() | โ | โ | โ |
Why is Stoolap faster? #
- Pure Rust Performance: Compiled with LTO and
opt-level = 3for mobile ARM64. - Snapshot Isolation (MVCC): High-throughput concurrent reads and writes without contention.
- Adaptive Query Execution: The optimizer learns from actual data distributions to choose the fastest plan.
- Hardware Acceleration: Direct use of ARM NEON instructions for vector distance metrics.
- Batch Transaction Wrapping: Multiple statements execute in a single transaction for minimal overhead.
- Prepared Statement Caching: Parse SQL once, execute plan with zero parse-lookup cost.
Connection String Options #
Configure your database with Stoolap connection strings:
// File-based with options
await db.open('file:///data/app.db?sync=full&checkpoint_interval=60');
// In-memory (unique instance)
await db.open(':memory:');
// Named in-memory (shared engine)
await db.open('memory://mydb');
| Parameter | Default | Description |
|---|---|---|
sync |
normal |
Sync mode: none, normal, full |
checkpoint_interval |
60 |
Seconds between checkpoint cycles |
wal_compression |
on |
LZ4 compression for WAL entries |
compression |
โ | Sets both wal_compression and volume_compression |
target_volume_rows |
1048576 |
Target rows per cold volume |
Documentation ๐ #
- ๐ฆ Rust Engine Docs โ Full SQL reference and architecture details.
- ๐ฏ Vector Search Guide โ Learn how to build semantic search.
- ๐ง Semantic Search Guide โ Built-in EMBED() function.
- ๐ค Contributing โ Help us build the future of mobile databases.
Join our community ๐ค #
We're building the most powerful embedded database for Flutter. Join us on GitHub to report issues, suggest features, or contribute code.
License #
Licensed under the Apache License, Version 2.0. See LICENSE for details.