db/heromodels/examples/postgres_example
2025-08-02 11:19:57 +02:00
..
example.rs add postgres example instructions 2025-08-02 11:19:57 +02:00
README.md add postgres example instructions 2025-08-02 11:19:57 +02:00
setup.sh add postgres example instructions 2025-08-02 11:19:57 +02:00

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

  1. Model Creation - Creating User and Comment models with the Hero Models framework
  2. Database Operations - Storing, retrieving, updating, and deleting records
  3. Indexing - Using username and active status indexes for efficient queries
  4. Relationships - Associating comments with users
  5. 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:

  1. Create 4 sample users with different attributes
  2. Display all users retrieved from the database
  3. Demonstrate index-based queries (by username and active status)
  4. Delete a user and show the updated results
  5. Create and associate comments with users
  6. 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