Getting Started

Quick start guide to install and use Akron ORM in your Python projects with practical examples.

Welcome to Akron ORM

Akron is a universal Python ORM that provides a consistent API across SQLite, MySQL, PostgreSQL, and MongoDB. Get started in minutes with this comprehensive guide.

✨ What You'll Learn

  • • Install Akron and its dependencies
  • • Connect to your first database
  • • Create tables and manage schemas
  • • Perform CRUD operations
  • • Use both Python API and CLI tools

Installation

Basic Installation

Install Akron using pip. This includes support for SQLite by default:

Install Akron ORM
1# Basic installation with SQLite support
2pip install akron
3
4# Verify installation
5python -c "import akron; print(f'Akron {akron.__version__} installed successfully')"
6
7# Check CLI availability
8akron --version
Expected Output
Collecting akron
Installing collected packages: akron
Successfully installed akron-1.0.0

Akron 1.0.0 installed successfully
akron 1.0.0

Database-Specific Dependencies

Install additional packages for other databases:

Database Dependencies
1# MySQL support
2pip install akron mysql-connector-python
3
4# PostgreSQL support
5pip install akron psycopg2-binary
6
7# MongoDB support
8pip install akron pymongo
9
10# All databases at once
11pip install akron mysql-connector-python psycopg2-binary pymongo

📝 Installation Notes

  • • SQLite is included with Python, no additional setup needed
  • • MySQL requires a running MySQL server
  • • PostgreSQL requires a running PostgreSQL server
  • • MongoDB requires a running MongoDB instance

Your First Database

Quick Start with SQLite

Let's create a simple blog application to demonstrate Akron's capabilities:

Basic Setup (save as blog_app.py)
1from akron import Akron
2from pydantic import BaseModel
3from akron.models import ModelMixin
4
5# Define your data models using Pydantic + ModelMixin
6class User(BaseModel, ModelMixin):
7 id: int
8 username: str
9 email: str
10 is_active: bool = True
11
12class Post(BaseModel, ModelMixin):
13 id: int
14 user_id: int # Foreign key to users table
15 title: str
16 content: str
17 published: bool = False
18
19# Connect to database (SQLite file will be created automatically)
20db = Akron("sqlite:///blog.db")
21
22# Create tables
23User.create_table(db)
24Post.create_table(db)
25
26print("Database and tables created successfully!")
27
28# Insert sample data
29alice_id = User.insert(db, User(
30 id=1,
31 username="alice",
32 email="alice@example.com"
33))
34
35bob_id = User.insert(db, User(
36 id=2,
37 username="bob",
38 email="bob@example.com"
39))
40
41# Create some posts
42Post.insert(db, Post(
43 id=1,
44 user_id=alice_id,
45 title="Welcome to Akron ORM",
46 content="This is my first post using Akron!",
47 published=True
48))
49
50Post.insert(db, Post(
51 id=2,
52 user_id=bob_id,
53 title="Database Magic",
54 content="Akron makes database operations so easy!",
55 published=True
56))
57
58# Query data
59all_users = User.find(db)
60published_posts = Post.find(db, {"published": True})
61
62print(f"\nUsers in database: {len(all_users)}")
63for user in all_users:
64 print(f" - {user.username} ({user.email})")
65
66print(f"\nPublished posts: {len(published_posts)}")
67for post in published_posts:
68 print(f" - {post.title} by user {post.user_id}")
69
70# Always close the connection
71db.close()
Expected Output
Database and tables created successfully!

Users in database: 2
  - alice (alice@example.com)
  - bob (bob@example.com)

Published posts: 2
  - Welcome to Akron ORM by user 1
  - Database Magic by user 2

Using the CLI

Alternatively, use the CLI for quick database operations:

CLI Quick Start
1# Create users table via CLI
2akron create-table users --db "sqlite:///blog.db" --schema '{
3 "id": "int",
4 "username": "str",
5 "email": "str",
6 "is_active": "bool"
7}'
8
9# Add sample data
10akron seed users --db "sqlite:///blog.db" --data '[
11 {"username": "alice", "email": "alice@example.com", "is_active": true},
12 {"username": "bob", "email": "bob@example.com", "is_active": true}
13]'
14
15# Check the data
16akron raw-sql --db "sqlite:///blog.db" --query "SELECT * FROM users"
17
18# Inspect database structure
19akron inspect-schema --db "sqlite:///blog.db"
Expected Output
✓ Table 'users' created successfully
✓ Seeded 2 records into 'users' table

Query Results:
[
  {"id": 1, "username": "alice", "email": "alice@example.com", "is_active": true},
  {"id": 2, "username": "bob", "email": "bob@example.com", "is_active": true}
]

Database Schema:
├── users
│   ├── id (int)
│   ├── username (str)
│   ├── email (str)
│   └── is_active (bool)

Core Concepts

🔌 Database Connections

Akron uses connection URLs to specify database type and location:

