This directory contains comprehensive examples demonstrating the capabilities of sqlite-graph. Examples are ordered from basic to advanced, making it easy to learn progressively.
# Install dependencies (from repository root)
npm install
# Build the library
npm run buildEach example is a standalone TypeScript file that can be executed with ts-node:
# Run from repository root
npx ts-node examples/basic-usage.ts
npx ts-node examples/graph-traversal.ts
npx ts-node examples/transactions.ts
npx ts-node examples/schema-validation.tsOr run all examples:
# From repository root
for example in examples/*.ts; do
echo "=== Running $example ==="
npx ts-node "$example"
echo ""
doneDifficulty: Beginner Topics: Core operations, CRUD, simple queries
Start here if you're new to sqlite-graph. This example covers:
- Creating an in-memory or file-based database
- Creating and retrieving nodes
- Creating edges (relationships)
- Updating and deleting nodes
- Basic queries with filtering
- Querying with relationships
- Exporting and importing data
Key Concepts:
// Create database
const db = new GraphDatabase(':memory:');
// Create nodes
const job = db.createNode('Job', { title: 'Engineer', status: 'active' });
// Create relationships
db.createEdge('POSTED_BY', jobId, companyId);
// Query nodes
const activeJobs = db.nodes('Job')
.where({ status: 'active' })
.exec();Difficulty: Intermediate Topics: Graph walking, pathfinding, advanced traversals
Learn how to navigate your graph data structure:
- Outgoing edge traversal (
.out()) - Incoming edge traversal (
.in()) - Bidirectional traversal (
.both()) - Depth-limited searches (
.maxDepth(),.minDepth()) - Finding shortest paths
- Finding all paths between nodes
- Filtering traversal results
- Unique node handling
Key Concepts:
// Find similar jobs up to 2 hops away
const similar = db.traverse(jobId)
.out('SIMILAR_TO')
.maxDepth(2)
.unique()
.toArray();
// Find shortest path
const path = db.traverse(job1Id)
.shortestPath(job2Id);
// Find all paths
const allPaths = db.traverse(job1Id)
.paths(job2Id, { maxPaths: 5 });Difficulty: Intermediate Topics: ACID operations, error handling, savepoints
Master transaction management for data consistency:
- Automatic commit on success
- Automatic rollback on error
- Manual transaction control
- Savepoints for partial rollbacks
- Release savepoints
- Complex multi-step operations
- Error recovery strategies
- Transaction best practices
Key Concepts:
// Automatic transaction
const result = db.transaction(() => {
const job = db.createNode('Job', { title: 'Engineer' });
const company = db.createNode('Company', { name: 'TechCorp' });
db.createEdge('POSTED_BY', job.id, company.id);
return { job, company };
});
// Manual control with savepoints
db.transaction((ctx) => {
const job = db.createNode('Job', { title: 'Test' });
ctx.savepoint('job_created');
try {
db.createEdge('POSTED_BY', job.id, companyId);
} catch (err) {
ctx.rollbackTo('job_created');
}
ctx.commit();
});Difficulty: Advanced Topics: Type safety, validation, data modeling
Build type-safe graph databases with schema validation:
- Defining node types and properties
- Defining edge types with constraints
- Property validation
- Handling schema violations
- Working with typed data
- Schema benefits for IDE support
- Extra properties flexibility
- Real-world job application workflow
Key Concepts:
// Define schema
const schema: GraphSchema = {
nodes: {
Job: {
properties: ['title', 'company', 'salary'],
indexes: ['company']
},
Company: {
properties: ['name', 'industry'],
indexes: ['name']
}
},
edges: {
POSTED_BY: {
from: 'Job',
to: 'Company',
properties: ['postedAt']
}
}
};
// Create database with schema
const db = new GraphDatabase(':memory:', { schema });
// Schema prevents invalid operations
db.createNode('InvalidType', {}); // Throws errorMany examples use a job search domain model:
- Job nodes: Represent job postings
- Company nodes: Represent employers
- Skill nodes: Represent required skills
- Person nodes: Represent candidates
- POSTED_BY edges: Job → Company
- REQUIRES edges: Job → Skill
- HAS_SKILL edges: Person → Skill
- APPLIED_TO edges: Person → Job
Examples build on each other:
- Basic Usage: Learn the fundamentals
- Graph Traversal: Navigate relationships
- Transactions: Ensure data consistency
- Schema Validation: Add type safety
Each example includes practical use cases:
- Job recommendation systems
- Skill matching
- Application tracking
- Company research
- Path analysis
- Start Sequential: Work through examples 1→2→3→4
- Experiment: Modify examples to explore variations
- Use TypeScript: Examples leverage TypeScript for better IDE support
- Read Comments: Each example has detailed inline documentation
- Check Output: Run examples to see results in action
When you run an example, you'll see output like:
=== Basic Usage Example ===
1. Creating nodes...
Created job: Senior Software Engineer (ID: 1)
Created TypeScript, Node.js, React skills
2. Creating relationships...
Linked job to required skills
3. Retrieving nodes by ID...
Retrieved: Senior Software Engineer
Created at: 2025-10-28T...
Updated at: 2025-10-28T...
[... more output ...]
=== Example Complete ===
After working through these examples:
- Read the API Documentation: Check the main README.md
- Review Tests: See
tests/directory for edge cases - Build Your Own: Create a graph for your domain
- Check Performance: See
benchmarks/for optimization tips
If you see TypeScript compilation errors:
npm run build # Rebuild the libraryMake sure you're running from the repository root:
pwd # Should be /path/to/sqlite-graph
npx ts-node examples/basic-usage.tsExamples use :memory: databases (temporary). If you modify examples to use file paths, remember to delete old database files between runs:
rm -f example.db # If you created a file-based databaseHave a useful pattern or use case? Consider contributing an example:
- Follow the existing format and style
- Include comprehensive inline comments
- Cover a specific topic in depth
- Add entry to this README
- Test that it runs successfully
- Main Documentation:
../README.md - API Reference:
../docs/API.md(if available) - Test Suite:
../tests/ - Benchmarks:
../benchmarks/ - GitHub Issues: Report bugs or request examples
Happy Coding! If you have questions, check the main README or open an issue.