Database Models
GAIA uses a hybrid database architecture with PostgreSQL for relational data and MongoDB for document storage.Database Architecture
PostgreSQL
- Use case: Structured data requiring ACID transactions
- ORM: SQLAlchemy with async support
- Connection: asyncpg driver
- Features: Connection pooling, migrations, type safety
MongoDB
- Use case: Flexible document storage, nested data structures
- Driver: Motor (async) and PyMongo (sync)
- Features: Lazy collection loading, schema flexibility
PostgreSQL Models
GAIA uses SQLAlchemy for PostgreSQL models with async support.Database Connection
Connection Configuration
Base Model
Example Model Definition
MongoDB Models
MongoDB collections are accessed through lazy-loaded collection objects.Collection Access
Available Collections
GAIA provides the following MongoDB collections:Lazy Collection Loading
Collections are initialized only when accessed:Pydantic Models
GAIA uses Pydantic for data validation and serialization.User Models
Chat Models
MongoDB Document Structure
User Document Example
Conversation Document Example
Working with MongoDB
CRUD Operations
Aggregation Pipeline
Synchronous MongoDB Access
For synchronous code (e.g., Composio tools):Best Practices
- Always convert ObjectId to string when returning data to API
- Use timezone-aware datetimes with
datetime.now(timezone.utc) - Index frequently queried fields for performance
- Use projection to limit returned fields
- Validate data with Pydantic models before database operations
- Handle ObjectId conversions in service layer, not endpoints
- Use aggregation pipelines for complex queries
- Implement proper error handling for database operations
- Use connection pooling for PostgreSQL
- Leverage lazy loading for MongoDB collections
Database Relationships
User → Conversations (1:N)
User → Goals (1:N)
Migration Strategy
For schema changes in MongoDB:- Add migration script in
app/db/migrations/ - Use versioning in documents when needed
- Handle backwards compatibility in code
- Test with production-like data