Intelligent SQL to NoSQL schema migration - analyzes query patterns to recommend optimal MongoDB schema design
Project description
๐งญ Schema Travels
Intelligent SQL โ MongoDB Schema Migration
"Stop guessing embed vs. reference. Let your query patterns decide."
The Problem
Migrating from PostgreSQL/MySQL to MongoDB? You'll face this question hundreds of times:
"Should I embed this data or reference it?"
Most migration tools do 1:1 table-to-collection mapping โ which completely ignores why you're moving to NoSQL in the first place.
The right answer depends on how you actually access your data. But manually analyzing thousands of queries? Nobody has time for that.
The Solution
Schema Travels analyzes your real query patterns and recommends an optimal MongoDB schema:
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Query Logs โโโโโโถโ Pattern Analysis โโโโโโถโ AI-Powered โ
โ + SQL Schema โ โ โข Hot joins โ โ Recommendationsโ
โ โ โ โข Co-access % โ โ โข EMBED โ
โ โ โ โข Write ratios โ โ โข REFERENCE โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
Result: A MongoDB schema optimized for your access patterns โ not generic "best practices."
What's New in v1.1.0
๐ Reproducible Results with Caching
Same inputs now produce the same recommendations every time:
# First run - calls Claude API
schema-travels analyze --logs-dir ./logs --schema-file ./schema.sql
# โ Cached to ~/.schema-travels/cache/
# Second run - uses cache (instant, consistent)
schema-travels analyze --logs-dir ./logs --schema-file ./schema.sql
# โ Same recommendations, no API call
# Force fresh analysis
schema-travels analyze --logs-dir ./logs --schema-file ./schema.sql --no-cache
๐ Better API Key Errors
Clear, actionable error when API key is missing:
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ ๏ธ API KEY NOT CONFIGURED โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Schema Travels requires an Anthropic API key for AI-powered โ
โ schema recommendations. โ
โ โ
โ Option 1: export ANTHROPIC_API_KEY=sk-ant-xxxxx โ
โ Option 2: echo "ANTHROPIC_API_KEY=sk-ant-xxxxx" > .env โ
โ โ
โ Get your API key at: https://console.anthropic.com/settings/keys โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
Quick Start
Installation
pip install schema-travels
Basic Usage
# Set your API key
export ANTHROPIC_API_KEY=sk-ant-xxxxx
# Analyze your database
schema-travels analyze \
--logs-dir ./postgresql-logs \
--schema-file ./schema.sql \
--target mongodb \
--output results.json
What You Get
๐ Analysis Summary
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Hot Joins (Top 5):
users โท orders : 12,847 calls, 8.3ms avg
orders โท order_items: 11,203 calls, 5.1ms avg
products โท reviews : 8,456 calls, 12.7ms avg
Recommendations:
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ Parent โ Child โ Decision โ Confidence โ
โโโโโโโโโโโโโโโผโโโโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโโโโค
โ users โ addresses โ EMBED โ 92% โ
โ orders โ order_items โ EMBED โ 87% โ
โ users โ orders โ REFERENCE โ 85% โ
โ products โ reviews โ REFERENCE โ 78% โ
โโโโโโโโโโโโโโโดโโโโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโโโโ
Why Schema Travels?
โ What Other Tools Do
SQL Table โ MongoDB Collection
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
users โ users
addresses โ addresses
orders โ orders
order_items โ order_items
This is just PostgreSQL with different syntax.
โ What Schema Travels Does
// users collection โ addresses embedded (92% co-accessed)
{
_id: ObjectId("..."),
email: "user@example.com",
name: "John Doe",
addresses: [ // โ EMBEDDED (bounded, rarely updated)
{ street: "123 Main", city: "NYC", is_default: true }
]
}
// orders collection โ items embedded, user referenced
{
_id: ObjectId("..."),
user_id: ObjectId("..."), // โ REFERENCED (accessed independently)
status: "shipped",
items: [ // โ EMBEDDED (always fetched together)
{ product_id: "...", quantity: 2, price: 29.99 }
]
}
Features
๐ Access Pattern Analysis
- Hot Join Detection โ Find frequently co-accessed tables
- Co-access Ratios โ Measure how often tables are queried together
- Write Ratio Tracking โ Identify update-heavy tables (bad embed candidates)
- Solo Access Detection โ Find independently accessed entities
๐ค AI-Powered Recommendations
- Claude Integration โ Intelligent embed/reference decisions
- Confidence Scores โ Know how certain each recommendation is
- Detailed Reasoning โ Understand why each decision was made
- Warning Detection โ Get alerts for potential issues
๐ Reproducible Results (v1.1.0)
- Recommendation Caching โ Same inputs = same outputs
- Version Tracking โ Cache auto-invalidates when logic changes
- Comparison Tools โ Diff recommendations between runs
- Cache Control โ
--no-cachefor fresh analysis
โก Migration Simulation
- Storage Impact โ Estimate size changes from embedding
- Latency Projection โ Predict query performance improvements
- Cost Estimation โ Calculate infrastructure cost differences
๐ Visualization
- HTML Reports โ Interactive schema visualization
- Mermaid Diagrams โ ER diagrams for documentation
- Console Output โ Rich terminal formatting
How It Works
1. Collect Access Patterns
Schema Travels parses your PostgreSQL/MySQL query logs:
2024-01-15 10:30:45 LOG: statement: SELECT u.*, a.* FROM users u
JOIN addresses a ON u.id = a.user_id WHERE u.id = 123
2024-01-15 10:30:45 LOG: duration: 3.45 ms
2. Analyze Patterns
For each table relationship, it calculates:
| Metric | Description | Embed Signal |
|---|---|---|
| Co-access ratio | % of queries accessing both tables | High = Embed |
| Child independence | % of queries accessing child alone | High = Reference |
| Write ratio | % of operations that are writes | High = Reference |
| Cardinality | Avg/max children per parent | High = Reference |
3. Apply Decision Rules
# Simplified decision logic
if max_children > 1000:
return REFERENCE # Unbounded = always reference
if co_access > 70% and write_ratio < 30% and max_children < 100:
return EMBED # High co-access, low writes, bounded
if child_independence > 40%:
return REFERENCE # Accessed alone too often
if write_ratio > 50%:
return REFERENCE # Too many updates
4. Generate Schema
Output includes:
- MongoDB collection definitions
- Embedded document structures
- Reference relationships
- Sample documents
Configuration
Environment Variables
# Required for AI recommendations
export ANTHROPIC_API_KEY=sk-ant-xxxxx
# Optional
export ANTHROPIC_MODEL=claude-sonnet-4-20250514 # or claude-opus-4-5-20250514
export LOG_LEVEL=INFO
Or create a .env file:
cp .env.example .env
# Edit .env with your API key
CLI Options
schema-travels analyze \
--logs-dir ./logs # Directory with query logs
--schema-file ./schema.sql # SQL DDL file
--db-type postgres # postgres or mysql
--target mongodb # Target database
--output results.json # Output file
--use-ai # Enable AI recommendations (default)
--no-ai # Use rule-based only
--no-cache # Bypass recommendation cache
--clear-cache # Clear all cached recommendations
Commands
| Command | Description |
|---|---|
schema-travels analyze |
Run full analysis |
schema-travels report --analysis-id <id> |
View previous analysis |
schema-travels history |
List all analyses |
schema-travels simulate --analysis-id <id> |
Run migration simulation |
schema-travels config |
Show current configuration |
Input Requirements
Query Logs
PostgreSQL โ Enable in postgresql.conf:
log_statement = 'all'
log_duration = on
log_line_prefix = '%t [%p] %u@%d '
MySQL โ Enable slow query log:
slow_query_log = 1
long_query_time = 0
log_queries_not_using_indexes = 1
Schema File
Standard SQL DDL:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total DECIMAL(10,2)
);
Storage Locations
~/.schema-travels/
โโโ schema_travels.db # Analysis history (SQLite)
โโโ cache/
โโโ index.json # Cache index with metadata
โโโ <hash>.json # Cached recommendations
Example Output
Recommendations JSON
{
"recommendations": [
{
"parent_table": "users",
"child_table": "addresses",
"decision": "EMBED",
"confidence": 0.92,
"reasoning": [
"92% co-access ratio",
"Low write frequency (8%)",
"Bounded cardinality (avg 2.1, max 5)"
],
"warnings": []
}
]
}
Generated MongoDB Schema
// users collection
{
$jsonSchema: {
bsonType: "object",
required: ["email"],
properties: {
email: { bsonType: "string" },
name: { bsonType: "string" },
addresses: {
bsonType: "array",
items: {
bsonType: "object",
properties: {
street: { bsonType: "string" },
city: { bsonType: "string" },
zip: { bsonType: "string" }
}
}
}
}
}
}
Architecture
schema-travels/
โโโ src/schema_travels/
โ โโโ collector/ # Log parsing, schema extraction
โ โโโ analyzer/ # Pattern detection (hot joins, mutations)
โ โโโ recommender/ # AI recommendations, schema generation, caching
โ โโโ simulator/ # Migration impact estimation
โ โโโ persistence/ # SQLite storage for history
โ โโโ cli/ # Command-line interface
โโโ tools/ # Workload generator, visualizer
โโโ examples/ # Sample schemas and logs
โโโ tests/ # Test suite
Development
# Clone
git clone https://github.com/kraghavan/schema-travels.git
cd schema-travels
# Setup
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"
# Test
pytest --cov=schema_travels
# Lint
ruff check src/
ruff format src/
Roadmap
- PostgreSQL log parsing
- MySQL log parsing
- MongoDB schema generation
- Claude AI integration
- Migration simulation
- Recommendation caching (v1.1.0)
- DynamoDB support
- Web UI dashboard
- Real-time log streaming
- Multi-database analysis
Contributing
Contributions welcome! Please read CONTRIBUTING.md first.
License
MIT License โ see LICENSE for details.
Acknowledgments
Stop guessing. Start measuring.
โญ Star on GitHub
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file schema_travels-1.1.0.tar.gz.
File metadata
- Download URL: schema_travels-1.1.0.tar.gz
- Upload date:
- Size: 57.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
af4edead7f3c5521273dd3a25483bcda7d346692012e00be34651df7e7481120
|
|
| MD5 |
796b02091a8ceb1096291a3042c780fe
|
|
| BLAKE2b-256 |
a7a0600f633cff8292a452b0cc57158fd8047981ac5e0fe9ca2a04ae03754344
|
File details
Details for the file schema_travels-1.1.0-py3-none-any.whl.
File metadata
- Download URL: schema_travels-1.1.0-py3-none-any.whl
- Upload date:
- Size: 59.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
00a75a85ea7481cf89f12b1dd7fec38108bd2447e85d1f897160a44403832f0f
|
|
| MD5 |
11ab68abd89ff71f82e99fedc3b9358a
|
|
| BLAKE2b-256 |
a8c9daf1d256cef8ad6d07015cb223e4ce57b1f17b50b42b1d0ea961ba6093ab
|