Database Operations

RouteMQ provides built-in database integration using SQLAlchemy for async database operations. This guide shows how to work with database models in your controllers.

Database Configuration

Database operations are configured through environment variables:

# Enable MySQL
ENABLE_MYSQL=true

# Database connection
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=your_username
MYSQL_PASSWORD=your_password
MYSQL_DATABASE=routemq

Model Structure

Base Model

All models extend the base Model class:

from core.model import Model, Base
from sqlalchemy import Column, Integer, String, DateTime, Float
from sqlalchemy.sql import func

class DeviceModel(Base, Model):
    __tablename__ = 'devices'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    device_id = Column(String(255), unique=True, nullable=False)
    name = Column(String(255), nullable=False)
    status = Column(String(50), default='offline')
    last_seen = Column(DateTime, default=func.now())
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

Creating Models

Create model files in the app/models/ directory:

Database Operations in Controllers

Basic CRUD Operations

Sensor Data Storage

Complex Queries and Aggregations

Batch Operations

Transaction Management

Database Best Practices

1. Always Use Session Management

2. Handle Database Unavailability

3. Use Indexes for Performance

4. Validate Data Before Database Operations

Migration and Schema Management

For production deployments, consider using Alembic for database migrations:

Next Steps

Last updated