2.6 KiB
2.6 KiB
PostgreSQL Model Example
This example demonstrates the Hero Models framework's PostgreSQL integration capabilities, showcasing how to create, store, retrieve, and manage models in a PostgreSQL database.
Quick Setup
Automated Setup (Recommended):
./setup.sh
The setup script will automatically:
- Detect your operating system (macOS, Ubuntu/Debian, CentOS/RHEL)
- Install PostgreSQL if not already installed
- Start the PostgreSQL service
- Create the required database user with password
- Test the database connection
- Configure PATH (macOS only)
Manual Setup: If you prefer to set up PostgreSQL manually, the example expects:
- PostgreSQL server running on
localhost:5432
- Username:
postgres
- Password:
test123
What This Example Demonstrates
Core Features
- Model Creation - Creating User and Comment models with the Hero Models framework
- Database Operations - Storing, retrieving, updating, and deleting records
- Indexing - Using username and active status indexes for efficient queries
- Relationships - Associating comments with users
- Connection Management - PostgreSQL connection pooling and configuration
Specific Operations
- User Management: Create users with different attributes (username, email, active status)
- Index Queries: Retrieve users by username and filter by active status
- Data Deletion: Remove users and see the impact on queries
- Comment System: Create comments and associate them with users
- Model Introspection: Display model information and database prefixes
Running the Example
From the heromodels root directory:
cargo run --example postgres_model_example
Expected Output
The example will:
- Create 4 sample users with different attributes
- Display all users retrieved from the database
- Demonstrate index-based queries (by username and active status)
- Delete a user and show the updated results
- Create and associate comments with users
- Display model metadata information
Code Structure
- Database Configuration: Sets up PostgreSQL connection with credentials
- Model Creation: Uses fluent builder pattern for creating User and Comment instances
- Database Operations: Demonstrates CRUD operations using the Hero Models API
- Index Usage: Shows how to query using predefined indexes
- Error Handling: Proper error handling for database operations
Key Technologies
- Hero Models Framework: Core ORM-like functionality
- PostgreSQL: Database backend with connection pooling
- Rust: Type-safe model definitions and operations
- Serde: JSON serialization/deserialization for database storage