1# SQLite (file-based)
2db = Akron("sqlite:///myapp.db")
3
4# SQLite (in-memory)
5db = Akron("sqlite:///:memory:")
6
7# MySQL
8db = Akron("mysql://user:password@localhost:3306/mydb")
9
10# PostgreSQL
11db = Akron("postgres://user:password@localhost:5432/mydb")
12
13# MongoDB
14db = Akron("mongodb://localhost:27017/mydb")

📋 Schema Definition

Define table schemas using simple type mappings:

1# Basic schema
2schema = {
3 "id": "int", # Integer primary key
4 "name": "str", # String/VARCHAR
5 "price": "float", # Floating point number
6 "active": "bool" # Boolean
7}
8
9# With foreign keys
10schema = {
11 "id": "int",
12 "user_id": "int->users.id", # Foreign key to users.id
13 "category_id": "int->categories.id",
14 "title": "str",
15 "content": "str"
16}

🔄 CRUD Operations

Consistent API for Create, Read, Update, Delete across all databases:

1# Create table
2db.create_table("products", {"id": "int", "name": "str", "price": "float"})
3
4# Insert data
5product_id = db.insert("products", {"name": "Laptop", "price": 999.99})
6
7# Read data
8all_products = db.find("products")
9expensive_products = db.find("products", {"price": 999.99})
10
11# Update data
12db.update("products", {"id": product_id}, {"price": 899.99})
13
14# Delete data
15db.delete("products", {"id": product_id})

🛡️ Type Safety with Pydantic

Use Pydantic models for automatic validation and type safety:

1from pydantic import BaseModel, EmailStr
2from akron.models import ModelMixin
3
4class User(BaseModel, ModelMixin):
5 id: int
6 username: str
7 email: EmailStr # Automatic email validation
8 age: int
9
10 class Config:
11 # Add custom validation
12 @validator('age')
13 def validate_age(cls, v):
14 if v < 0 or v > 150:
15 raise ValueError('Age must be between 0 and 150')
16 return v
17
18# Usage with automatic validation
19try:
20 user = User(
21 id=1,
22 username="alice",
23 email="invalid-email", # This will raise ValidationError
24 age=25
25 )
26 User.insert(db, user)
27except ValidationError as e:
28 print(f"Validation failed: {e}")

Working with Different Databases

MySQL Example

Connect to MySQL with the same API:

MySQL Setup
1# Make sure MySQL is running and create a database first:
2# CREATE DATABASE myapp;
3
4from akron import Akron
5
6# Connect to MySQL
7db = Akron("mysql://username:password@localhost:3306/myapp")
8
9# Same API works across all databases
10db.create_table("customers", {
11 "id": "int",
12 "name": "str",
13 "email": "str",
14 "created_at": "str"
15})
16
17customer_id = db.insert("customers", {
18 "name": "John Doe",
19 "email": "john@example.com",
20 "created_at": "2024-01-15"
21})
22
23customers = db.find("customers", {"email": "john@example.com"})
24print(f"Found customer: {customers[0]}")
25
26db.close()

MongoDB Example

MongoDB works seamlessly with the same API:

MongoDB Setup
1# Make sure MongoDB is running
2
3from akron import Akron
4
5# Connect to MongoDB
6db = Akron("mongodb://localhost:27017/myapp")
7
8# MongoDB is schemaless, but Akron provides structure
9db.create_table("orders", {
10 "id": "int",
11 "customer_id": "int",
12 "items": "str", # JSON string in MongoDB
13 "total": "float",
14 "status": "str"
15})
16
17order_id = db.insert("orders", {
18 "customer_id": 1,
19 "items": '["laptop", "mouse"]',
20 "total": 1099.99,
21 "status": "pending"
22})
23
24pending_orders = db.find("orders", {"status": "pending"})
25print(f"Pending orders: {len(pending_orders)}")
26
27db.close()

Best Practices

🔄 Connection Management

  • Use context managers for automatic connection cleanup
  • Always close connections when done
  • Consider connection pooling for production applications
1# Recommended: Use with statement
2with Akron("sqlite:///app.db") as db:
3 result = db.find("users", {"active": True})
4 # Connection automatically closed

🛡️ Data Validation

  • Use Pydantic models for type safety and validation
  • Define clear schemas with appropriate types
  • Handle validation errors gracefully

🚀 Performance

  • Use specific filters in queries to avoid scanning entire tables
  • Create indexes on frequently queried columns (database-specific)
  • Batch operations when inserting multiple records

🧪 Development

  • Use SQLite for development and testing
  • Keep database schemas in version control
  • Use migrations for schema changes
  • Test with sample data using the seed command

Next Steps

Now that you've got the basics, explore advanced features:

API Reference

Detailed documentation for all methods

→ explore API methods

CLI Tools

Command-line interface for database management

→ learn CLI commands

Database Support

Database-specific features and configurations

→ view database guides