Database Domain Specialist
Quick Reference
Enterprise Database Expertise - Comprehensive database patterns and implementations covering PostgreSQL, MongoDB, Redis, Oracle, and advanced data management for scalable modern applications.
Core Capabilities:
- PostgreSQL: Advanced relational patterns, optimization, and scaling
- MongoDB: Document modeling, aggregation, and NoSQL performance tuning
- Redis: In-memory caching, real-time analytics, and distributed systems
- Oracle: Enterprise patterns, PL/SQL, partitioning, and hierarchical queries
- Multi-Database: Hybrid architectures and data integration patterns
- Performance: Query optimization, indexing strategies, and scaling
- Operations: Connection management, migrations, and monitoring
When to Use:
- Designing database schemas and data models
- Implementing caching strategies and performance optimization
- Building scalable data architectures
- Working with multi-database systems
- Optimizing database queries and performance
Implementation Guide
Quick Start Workflow
Database Stack Initialization:
Create a DatabaseManager instance and configure multiple database connections. Set up PostgreSQL with connection string, pool size of 20, and query logging enabled. Configure MongoDB with connection string, database name, and sharding enabled. Configure Redis with connection string, max connections of 50, and clustering enabled. Use the unified interface to query user data with profile and analytics across all database types.
Single Database Operations:
Run PostgreSQL schema migrations using the migration command with the database type and migration file path. Execute MongoDB aggregation pipelines by specifying the collection name and pipeline JSON file. Warm Redis cache by specifying key patterns and TTL values.
Core Components
PostgreSQL Module:
- Advanced schema design and constraints
- Complex query optimization and indexing
- Window functions and CTEs
- Partitioning and materialized views
- Connection pooling and performance tuning
MongoDB Module:
- Document modeling and schema design
- Aggregation pipelines for analytics
- Indexing strategies and performance
- Sharding and scaling patterns
- Data consistency and validation
Redis Module:
- Multi-layer caching strategies
- Real-time analytics and counting
- Distributed locking and coordination
- Pub/sub messaging and streams
- Advanced data structures including HyperLogLog and Geo
Oracle Module:
- Hierarchical and recursive query patterns (CONNECT BY)
- PL/SQL procedures, packages, and batch operations
- Partitioning strategies (range, list, hash, composite)
- Enterprise features and statement caching
- LOB handling and large data processing
Advanced Patterns
Multi-Database Architecture
Polyglot Persistence Pattern:
Create a DataRouter class that initializes connections to PostgreSQL, MongoDB, Redis, and Oracle. Implement get_user_profile method that retrieves structured user data from PostgreSQL or Oracle, flexible profile data from MongoDB, and real-time status from Redis, then merges all data sources. Implement update_user_data method that routes structured data updates to PostgreSQL/Oracle, profile data updates to MongoDB, and real-time data updates to Redis, followed by cache invalidation.
Data Synchronization:
Create a DataSyncManager class that synchronizes user data across databases. Implement sync_user_data method that retrieves user from PostgreSQL, creates a search document for MongoDB, upserts to the MongoDB search collection, creates cache data, and updates Redis cache with TTL.
Performance Optimization
Query Performance Analysis:
For PostgreSQL, execute EXPLAIN ANALYZE BUFFERS on queries and use a QueryAnalyzer to generate optimization suggestions. For MongoDB, create an AggregationOptimizer to analyze and optimize aggregation pipelines. For Redis, retrieve info metrics and use a PerformanceAnalyzer to generate recommendations.
Scaling Strategies:
Configure PostgreSQL read replicas by providing replica connection URLs. Set up MongoDB sharding with shard key and number of shards. Configure Redis clustering by providing node URLs for the cluster.
Works Well With
Complementary Skills:
- moai-domain-backend - API integration and business logic
- moai-foundation-core - Database migration and schema management
- moai-workflow-project - Database project setup and configuration
- moai-platform-supabase - Supabase database integration patterns
- moai-platform-neon - Neon database integration patterns
- moai-platform-firestore - Firestore database integration patterns
Technology Integration:
- ORMs and ODMs including SQLAlchemy, Mongoose, and TypeORM
- Connection pooling with PgBouncer and connection pools
- Migration tools including Alembic, Flyway, and Data Pump
- Monitoring with pg_stat_statements, MongoDB Atlas, and Oracle AWR
- python-oracledb for Oracle connectivity and PL/SQL execution
- Cache invalidation and synchronization
Technology Stack
Relational Database:
- PostgreSQL 14+ as primary database
- MySQL 8.0+ as alternative
- Connection pooling with PgBouncer and SQLAlchemy
NoSQL Database:
- MongoDB 6.0+ as primary document store
- Document modeling and validation
- Aggregation framework
- Sharding and replication
In-Memory Database:
- Redis 7.0+ as primary cache
- Redis Stack for advanced features
- Clustering and high availability
- Advanced data structures
Enterprise Database:
- Oracle 19c+ / 21c+ for enterprise workloads
- python-oracledb (successor to cx_Oracle)
- PL/SQL procedures and packages
- Partitioning and advanced analytics
Supporting Tools:
- Migration tools including Alembic and Flyway
- Monitoring with Prometheus and Grafana
- ORMs and ODMs including SQLAlchemy and Mongoose
- Connection management utilities
Performance Features:
- Query optimization and analysis
- Index management and strategies
- Caching layers and invalidation
- Load balancing and failover
Resources
Status: Production Ready
Last Updated: 2026-01-11
Maintained by: MoAI-ADK Database Team
Common Rationalizations
| Rationalization |
Reality |
| "I do not need an index, the table is small" |
Tables grow. The missing index that is invisible at 1K rows becomes a production incident at 1M rows. |
| "I will add the migration later" |
Schema changes without migrations are unreproducible. Every change must have a reversible migration script. |
| "This query works fine in development" |
Development databases have tiny datasets. Production query plans differ dramatically at scale. Explain analyze first. |
| "NoSQL does not need schema design" |
Schemaless does not mean designless. Document structure decisions affect every query and index. |
| "I will just add a column, it is non-breaking" |
Adding a NOT NULL column without a default breaks existing inserts. Column additions need default values or migration backfills. |
| "Connection pooling is handled by the framework" |
Framework defaults are generic. Pool size, timeout, and idle limits must be tuned to the workload. |
Red Flags
- Schema change committed without a corresponding migration file
- Query uses SELECT * in production code instead of explicit column list
- No index exists for columns used in WHERE, JOIN, or ORDER BY clauses
- Connection string hardcoded in source instead of environment variable
- Transaction scope spans user-facing HTTP request duration (long-held locks)
- No EXPLAIN ANALYZE output for new queries touching large tables
Verification
Cloud Vendor Guide (absorbed from moai-platform-database-cloud)
Cloud database platform selection and configuration for Neon, Supabase, and Firebase Firestore.
Quick Decision Guide
| Need |
Platform |
| Serverless PostgreSQL with auto-scaling |
Neon |
| Database branching for CI/CD previews |
Neon branching |
| Edge-compatible connection pooling |
Neon + Neon Proxy |
| Vector search (pgvector) for AI/ML |
Supabase |
| Row-Level Security for multi-tenant apps |
Supabase RLS |
| Real-time subscriptions + full-stack |
Supabase |
| Mobile-first with offline sync |
Firebase Firestore |
| Cross-platform (iOS/Android/Web) |
Firebase Firestore |
Neon (Serverless PostgreSQL)
Key features: Auto-scaling compute, scale-to-zero, database branching, pg_bouncer pooling.
Setup:
npm install @neondatabase/serverless
# Connection string: postgresql://user:pass@ep-xxx.neon.tech/dbname?sslmode=require
Branch workflow: Create a branch per PR (neonctl branches create --name pr-123), run migrations, test, delete on merge. Zero cost during idle periods.
Supabase (PostgreSQL 16)
Key features: pgvector, Row-Level Security, real-time subscriptions, built-in auth/storage.
RLS policy pattern:
CREATE POLICY "users_own_data" ON items
FOR ALL USING (auth.uid() = user_id);
pgvector search: SELECT * FROM embeddings ORDER BY embedding <-> $1 LIMIT 10;
Firebase Firestore (NoSQL)
Key features: Real-time sync, offline caching, Security Rules, mobile SDKs.
Security Rules pattern:
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
Offline persistence: Enable via enableIndexedDbPersistence(db) (web) or SDK default (mobile).
Refactor Notes
Refactor scope (deferred to future sub-SPEC):
- Separate moai-domain-db-docs workflow skill from this query/schema design skill
- Extract cloud vendor deep-dives (Neon, Supabase, Firestore) into dedicated Level-3 modules
- Consolidate overlapping ORM pattern content across database types
This skill is retained in v3.0 but its body will be restructured in a follow-up SPEC. Cloud vendor content absorbed from moai-platform-database-cloud in Wave 1.2.
1---
2name: moai-domain-database
3description: >
4 Database specialist covering PostgreSQL, MongoDB, Redis, Oracle, and cloud database
5 platforms (Neon, Supabase, Firestore). Use for schema design, query optimization,
6 indexing strategies, data modeling, or cloud database selection.
7 Cloud vendor guide absorbed from moai-platform-database-cloud.
8
9when_to_use: >
10 Use for schema design, query optimization, indexing strategies, and
11 ORMs/ODMs (Prisma, Mongoose, SQLAlchemy, Drizzle). Covers PostgreSQL,
12 MongoDB, Redis, Oracle, and cloud databases (Neon, Supabase, Firestore).
13
14license: Apache-2.0
15compatibility: Designed for Claude Code
16allowed-tools: Read, Write, Edit, Bash(psql:*), Bash(mysql:*), Bash(sqlite3:*), Bash(mongosh:*), Bash(redis-cli:*), Bash(npm:*), Bash(npx:*), Bash(prisma:*), Bash(neonctl:*), Bash(firebase:*), Bash(supabase:*), Grep, Glob
17user-invocable: false
18metadata:
19 source: https://skillmd.com/skills/modu-ai/moai-domain-database
20 version: "2.0.0"
21 category: "domain"
22 status: "active"
23 updated: "2026-04-25"
24 tags: "database, postgresql, mongodb, redis, oracle, data-patterns, performance, neon, supabase, firestore, cloud-database, serverless"
25 author: "MoAI-ADK Team"
26 related-skills: "moai-platform-database-cloud"
27
28# MoAI Extension: Progressive Disclosure
29progressive_disclosure:
30 enabled: true
31 level1_tokens: 100
32 level2_tokens: 5000
33---
34
35# Database Domain Specialist
36
37## Quick Reference
38
39Enterprise Database Expertise - Comprehensive database patterns and implementations covering PostgreSQL, MongoDB, Redis, Oracle, and advanced data management for scalable modern applications.
40
41Core Capabilities:
42
43- PostgreSQL: Advanced relational patterns, optimization, and scaling
44- MongoDB: Document modeling, aggregation, and NoSQL performance tuning
45- Redis: In-memory caching, real-time analytics, and distributed systems
46- Oracle: Enterprise patterns, PL/SQL, partitioning, and hierarchical queries
47- Multi-Database: Hybrid architectures and data integration patterns
48- Performance: Query optimization, indexing strategies, and scaling
49- Operations: Connection management, migrations, and monitoring
50
51When to Use:
52
53- Designing database schemas and data models
54- Implementing caching strategies and performance optimization
55- Building scalable data architectures
56- Working with multi-database systems
57- Optimizing database queries and performance
58
59---
60
61## Implementation Guide
62
63### Quick Start Workflow
64
65Database Stack Initialization:
66
67Create a DatabaseManager instance and configure multiple database connections. Set up PostgreSQL with connection string, pool size of 20, and query logging enabled. Configure MongoDB with connection string, database name, and sharding enabled. Configure Redis with connection string, max connections of 50, and clustering enabled. Use the unified interface to query user data with profile and analytics across all database types.
68
69Single Database Operations:
70
71Run PostgreSQL schema migrations using the migration command with the database type and migration file path. Execute MongoDB aggregation pipelines by specifying the collection name and pipeline JSON file. Warm Redis cache by specifying key patterns and TTL values.
72
73### Core Components
74
75PostgreSQL Module:
76
77- Advanced schema design and constraints
78- Complex query optimization and indexing
79- Window functions and CTEs
80- Partitioning and materialized views
81- Connection pooling and performance tuning
82
83MongoDB Module:
84
85- Document modeling and schema design
86- Aggregation pipelines for analytics
87- Indexing strategies and performance
88- Sharding and scaling patterns
89- Data consistency and validation
90
91Redis Module:
92
93- Multi-layer caching strategies
94- Real-time analytics and counting
95- Distributed locking and coordination
96- Pub/sub messaging and streams
97- Advanced data structures including HyperLogLog and Geo
98
99Oracle Module:
100
101- Hierarchical and recursive query patterns (CONNECT BY)
102- PL/SQL procedures, packages, and batch operations
103- Partitioning strategies (range, list, hash, composite)
104- Enterprise features and statement caching
105- LOB handling and large data processing
106
107---
108
109## Advanced Patterns
110
111### Multi-Database Architecture
112
113Polyglot Persistence Pattern:
114
115Create a DataRouter class that initializes connections to PostgreSQL, MongoDB, Redis, and Oracle. Implement get_user_profile method that retrieves structured user data from PostgreSQL or Oracle, flexible profile data from MongoDB, and real-time status from Redis, then merges all data sources. Implement update_user_data method that routes structured data updates to PostgreSQL/Oracle, profile data updates to MongoDB, and real-time data updates to Redis, followed by cache invalidation.
116
117Data Synchronization:
118
119Create a DataSyncManager class that synchronizes user data across databases. Implement sync_user_data method that retrieves user from PostgreSQL, creates a search document for MongoDB, upserts to the MongoDB search collection, creates cache data, and updates Redis cache with TTL.
120
121### Performance Optimization
122
123Query Performance Analysis:
124
125For PostgreSQL, execute EXPLAIN ANALYZE BUFFERS on queries and use a QueryAnalyzer to generate optimization suggestions. For MongoDB, create an AggregationOptimizer to analyze and optimize aggregation pipelines. For Redis, retrieve info metrics and use a PerformanceAnalyzer to generate recommendations.
126
127Scaling Strategies:
128
129Configure PostgreSQL read replicas by providing replica connection URLs. Set up MongoDB sharding with shard key and number of shards. Configure Redis clustering by providing node URLs for the cluster.
130
131---
132
133## Works Well With
134
135Complementary Skills:
136
137- moai-domain-backend - API integration and business logic
138- moai-foundation-core - Database migration and schema management
139- moai-workflow-project - Database project setup and configuration
140- moai-platform-supabase - Supabase database integration patterns
141- moai-platform-neon - Neon database integration patterns
142- moai-platform-firestore - Firestore database integration patterns
143
144Technology Integration:
145
146- ORMs and ODMs including SQLAlchemy, Mongoose, and TypeORM
147- Connection pooling with PgBouncer and connection pools
148- Migration tools including Alembic, Flyway, and Data Pump
149- Monitoring with pg_stat_statements, MongoDB Atlas, and Oracle AWR
150- python-oracledb for Oracle connectivity and PL/SQL execution
151- Cache invalidation and synchronization
152
153---
154
155## Technology Stack
156
157Relational Database:
158
159- PostgreSQL 14+ as primary database
160- MySQL 8.0+ as alternative
161- Connection pooling with PgBouncer and SQLAlchemy
162
163NoSQL Database:
164
165- MongoDB 6.0+ as primary document store
166- Document modeling and validation
167- Aggregation framework
168- Sharding and replication
169
170In-Memory Database:
171
172- Redis 7.0+ as primary cache
173- Redis Stack for advanced features
174- Clustering and high availability
175- Advanced data structures
176
177Enterprise Database:
178
179- Oracle 19c+ / 21c+ for enterprise workloads
180- python-oracledb (successor to cx_Oracle)
181- PL/SQL procedures and packages
182- Partitioning and advanced analytics
183
184Supporting Tools:
185
186- Migration tools including Alembic and Flyway
187- Monitoring with Prometheus and Grafana
188- ORMs and ODMs including SQLAlchemy and Mongoose
189- Connection management utilities
190
191Performance Features:
192
193- Query optimization and analysis
194- Index management and strategies
195- Caching layers and invalidation
196- Load balancing and failover
197
198---
199
200## Resources
201
202Status: Production Ready
203Last Updated: 2026-01-11
204Maintained by: MoAI-ADK Database Team
205
206<!-- moai:evolvable-start id="rationalizations" -->
207## Common Rationalizations
208
209| Rationalization | Reality |
210|---|---|
211| "I do not need an index, the table is small" | Tables grow. The missing index that is invisible at 1K rows becomes a production incident at 1M rows. |
212| "I will add the migration later" | Schema changes without migrations are unreproducible. Every change must have a reversible migration script. |
213| "This query works fine in development" | Development databases have tiny datasets. Production query plans differ dramatically at scale. Explain analyze first. |
214| "NoSQL does not need schema design" | Schemaless does not mean designless. Document structure decisions affect every query and index. |
215| "I will just add a column, it is non-breaking" | Adding a NOT NULL column without a default breaks existing inserts. Column additions need default values or migration backfills. |
216| "Connection pooling is handled by the framework" | Framework defaults are generic. Pool size, timeout, and idle limits must be tuned to the workload. |
217
218<!-- moai:evolvable-end -->
219
220<!-- moai:evolvable-start id="red-flags" -->
221## Red Flags
222
223- Schema change committed without a corresponding migration file
224- Query uses SELECT * in production code instead of explicit column list
225- No index exists for columns used in WHERE, JOIN, or ORDER BY clauses
226- Connection string hardcoded in source instead of environment variable
227- Transaction scope spans user-facing HTTP request duration (long-held locks)
228- No EXPLAIN ANALYZE output for new queries touching large tables
229
230<!-- moai:evolvable-end -->
231
232<!-- moai:evolvable-start id="verification" -->
233## Verification
234
235- [ ] Migration file exists for every schema change (show migration file list)
236- [ ] Indexes exist for frequently queried columns (show index definitions)
237- [ ] EXPLAIN ANALYZE run for new queries on representative data (show output)
238- [ ] Connection credentials sourced from environment variables
239- [ ] Transaction scopes are minimal and do not span I/O waits
240- [ ] Backup and restore procedure documented and tested
241- [ ] Connection pool settings configured with explicit size and timeout
242
243<!-- moai:evolvable-end -->
244
245---
246
247## Cloud Vendor Guide (absorbed from moai-platform-database-cloud)
248
249Cloud database platform selection and configuration for Neon, Supabase, and Firebase Firestore.
250
251### Quick Decision Guide
252
253| Need | Platform |
254|------|----------|
255| Serverless PostgreSQL with auto-scaling | Neon |
256| Database branching for CI/CD previews | Neon branching |
257| Edge-compatible connection pooling | Neon + Neon Proxy |
258| Vector search (pgvector) for AI/ML | Supabase |
259| Row-Level Security for multi-tenant apps | Supabase RLS |
260| Real-time subscriptions + full-stack | Supabase |
261| Mobile-first with offline sync | Firebase Firestore |
262| Cross-platform (iOS/Android/Web) | Firebase Firestore |
263
264### Neon (Serverless PostgreSQL)
265
266Key features: Auto-scaling compute, scale-to-zero, database branching, pg_bouncer pooling.
267
268Setup:
269```bash
270npm install @neondatabase/serverless
271# Connection string: postgresql://user:pass@ep-xxx.neon.tech/dbname?sslmode=require
272```
273
274Branch workflow: Create a branch per PR (`neonctl branches create --name pr-123`), run migrations, test, delete on merge. Zero cost during idle periods.
275
276### Supabase (PostgreSQL 16)
277
278Key features: pgvector, Row-Level Security, real-time subscriptions, built-in auth/storage.
279
280RLS policy pattern:
281```sql
282CREATE POLICY "users_own_data" ON items
283 FOR ALL USING (auth.uid() = user_id);
284```
285
286pgvector search: `SELECT * FROM embeddings ORDER BY embedding <-> $1 LIMIT 10;`
287
288### Firebase Firestore (NoSQL)
289
290Key features: Real-time sync, offline caching, Security Rules, mobile SDKs.
291
292Security Rules pattern:
293```javascript
294match /users/{userId} {
295 allow read, write: if request.auth.uid == userId;
296}
297```
298
299Offline persistence: Enable via `enableIndexedDbPersistence(db)` (web) or SDK default (mobile).
300
301## Refactor Notes
302
303**Refactor scope** (deferred to future sub-SPEC):
304- Separate moai-domain-db-docs workflow skill from this query/schema design skill
305- Extract cloud vendor deep-dives (Neon, Supabase, Firestore) into dedicated Level-3 modules
306- Consolidate overlapping ORM pattern content across database types
307
308This skill is retained in v3.0 but its body will be restructured in a follow-up SPEC. Cloud vendor content absorbed from moai-platform-database-cloud in Wave 1.2.