TegDB
TegDB is a lightweight, embedded database engine with a SQL-like interface designed for simplicity, performance, and reliability. It provides ACID transactions, crash recovery, and efficient RDBMS.
Design Philosophy: TegDB prioritizes simplicity and reliability over complexity. It uses a single-threaded design to eliminate concurrency bugs, reduce memory overhead, and provide predictable performance - making it ideal for embedded systems and applications where resource efficiency matters more than parallel processing.
Key Features
🚀 Performance & Footprint
- Key->offset B+tree index; values are stored on disk, small values can be inlined to reduce IO
- Bounded cache (configurable cap) to boost hot-read hit rates
- Primary key optimized queries (O(log n) lookups)
- Streaming query processing with early LIMIT termination
- Efficient binary serialization
🔒 ACID Transactions
- Atomicity: All-or-nothing transaction execution
- Consistency: Schema validation and constraint enforcement
- Isolation: Write-through with snapshot-like behavior
- Durability: Write-ahead logging with commit markers
🛡️ Reliability
- Crash recovery from write-ahead log
- File locking prevents concurrent access corruption
- Graceful handling of partial writes and corruption
- Automatic rollback on transaction drop
- Strong durability by default: per-transaction fsync, configurable group commit
- Observability: metrics for bytes read/written, cache hits/misses, fsync counts
📦 Simple Design
- Single-threaded architecture eliminates race conditions
- Minimal dependencies (only
fs2for file locking) - Clean separation of concerns across layers
- Extensive test coverage including ACID compliance
🔌 Extension System
- PostgreSQL-inspired plugin architecture
- Built-in string functions: UPPER, LOWER, LENGTH, TRIM, SUBSTR, REPLACE, CONCAT, REVERSE
- Built-in math functions: ABS, CEIL, FLOOR, ROUND, SQRT, POW, MOD, SIGN
- Create custom scalar and aggregate functions
- Type-safe function signatures with validation
Getting Started
Quick Start (CLI + MinIO in 2–3 minutes)
This walkthrough uses released builds and the CLI tools, no code required.
- Install the CLIs
# Clone the repository
# Build both CLI tools (tg and tgstream)
# Or build individually:
# cargo build --release --bin tg
# cargo build --release --bin tgstream
# Copy binaries to PATH (or add target/release to your PATH)
# Ensure ~/.cargo/bin is on your PATH
Alternative: If you prefer installing from crates.io:
- Start MinIO locally and create a bucket
# Run MinIO
# Create a bucket using the MinIO Console at http://localhost:9001 (Login: minioadmin/minioadmin)
# In the Console: Buckets → Create Bucket → Name: tegdb-backups
- Configure AWS-compatible env vars for MinIO
- Create and query a database with the
tgCLI
# Use an absolute file URL ending with .teg
DB=file:////quickstart.teg
# Create table and insert a row
# Query
- Enable continuous cloud backup to MinIO with
tgstream
# Create config file (use absolute path - replace /path/to with your actual path)
# Start replication (best run under a supervisor/tmux)
# In another terminal, verify backup is working:
# You should see base snapshots appearing every 15 minutes
- Restore database from backup
# List available backups
# Restore to latest state
# Verify restored data
# Should show: Alice
Example restore scenario: If your original database gets corrupted or deleted, you can restore it from MinIO:
# Original database is lost/corrupted
# Restore from backup
# Continue using the restored database
Using TegDB as a Library
Add TegDB to your Cargo.toml:
[]
= "0.3.0"
Basic Usage
use Database;
Transaction Example
use Database;
SQL Support
TegDB supports a comprehensive subset of SQL:
Data Definition Language (DDL)
-- Create tables with constraints
(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL,
category TEXT
);
-- Drop tables
IF EXISTS old_table;
Data Manipulation Language (DML)
-- Insert single or multiple rows
INSERT INTO products (id, name, price) VALUES (1, 'Widget', 19.99);
INSERT INTO products (id, name, price) VALUES
(2, 'Gadget', 29.99),
(3, 'Tool', 39.99);
-- Update with conditions
UPDATE products SET price = 24.99 WHERE name = 'Widget';
-- Delete with conditions
DELETE FROM products WHERE price < 20.00;
-- Query with filtering and limits
SELECT name, price FROM products
WHERE category = 'Electronics'
LIMIT 10;
Transaction Control
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
-- or ROLLBACK;
Supported Data Types
INTEGER- 64-bit signed integersREAL- 64-bit floating point numbersTEXT- UTF-8 strings (requires length specification, e.g., TEXT(100))NULL- Null values
Extension System
TegDB provides a PostgreSQL-inspired extension system for adding custom functions. Extensions can be loaded via SQL commands (PostgreSQL-style) or programmatically via the Rust API.
Loading Extensions via SQL (PostgreSQL-style)
The recommended way to manage extensions is using SQL commands:
-- Load built-in extensions
CREATE EXTENSION tegdb_string;
CREATE EXTENSION tegdb_math;
-- Use extension functions in SQL
SELECT UPPER('hello'), SQRT(144);
-- Load custom extension from dynamic library
CREATE EXTENSION my_extension;
-- Or specify explicit path
CREATE EXTENSION my_extension WITH PATH '/path/to/libmy_extension.so';
-- Extensions persist automatically - they'll be loaded on next database open
-- Remove an extension
DROP EXTENSION my_extension;
Loading Extensions via Rust API
You can also register extensions programmatically:
use ;
let mut db = open?;
// Register built-in extensions
db.register_extension?;
db.register_extension?;
// Call functions directly
let result = db.call_function?;
assert_eq!;
let result = db.call_function?;
assert_eq!;
Available Functions
String Functions (tegdb_string):
UPPER(text)- Convert to uppercaseLOWER(text)- Convert to lowercaseLENGTH(text)- String lengthTRIM(text)/LTRIM(text)/RTRIM(text)- Trim whitespaceSUBSTR(text, start, length)- Extract substringREPLACE(text, from, to)- Replace occurrencesCONCAT(text, ...)- Concatenate strings (variadic)REVERSE(text)- Reverse string
Math Functions (tegdb_math):
ABS(number)- Absolute valueCEIL(number)/FLOOR(number)- Ceiling/floorROUND(number, decimals)- Round to decimal placesSQRT(number)- Square rootPOW(base, exponent)- PowerMOD(a, b)- ModuloSIGN(number)- Sign (-1, 0, or 1)
Creating Custom Extensions
Define custom extensions by implementing the Extension trait:
use ;
// Define a custom function
;
// Define an extension
;
// Register and use
db.register_extension?;
let result = db.call_function?;
assert_eq!;
Extension Management
Via SQL:
-- Extensions are automatically persisted and loaded on database open
-- No need to re-run CREATE EXTENSION after restarting
Via Rust API:
// List registered extensions
for in db.list_extensions
// Check if a function exists
if db.has_function
// Unregister an extension
db.unregister_extension?;
Creating Loadable Extensions
To create a dynamic library extension that can be loaded via CREATE EXTENSION:
-
Create a Rust library project:
-
Configure Cargo.toml:
[] = ["cdylib"] [] = { = "../tegdb" } # Or from crates.io -
Implement the extension:
use ; ; ; pub extern "C" -
Build and install:
# Or place in ./extensions/ relative to your database -
Use in SQL:
CREATE EXTENSION my_extension; SELECT MY_FUNCTION('hello');
For complete examples, see examples/extension_demo.rs and examples/extension_template.rs.
Performance Characteristics
Time Complexity
- Primary key lookups: O(log n)
- Range scans: O(log n + k) where k = result size
- Inserts/Updates/Deletes: O(log n)
- Schema operations: O(1) with caching
Memory Usage
- In-memory index: BTreeMap holds key -> value offset (values on disk), small values can inline
- Bounded cache: Byte-capped value/page cache for hot data
- Lazy allocation: Undo logs only allocated when needed
- Streaming queries: LIMIT processed without loading full result
Storage Format
- Fixed header: 64-byte header with magic
TEGDB\0, version (1), limits, flags - Append-only log: Fast writes after the header, no seek overhead
- Binary serialization: Compact data representation
- Key->offset layout: B+tree holds offsets; values stored in the data region, small values inline
- Automatic compaction: Reclaims space from old entries while preserving header
- Crash recovery: Replay from last commit marker
Cloud Backup & Replication (tgstream)
TegDB includes tgstream, a standalone streaming backup tool that continuously replicates your database to cloud storage (S3, MinIO, etc.), similar to Litestream for SQLite.
Features
- Incremental Replication: Tracks file offsets and uploads only committed changes
- Base Snapshots: Periodic full database snapshots for fast recovery
- Automatic Rotation Detection: Handles database compaction/rotation automatically
- Point-in-Time Recovery: Restore to any previous state using base + segments
- Retention Policies: Configurable retention for snapshots and segments
- Compression: Optional gzip compression to reduce storage costs
Installation
Install from crates.io:
# Or install both binaries:
Configuration
Create a configuration file tgstream.toml:
= "/absolute/path/to/your/database.teg"
[]
= "my-backup-bucket"
= "dbs/mydb"
= "us-east-1"
# Optional: For MinIO or custom S3-compatible storage
= "http://localhost:9000" # MinIO endpoint
= "minioadmin" # MinIO access key
= "minioadmin" # MinIO secret key
[]
= 60 # Create new base snapshot every hour
= 100 # Or after 100MB of segments
[]
= 1024 # Minimum segment size to upload
= 2000 # Wait 2 seconds before uploading
[]
= 3 # Keep last 3 base snapshots
= 107374182400 # 100GB max segments
= true # Enable compression
For AWS S3, you can omit endpoint, access_key_id, and secret_access_key and use environment variables or IAM roles instead:
Commands
# Run continuous replication
# Create a one-off snapshot
# Restore database from backup
# List available snapshots
# Prune old snapshots
How It Works
- Monitoring: Tegstream monitors your
.tegfile for new committed transactions - Segment Uploads: After each commit, new data is uploaded as incremental segments
- Base Snapshots: Periodically (every N minutes or after N MB of segments), a full snapshot is created
- State Tracking: Local state file tracks progress, file metadata, and prevents duplicate uploads
- Restore: Downloads base snapshot + all subsequent segments to reconstruct the database
The tool is designed to be run as a background service alongside your application, providing continuous off-site backup with minimal overhead.
flowchart LR
subgraph App
TG[tg CLI / App]
end
DB[(.teg file)]
TS[tgstream]
S3[(S3/MinIO Bucket)]
TG -- SQL --> DB
TS -- monitor commits --> DB
TS -- base snapshots --> S3
TS -- incremental segments --> S3
S3 -- base+segments --> Restore[tgstream restore]
Architecture Overview
TegDB implements a clean layered architecture with four distinct layers:
flowchart TB
A[Database API\nSQLite-like interface\nwith schema caching]
B[SQL Executor\nQuery optimization\n+ execution]
C[SQL Parser\nnom-based AST]
D[Storage Engine\nKV + WAL + TX]
A --> B --> C --> D
Core Components
- Storage Engine: BTreeMap-based in-memory storage with append-only log persistence
- Transaction System: Write-through transactions with undo logging and commit markers
- SQL Support: Full SQL parser and executor supporting DDL and DML operations
- Index-Organized Tables: Primary key optimization with direct key lookups
- Schema Caching: Database-level schema caching for improved performance
- Crash Recovery: WAL-based recovery using transaction commit markers
See ARCHITECTURE.md for detailed information about:
- Layer-by-layer implementation details
- Storage format and recovery mechanisms
- Memory management and performance optimizations
- Transaction system and ACID guarantees
- Query optimization and execution strategies
Advanced Usage
Engine Configuration
use Duration;
use ;
let config = EngineConfig ;
// Note: Custom config requires low-level API
Key defaults:
- Values are stored on disk; the B+tree indexes key -> value offset. Small values (<=
inline_value_threshold) stay inline. - A byte-capped value cache (
cache_size_bytes) keeps hot values in memory. - Durability defaults to per-commit
fsync; setDurabilityLevel::GroupCommitwith a non-zerogroup_commit_intervalto coalesce flushes. - Default compaction uses an absolute threshold (10 MiB), fragmentation ratio (2.0), and a minimum written delta (2 MiB) since the last compaction.
- No default hard cap on key count or disk size; set
initial_capacityandpreallocate_sizeto enforce limits in production.
Metrics (observability):
let metrics = engine.metrics;
println!;
Low-Level Engine API
For advanced use cases, you can access low-level APIs via module paths:
use ;
// Direct key-value operations (requires absolute PathBuf)
let mut engine = new?;
engine.set?;
let value = engine.get;
// Transaction control
let mut tx = engine.begin_transaction;
tx.set?;
tx.set?;
tx.commit?;
Development
Building from Source
# Standard build
# Run tests
# Run benchmarks
Testing
TegDB includes comprehensive tests covering:
- ACID transaction properties
- Crash recovery scenarios
- SQL parsing and execution
- Performance benchmarks
- Edge cases and error conditions
# Run the full native test suite
# Run with verbose output
# CI-friendly run (preserves test output)
Code Quality
Use the following commands to keep the tree clean:
# Format source code
# Run Clippy with the same settings as CI
# Run the full CI-equivalent precheck suite
Benchmarks
Run performance benchmarks against other embedded databases:
Included benchmarks compare against:
- SQLite
- sled
- redb
Design Principles
- Simplicity First: Prefer simple, understandable solutions
- Reliability: Prioritize correctness over performance optimizations
- Standard Library: Use std library when possible to minimize dependencies
- Single Threaded: Eliminate concurrency complexity and bugs
- Resource Efficient: Optimize for memory and CPU usage
Limitations
Current Limitations
- Single-threaded: No concurrent access support
- No secondary indexes: Only primary key optimization
- Limited SQL: Subset of full SQL standard
- No foreign keys: Basic constraint support only
- No joins: Single table queries only
Future Enhancements
- Secondary index support
- JOIN operation support
- More SQL features (subqueries, aggregation)
- Compression for large values
- Streaming for very large result sets
- Enhanced backup features (multi-DB support, encryption-at-rest)
License
Licensed under AGPL-3.0. See LICENSE for details.
The AGPL-3.0 ensures that any modifications to TegDB remain open source and available to the community.
Contributing
Contributions welcome! Please:
- Follow the design principles above
- Include comprehensive tests
- Update documentation for new features
- Ensure benchmarks still pass
See CONTRIBUTING.md for detailed guidelines.