update # libsql-orm
A powerful, async-first ORM for Turso Database with first-class support for Cloudflare Workers and WebAssembly environments.
⚠️ Disclaimer: This library is in early development and not fully tested in production environments. Use at your own risk. Please report any issues you encounter and feel free to contribute via pull requests - we're happy to address them and welcome community contributions!
✨ Features
- 🚀 Cloudflare Workers Ready - Built specifically for edge computing environments
- 🔄 Async/Await Support - Fully async API with excellent performance
- 🎯 Type-Safe - Leverages Rust's type system for compile-time safety
- 📊 Rich Query Builder - Fluent API for complex queries
- 🔍 Advanced Filtering - Search, pagination, sorting, and aggregations
- 🎨 Derive Macros - Automatic model generation with
#[derive(Model)] - 📦 Bulk Operations - Efficient batch inserts, updates, and deletes
- 🌐 WASM Compatible - Optimized for WebAssembly targets
- 🔧 Custom Table Names -
#[table_name("custom")]attribute support - ✅ Boolean Type Safety - Automatic SQLite integer ↔ Rust boolean conversion
- 🏷️ Column Attributes -
#[orm_column(...)]for column customization - 🔄 Upsert Operations - Smart create_or_update and upsert methods
- 🔌 MCP Support - Model Context Protocol integration for AI-powered database interactions
🚀 Quick Start
Add this to your Cargo.toml:
[]
= { = "0.2.4", = ["cloudflare"] }
= { = "1.0", = ["derive"] }
= { = "0.4", = ["serde"] }
# Required for Cloudflare Workers support - use git version of libsql with newer worker dependency
[]
= { = "https://github.com/ayonsaha2011/libsql", = ["cloudflare"] }
Why the Git Patch?
For Cloudflare Workers compatibility, you need to use a patched version of libsql that includes:
- Updated
workerdependency compatibility - Enhanced WASM support for edge environments
- Cloudflare-specific optimizations
The patch ensures seamless integration with Cloudflare Workers' runtime environment.
Basic Usage
use ;
use ;
use ;
// Custom table name (optional)
// In your async function
async
Cloudflare Workers Integration
First, ensure your Cargo.toml includes the necessary features and patches:
[]
= { = "0.2.4", = ["cloudflare"] }
= ">=0.7.0"
= { = "1.0", = ["derive"] }
= { = "0.4", = ["serde"] }
# Use git version of libsql with newer worker dependency
[]
= { = "https://github.com/ayonsaha2011/libsql", = ["cloudflare"] }
Then in your worker code:
use *;
use ;
use ;
use ;
// Custom table name
async
Advanced Cloudflare Workers with Axum Integration
For more complex applications, you can integrate libsql-orm with Axum for better routing and state management.
Key Requirements:
- 🏗️ Library crate: Use
crate-type = ["cdylib"]for Cloudflare Workers - 🔧 Worker features: Enable
httpandaxumfeatures for the worker crate - 🎯 Axum config: Use
default-features = falsefor WASM compatibility - 🔗 Tower service: Required for Axum routing integration
Setup:
[]
= "my-cloudflare-app"
= "0.1.0"
= "2021"
[]
= ["cdylib"]
[]
= { = "0.7", = ['http', 'axum'] }
= { = "0.7", = ['http'] }
= { = "0.8", = false, = ["json", "macros"] }
= "0.3.3"
= { = "0.2.4", = ["cloudflare"] }
= { = "1.0", = ["derive"] }
= "1.0"
= { = "0.4", = ["serde"] }
= "0.1"
# Use git version of libsql with newer worker dependency
[]
= { = "https://github.com/ayonsaha2011/libsql", = ["cloudflare"] }
use ;
use Service;
use *;
use Result;
use ;
use ;
use ;
use Arc;
// Application state
// User model
// Request/Response DTOs
// Route handlers
async
async
async
async
async
async
// Create router with all routes
// Main Cloudflare Workers handler
async
This example demonstrates:
- 🏗️ Clean Architecture: Separating models, DTOs, and handlers
- 🔄 State Management: Using Axum's state system for database sharing
- 🛣️ RESTful Routing: Complete CRUD operations with proper HTTP methods
- 📊 Error Handling: Comprehensive error handling with tuple returns
- 🎯 Type Safety: Strong typing with request/response DTOs
- 🚀 Performance: Efficient database connection sharing with
AppState::new() - 📝 Logging: Built-in
console_log!macro for debugging - 🔍 Advanced Queries: Filtering and conditional operations
- ⚡ Worker Integration:
#[worker::send]attributes for optimal performance
API Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /users |
Get all users |
| POST | /users |
Create a new user |
| GET | /users/:id |
Get user by ID |
| PUT | /users/:id |
Update user |
| DELETE | /users/:id |
Delete user |
| GET | /users/active |
Get all active users |
🚀 Deployment
To deploy this Cloudflare Workers application, you'll need a wrangler.toml configuration:
= "my-cloudflare-app"
= "build/worker/shim.mjs"
= "2023-05-18"
[]
= "your-database-url"
= "your-auth-token"
[[]]
= "CompiledWasm"
= ["**/*.wasm"]
= true
Deploy commands:
# Install dependencies
# Deploy to Cloudflare Workers
📚 Advanced Features
Custom Table Names
Use the #[table_name("custom_name")] attribute to specify custom table names:
// Custom table name
// Default table name would be "user" (struct name lowercase)
// With attribute, table name is "user_accounts"
assert_eq!;
Benefits:
- 🏷️ Legacy Integration - Map to existing database tables
- 🎯 Naming Control - Override default naming conventions
- 📁 Multi-tenant - Use prefixes like
tenant_users - 🔄 Migration Friendly - Rename tables without changing structs
Boolean Type Safety
libsql-orm automatically handles boolean conversion between SQLite and Rust:
use ;
use ;
// All boolean operations work seamlessly
let user = find_where.await?;
// JSON serialization works correctly
let json = to_string?; // ✅ Booleans as true/false
let deserialized: User = from_str?; // ✅ No errors
Key Features:
- ✅ Automatic Detection - Boolean fields identified at compile time
- ✅ Zero Configuration - Works with any boolean field name
- ✅ Type Safety - No runtime errors or invalid conversions
- ✅ Performance - Conversion logic generated at compile time
- ✅ JSON Compatible - Seamless serialization/deserialization
Column Attributes
Customize column properties with #[orm_column(...)]:
use Model;
use ;
Query Builder
use ;
// Complex query with filtering and pagination
let query = new
.select
.r#where
.order_by
.limit
.offset;
let = query.build?;
Pagination
use ;
let pagination = new; // page 1, 10 items per page
let result: = find_paginated.await?;
// Access pagination info
// Page: result.pagination.page
// Total pages: result.pagination.total_pages.unwrap_or(0)
// Total items: result.pagination.total.unwrap_or(0)
for user in result.data
Bulk Operations
// Bulk insert
let users = vec!;
let saved_users = bulk_create.await?;
// Bulk delete
let ids_to_delete = vec!;
let deleted_count = bulk_delete.await?;
Aggregations
use Aggregate;
// Count users
let total_users = count.await?;
// Average age
let avg_age = aggregate.await?;
// Count with filter
let active_users_count = count_where.await?;
Search
use ;
let search = new;
// Optional pagination
let pagination = new;
let results = search.await?;
Upsert Operations
libsql-orm provides intelligent create-or-update operations:
use ;
use ;
// Create or update based on primary key
let mut user = User ;
// Automatically decides whether to create or update
let saved_user = user.create_or_update.await?;
// Upsert based on unique constraints (e.g., email)
let user = User ;
// Will update existing record with this email, or create new if not found
let saved_user = user.upsert.await?;
// Multiple unique constraints
let saved_user = user.upsert.await?;
🔌 MCP (Model Context Protocol) Support
libsql-orm provides comprehensive MCP server integration for AI-powered database interactions. The MCP protocol enables seamless communication between AI assistants and your Turso database.
MCP Features
- 40+ Tools: Complete CRUD operations, queries, migrations, and more
- Type-Safe Queries: Automatic validation and type checking
- Advanced Filtering: Complex AND/OR/NOT filter combinations
- Pagination Support: Both offset-based and cursor-based pagination
- Migration Management: Create, execute, and track database migrations
- Bulk Operations: Efficient batch processing
- Search Capabilities: Multi-column text search
- Aggregations: COUNT, SUM, AVG, MIN, MAX operations
MCP Resources
The MCP server exposes:
- Database connection resources
- Model resources (table-based)
- Query builder resources
- Migration tracking resources
Quick MCP Example
📖 Complete MCP Documentation - Comprehensive guide with all 40+ tools, examples, and best practices
🏗️ Architecture
WASM Compatibility
libsql-orm is built from the ground up for WebAssembly environments:
- Uses
libsqlWASM bindings for database connectivity - Optimized async runtime for edge computing
- Minimal binary size with selective feature compilation
- Compatible with Cloudflare Workers, Deno Deploy, and other edge platforms
🔗 Ecosystem
libsql-orm works great with:
- Turso Database - The database platform
- Turso - Managed Turso hosting
- Cloudflare Workers - Edge computing platform
- worker-rs - Cloudflare Workers Rust SDK
🤝 Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
☕ Support the Project
If you find this library helpful and would like to support its development, consider making a donation:
💰 Donation Options
- GitHub Sponsors: Sponsor on GitHub
- Buy Me a Coffee: Buy me a coffee
- PayPal: PayPal Donation
🎯 What Your Support Helps With
- 🚀 Feature Development - Building new capabilities and improvements
- 🐛 Bug Fixes - Maintaining stability and reliability
- 📚 Documentation - Creating better guides and examples
- 🔧 Maintenance - Keeping the library up-to-date with dependencies
- ☁️ Infrastructure - Hosting costs for CI/CD and testing
Every contribution, no matter the size, helps make this library better for everyone! 🙏
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Turso team for the excellent database platform
- Cloudflare for the Workers platform
- Rust community for the amazing ecosystem
Need help?