AI Database Architect is a web-based application that automatically generates relational database schemas from user-defined business rules.For DB-First Projects
Traditional database design requires:
- Deep understanding of business requirements
- Manual extraction of entities and relationships
- Careful consideration of normalization forms (1NF, 2NF, 3NF)
- Time-consuming diagram creation
- Extensive SQL script writing
For developers, especially those working on multiple projects simultaneously, this process can consume days or even weeks. The AI Database Architect addresses this pain point by automating the entire workflow while maintaining professional standards.
The platform is built on a PHP-based architecture with a MySQL database, utilizing the MVC pattern for clean separation of concerns:
- PHP 8.x: Server-side logic and API endpoints , this project not tested with lower versions ,but you can still use with lower versions if needed , might require minimal configurations
- MySQL/PDO: Database management with prepared statements for security
- Gemini AI (2.5 Flash Lite): Natural language processing and intelligent analysis
- Session-based Authentication: Secure user management
The user interface prioritizes modern design principles and user experience:
- Tailwind CSS: Utility-first styling for rapid UI development
- Lucide Icons: Consistent and beautiful iconography
- Vanilla JavaScript: Lightweight, dependency-free interactions
- Viz.js: Advanced ER diagram rendering with Graphviz
- SVG Pan Zoom: Interactive diagram navigation
- Service Layer Pattern: The
GeminiServiceclass encapsulates all AI interactions - API-First Architecture: Stages Consume API rather write PHP script into Page ,Seperated Logic to Request & Response style
- Progressive Enhancement: Each stage builds upon the previous one , that allow to ai seperate tasks and give better solutions
- Error Resilience: Automatic retry logic for AI service overload scenarios
Users Can List View Their Projects & Work on multiple Projects from one account
Users begin by providing a natural language description of their project. The system accepts descriptions in various formats—from simple bullet points to comprehensive business requirement documents.
{
"name": "E-Commerce Platform",
"domain": "Retail",
"description": "An online store where customers can browse products,
add items to cart, place orders, and make payments..."
}This is where the AI magic begins. The GeminiService analyzes the project description and extracts structured business rules using sophisticated prompt engineering:
Rule Classification System:
- Structural (S): Define entities and their core attributes
- Operational (O): Describe business processes and workflows
- Threshold (T): Specify limits and constraints
- Authorization (Y): Define access control requirements
Entity Component Analysis:
- E: Entity definitions
- R: Relationship identifications
- A: Attribute specifications
- C: Constraint declarations
Implementation Type Mapping: The AI determines how each rule should be implemented:
- Primary/Foreign Keys
- Database Triggers
- Application-level Constraints
- Access Control Mechanisms
Based on the extracted rules, the AI generates an initial database schema. This stage creates the foundational structure:
// Example generated table structure
{
"table_name": "customers",
"columns": [
{"name": "customer_id", "type": "INT", "is_primary": true},
{"name": "email", "type": "VARCHAR(255)", "is_unique": true},
{"name": "full_name", "type": "VARCHAR(100)", "is_nullable": false}
]
}Before normalization, the system performs an automated audit to identify potential issues:
- Missing Primary Keys
- Inappropriate data types
- Constraint violations
- Orphaned relationships
The audit system provides actionable recommendations, ensuring the schema meets minimum quality standards before proceeding.

