This example demonstrates running SQLite databases on the Internet Computer using ic-sql-migrate with the complete Chinook music store database. It explores how ICP canisters handle complex databases with thousands of records and sophisticated queries.
This canister imports the entire Chinook database (a sample database representing a digital media store) and provides five test endpoints that demonstrate both complex read queries and intensive write operations. The example allows you to assess SQLite's capabilities when running on ICP.
The Chinook database is a sample database that represents a digital media store, including:
- Customer - Store customers with addresses and support representatives
- Employee - Store employees including sales support agents
- Invoice - Customer purchases
- InvoiceLine - Individual items within invoices
- Track - Music tracks available for purchase
- Album - Albums containing tracks
- Artist - Musical artists
- Genre - Music genres (Rock, Jazz, etc.)
- MediaType - Format of tracks (MP3, AAC, etc.)
- Playlist - Curated track collections
- PlaylistTrack - Many-to-many relationship for playlists
- 59 customers across 24 countries
- 275 artists
- 347 albums
- 3,503 tracks
- 412 invoices with 2,240 line items
- Pre-populated playlists demonstrating relationships
sqlite/
├── migrations/
│ └── 000_init.sql # Complete Chinook database schema and data
├── src/
│ ├── seeds/ # Data seeding modules
│ │ ├── mod.rs # Auto-generated module file
│ │ ├── seed_001_test.rs # First seed file
│ │ └── seed_002_more_data.rs # Second seed file
│ └── lib.rs # Canister implementation with test endpoints
├── build.rs # Embeds migrations and generates seed module
├── Cargo.toml # Dependencies and build configuration
└── sqlite.did # Candid interface definition
The canister provides five test endpoints (test1 through test5) that demonstrate various database capabilities:
- Identifies top 15 customers by total purchase amount
- Performs complex JOINs across Customer, Invoice, and Employee tables
- Returns customer details, support rep, purchase history, and spending patterns
- Calculates total spent, average invoice, and purchase date range
- Analyzes top 10 genres by revenue with track counts and artist diversity
- Identifies top 10 best-selling artists with album and track statistics
- Uses aggregation functions and GROUP BY clauses
- Demonstrates multi-table JOINs and revenue calculations
- Analyzes sales by year and country with customer metrics
- Evaluates employee performance through their customer sales
- Shows temporal data handling and geographic distribution
- Calculates averages, totals, and unique customer counts
- Creates 250 new invoices with 5-25 line items each (thousands of records)
- Implements bulk discount logic and country-specific tax calculations
- Creates customer statistics in temporary tables
- Generates audit log entries for all operations
- Demonstrates transaction handling and bulk INSERT performance
- Creates 15+ genre-specific playlists with up to 500 tracks each
- Generates year-based retrospective playlists (2009-2014)
- Simulates collaborative playlists for 30 active customers
- Creates and populates analytics tables:
TrackAnalytics- Play counts, ratings, popularity scoresPlaylistRecommendations- Relationships between playlistsPlaylistMetadata- Duration, track counts, play statistics
- Demonstrates complex CREATE TABLE, bulk INSERTs, and data analysis
Each endpoint reports instruction counts, allowing you to evaluate SQLite's performance on ICP:
- Read queries typically use 10-50 million instructions
- Write operations use 100-500 million instructions for thousands of records
- Database handles complex JOINs, subqueries, and aggregations efficiently
This example includes CanBench support for performance benchmarking and instruction usage monitoring. CanBench helps track how code changes affect the canister's computational resource consumption.
Install CanBench globally:
cargo install canbenchNavigate to the SQLite example directory:
cd examples/sqliteRun benchmarks to see current performance estimates:
canbenchTo persist benchmark results for future comparisons:
canbench --persistWhen benchmark results are persisted, subsequent runs will compare against the stored baseline, making it easy to track performance regressions or improvements.
CanBench provides detailed instruction counts for your canister operations, helping you:
- Monitor performance changes across code updates
- Identify expensive operations that may need optimization
- Ensure your canister stays within ICP's instruction limits
- Compare performance before and after optimizations
dfx start --clean --backgrounddfx deploy sqlite-exampledfx canister call sqlite-example verify_migrationsExpected output:
=== Migration Verification ===
Migrations executed: 1 / 1
Status: ✓ All migrations applied
Chinook Database Contents:
- Customers: 59
- Tracks: 3503
- Albums: 347
- Invoices: 412
dfx canister call sqlite-example verify_seedsExpected output:
=== Seed Verification ===
Seeds executed: 2 / 2
Status: ✓ All seeds applied
Seed Data Verified:
- Album 9999: Test Album from Seeds
- Album 9998: Another Test Album
# Read operations - analyze existing data
dfx canister call sqlite-example test1 # Top customers with purchase history
dfx canister call sqlite-example test2 # Genre and artist revenue analysis
dfx canister call sqlite-example test3 # Sales trends by geography and time
# Write operations - generate new data
dfx canister call sqlite-example test4 # Generate 250+ invoices with line items
dfx canister call sqlite-example test5 # Create playlists and analytics data=== Top 15 Customers Analysis (Instructions: 25432187) ===
1. ID: 6 | Helena Holý (Prague, Czech Republic) | Rep: Steve Johnson | Total: $49.62 | Invoices: 7 | Avg: $7.09 | Period: 2009-01-02 to 2013-12-05
2. ID: 26 | Richard Cunningham (Fort Worth, USA) | Rep: Steve Johnson | Total: $47.62 | Invoices: 7 | Avg: $6.80 | Period: 2009-01-08 to 2012-12-28
...
Test 4 completed: Created 250 invoices with 3750 line items ($45678.90 total revenue), 250 audit records. Instructions used: 387654321
The single migration file (000_init.sql) contains the entire Chinook database structure and data:
- 11 CREATE TABLE statements with proper foreign keys
- Thousands of INSERT statements for initial data
- Indexes for optimal query performance
The example demonstrates the seed system with two seed files in src/seeds/:
seed_001_test.rs:
use ic_sql_migrate::MigrateResult;
use ic_rusqlite::Connection;
pub fn seed(conn: &Connection) -> MigrateResult<()> {
conn.execute(
"INSERT INTO Album (AlbumId, Title, ArtistId) VALUES (9999, 'Test Album from Seeds', 1)",
[],
)?;
ic_cdk::println!("Seed 001: Inserted test album");
Ok(())
}Seeds are:
- Tracked in the
_seedstable to prevent re-execution - Run in alphabetical order by filename
Uses ic_rusqlite::with_connection() for safe database access:
with_connection(|mut conn| {
let conn: &mut Connection = &mut conn;
// Perform database operations
});Each endpoint uses ic_cdk::api::performance_counter to track instruction usage:
let start_instructions = performance_counter(0);
// ... perform operations ...
let end_instructions = performance_counter(0);
let instructions_used = end_instructions - start_instructions;To add new test endpoints:
- Create a new function with
#[query](read) or#[update](write) attribute - Use
with_connection()to access the database - Track performance with
performance_counter() - Add the endpoint to
sqlite.did
Example:
#[query]
fn test6() -> String {
let start = performance_counter(0);
let result = with_connection(|mut conn| {
// Your database operations here
});
let instructions = performance_counter(0) - start;
format!("Result: {:?}, Instructions: {}", result, instructions)
}- Check SQL syntax in the migration file
- View logs:
dfx canister logs sqlite - Ensure the database isn't corrupted
- Monitor instruction counts in responses
- Consider adding indexes for frequently queried columns
- Batch write operations in transactions
- The Chinook database is relatively small (~1MB)
- Monitor canister memory usage with
dfx canister status - Consider pagination for very large result sets
This example allows you to explore:
- SQLite's capabilities on ICP with complex queries and operations
- Performance characteristics when working with thousands of records
- SQL feature support including JOINs, subqueries, and transactions
- Database patterns familiar from traditional applications
MIT - See LICENSE file in the repository root