# Models

Models are the foundation of your Prax schema, representing database tables and their structure.

## What is a Model?

A model defines a database table and its columns. Each model generates type-safe Rust code including the struct definition, query builders, and filter functions. Models are the core building block of your Prax schema.

## Model Anatomy

Understanding the structure of a model definition:

#### Field Attributes (@)

- • `@id` - Primary key
- • `@auto` - Auto-increment
- • `@unique` - Unique constraint
- • `@default()` - Default value
- • `@map()` - Column name mapping
- • `@relation()` - Define relations

#### Model Attributes (@@)

- • `@@map()` - Table name mapping
- • `@@id([])` - Composite primary key
- • `@@unique([])` - Composite unique
- • `@@index([])` - Create index
- • `@@schema()` - Database schema

## Complete Model Example

Here's a production-ready User model showcasing common patterns:

## Composite Primary Keys

Use `@@id([fields])` to define composite primary keys. This is common for join tables and multi-tenant schemas.

## Indexes

Indexes improve query performance. Prax supports various index types depending on your database.

Index Type | Use Case | Databases
--- | --- | ---
`B-Tree` | Default, range queries, sorting | All
`Hash` | Equality comparisons only | PostgreSQL, MySQL
`GIN` | Arrays, JSONB, full-text search | PostgreSQL
`GiST` | Geometric data, full-text search | PostgreSQL
`BRIN` | Large tables with sorted data | PostgreSQL

## Soft Delete Pattern

Soft deletes preserve data by marking records as deleted instead of physically removing them. Use a nullable `deletedAt` timestamp field.

## Multi-Tenant Models

Prax supports various multi-tenancy patterns for SaaS applications:

Tip: Row-level tenancy is the simplest to implement. Use Prax's built-in tenant middleware for automatic filtering. See the Middleware documentation for details.

## Documenting Models

Use triple-slash comments (`///`) to document your models and fields. Documentation is preserved in generated code and API schemas.

## Naming Conventions

#### Models

Use singular `PascalCase`. The generated table name will be lowercase plural (unless overridden with `@@map`).

#### Fields

Use `camelCase` for field names. Use `@map()` for snake_case column names if needed.

#### Foreign Keys

Use `modelId` pattern (e.g., `userId`, `postId`).

## Generated Rust Code

Models generate type-safe Rust structs and query builder modules:

## Model Attributes Reference

Attribute | Description | Example
--- | --- | ---
`@@map("name")` | Custom table name in database | `@@map("app_users")`
`@@id([fields])` | Composite primary key | `@@id([tenantId, id])`
`@@unique([fields])` | Composite unique constraint | `@@unique([email, tenantId])`
`@@index([fields])` | Create index on fields | `@@index([status, createdAt])`
`@@schema("name")` | Database schema (PostgreSQL) | `@@schema("analytics")`
`@@ignore` | Exclude from client generation | `@@ignore`