Database Configuration

RouteMQ supports MySQL integration for persistent data storage using SQLAlchemy with async support.

Environment Setup

Configure your database connection in the .env file:

# Enable/disable database integration
ENABLE_MYSQL=true

# Database connection settings
DB_HOST=localhost
DB_PORT=3306
DB_NAME=mqtt_framework
DB_USER=root
DB_PASS=your_password

Database Dependencies

The framework uses these database-related packages:

  • SQLAlchemy 2.0+: Modern async ORM

  • aiomysql: Async MySQL driver

  • python-dotenv: Environment variable management

These are included in requirements.txt:

Connection Configuration

Automatic Configuration

The framework automatically configures the database connection on startup:

Manual Configuration

You can also configure the database manually:

Connection String Format

The connection string follows SQLAlchemy's format for async MySQL:

Connection String Examples

Database Setup

Creating the Database

Before running your application, create the database:

Table Creation

The framework automatically creates tables when the application starts:

Configuration Options

Development Settings

Production Settings

Docker Configuration

Connection Pool Settings

SQLAlchemy's async engine provides connection pooling by default. You can customize pool settings:

SSL Configuration

For secure connections, configure SSL in the connection string:

Disabling Database Integration

To run without database support:

When disabled:

  • Database operations return None or empty results

  • No database connections are created

  • Models can still be defined but won't persist data

  • Warnings are logged when database operations are attempted

Troubleshooting

Common Connection Issues

Error: aiomysql not installed

Error: Access denied for user

Error: Unknown database

Error: Connection timeout

  • Check if MySQL server is running

  • Verify host and port settings

  • Check firewall settings

Debug Connection Issues

Enable SQL query logging:

Check connection in logs:

Testing Database Connection

Configuration Best Practices

Security

  1. Use environment variables for sensitive data

  2. Create dedicated database users with minimal privileges

  3. Use SSL connections in production

  4. Regularly rotate passwords

Performance

  1. Configure appropriate pool sizes based on expected load

  2. Use connection recycling to prevent stale connections

  3. Monitor connection usage in production

  4. Consider read replicas for high-read workloads

Development

  1. Use separate databases for development, testing, and production

  2. Keep connection strings in version-controlled .env.example files

  3. Document required database setup for new developers

Docker Setup

Docker Compose Example

Initialization Script

Next Steps

Last updated