The platform implements a rigorous normalization process:
- Eliminates repeating groups
- Ensures atomic values
- Creates separate tables for multi-valued attributes
- Removes partial dependencies
- Ensures all non-key attributes depend on the entire primary key
- Particularly critical for composite key tables
- Eliminates transitive dependencies
- Ensures non-key attributes depend only on the primary key
- Creates lookup tables where necessary
Each normalization step is logged, providing transparency and allowing developers to understand the transformations applied to their schema.
The platform generates beautiful, interactive Entity-Relationship diagrams using Crow's Foot notation:
Features:
- Interactive Pan & Zoom: Navigate large schemas effortlessly
- Visual Differentiation: Color-coded primary keys, foreign keys, and regular attributes
- Cardinality Display: Clear 1:1, 1:N, and M:N relationship indicators
- Export Capabilities: Download diagrams in Draw.io format for further customization
The diagram generation uses Graphviz's DOT language, carefully constructing HTML-like table nodes with proper styling:
// Sophisticated DOT generation with proper escaping
function generateDot(tables, relationships) {
let dot = `digraph ER {
graph [rankdir=LR, splines=polyline, nodesep=0.6];
// ... table and relationship definitions
}`;
return dot;
}The final stage produces production-ready SQL scripts:
- CREATE TABLE statements with proper data types
- Primary Key declarations
- Foreign Key constraints with ON DELETE/ON UPDATE clauses
- Index creation for performance optimization
- Comments for documentation
Users can download the complete SQL file and deploy it immediately to their database servers.
At the heart of the platform lies the GeminiService class, a sophisticated wrapper around Google's Gemini API:
1. User-Specific API Keys
// Each user provides their own Gemini API key
// Stored securely in the settings table
$this->apiKey = $settings['gemini_api_key'];2. Intelligent Retry Mechanism
$maxRetries = 3;
while ($attempt < $maxRetries) {
// Handle API overload gracefully
if ($httpCode === 503) {
sleep(2);
continue;
}
}3. JSON Mode for Structured Output
if ($jsonMode) {
$postData['generationConfig']['response_mime_type'] = 'application/json';
}4. Prompt Engineering Excellence
The system instruction is carefully crafted to ensure consistent, high-quality output:
$systemInstruction = "You are an expert Database Architect.
Your task is to analyze project descriptions and extract structured
Business Rules, Entities, and Attributes. You must strictly follow
3NF normalization principles.";The platform implements multiple security layers:
// Using PDO prepared statements throughout
$stmt = $db->prepare("SELECT * FROM projects WHERE id = ? AND user_id = ?");
$stmt->execute([$project_id, $user_id]);- Session-based authentication
- User-specific data isolation
- CSRF protection mechanisms
|
|
| Login | Register |
- User API keys stored encrypted
- Never exposed in client-side code
- Server-side validation on every request
// Proper HTML escaping
echo htmlspecialchars($rule['rule_statement']);The interface is designed with developer productivity in mind:
1. Status Badges: Clear visual indicators of project progress
<span class="bg-green-100 text-green-700 border-green-200">
✓ Completed
</span>2. Progressive Disclosure: Information revealed as needed
- Collapsed views for table listings
- Expandable rationale for business rules
- Hover tooltips for technical details
3. Loading States: Every async operation provides feedback
btn.innerHTML = `<i class="animate-spin">⟳</i> Processing...`;4. Error Handling: User-friendly error messages
if (!data.success) {
alert('AI Error: ' + data.message);
}Input: "Build an online store with products, customers, orders, and payments"
Output: Fully normalized schema with:
- Customer authentication tables
- Product catalog with categories
- Shopping cart functionality
- Order processing tables
- Payment transaction logs
Input: "Manage books, members, borrowing, and returns with late fees"
Output: Complete database design including:
- Book inventory tables
- Member management
- Transaction history
- Fine calculation tables
Input: "Track patients, doctors, appointments, and medical records"
Output: HIPAA-consideration ready schema with:
- Patient information tables
- Medical staff management
- Appointment scheduling
- Medical record storage
- Tables and columns loaded on demand
- Pagination for large project lists
// Debounced search to reduce API calls
function debounceSearch() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => fetchProjects(1), 300);
}- Composite indexes on frequently queried columns
- Foreign key indexes for join optimization
- Single API call for rule extraction
- Batch processing for normalization steps
- Result caching to avoid redundant calls
Problem: Gemini occasionally returned markdown-wrapped JSON
```json
{"entity": "User"}
**Solution**: Implemented robust JSON cleaning
```php
private function cleanJson($text) {
$text = preg_replace('/^```json\s*/i', '', $text);
$text = preg_replace('/\s*```$/', '', $text);
return trim($text);
}
Problem: Large schemas crashed the browser
Solution: Implemented SVG pan/zoom with viewport optimization
panZoomInstance = svgPanZoom('#er-svg', {
zoomEnabled: true,
fit: true,
center: true
});Problem: AI sometimes missed subtle dependencies
Solution: Multi-pass analysis with explicit dependency checking
- First pass: Obvious violations
- Second pass: Transitive dependency analysis
- Third pass: Validation and confirmation
- This project like MVP version so it's require essential for daily use CRUD operations for each stage to Adjust small changes apart from AI
- PostgreSQL export
- MongoDB schema generation
- SQLite for prototyping
- Schema versioning
- Migration script generation
- Rollback capabilities
- Shared projects
- Comment system for rules
- Approval workflows
- Query optimization suggestions
- Index recommendations based on usage patterns
- Automatic denormalization for read-heavy workloads
- REST API for external tools
- CI/CD pipeline integration
- Direct database deployment
AI Database Architect shows that AI can be used to speed up database design without compromising design quality. The project focuses on making database schema generation more efficient and accessible by automating core design steps.
| Layer | Technologies |
|---|---|
| Frontend | Tailwind CSS, Vanilla JS, Lucide Icons |
| Backend | PHP 8.x, PDO/MySQL |
| AI Engine | Google Gemini 2.5 Flash Lite |
| Visualization | Viz.js (Graphviz), SVG Pan Zoom |
| Architecture | Basic Request & Response Architecure PHP for backend short activations and Frontend Consumes those endpoints |
- PHP 8.0 or higher
- MySQL 5.7 or higher
- Web server (Apache/Nginx)
- Google Gemini API Key
- Clone the repository
- Import the database schema from
instance.sql - Configure database credentials in
config/db.php - Register an account and add your Gemini API key in Settings
- Start designing your database!
This project showcases the intersection of artificial intelligence and traditional database theory, proving that automation and best practices can coexist harmoniously.











