---
title: "PostgreSQL Setup"
description: "Complete guide to installing and configuring PostgreSQL for TracerTM development"
---

# PostgreSQL Setup

This guide provides comprehensive instructions for setting up PostgreSQL as the production database for TracerTM. While SQLite is supported for development, PostgreSQL is recommended for production deployments and offers better performance, concurrency, and advanced features.

## Overview

TracerTM uses PostgreSQL with the following components:
- **PostgreSQL 15+**: Core database engine
- **asyncpg**: Async PostgreSQL driver for Python
- **SQLAlchemy 2.0**: ORM with async support
- **Alembic**: Database migration tool
- **pgvector** (optional): Vector extension for AI/ML features

## Prerequisites

- PostgreSQL 15 or higher
- Python 3.12+
- Administrative access to create databases and users

---

## Installation

### macOS

#### Option 1: Homebrew (Recommended)

```bash
# Install PostgreSQL
brew install postgresql@15

# Start PostgreSQL service
brew services start postgresql@15

# Add PostgreSQL to PATH (add to ~/.zshrc or ~/.bashrc)
echo 'export PATH="/opt/homebrew/opt/postgresql@15/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

# Verify installation
psql --version
```

#### Option 2: Postgres.app

1. Download from [https://postgresapp.com/](https://postgresapp.com/)
2. Move Postgres.app to Applications
3. Open Postgres.app and initialize
4. Add to PATH:
   ```bash
   echo 'export PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"' >> ~/.zshrc
   source ~/.zshrc
   ```

### Linux (Ubuntu/Debian)

```bash
# Add PostgreSQL repository
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

# Update and install
sudo apt update
sudo apt install -y postgresql-15 postgresql-contrib-15

# Start PostgreSQL service
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Check status
sudo systemctl status postgresql
```

### Linux (RHEL/CentOS/Fedora)

```bash
# Install repository
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/F-$(rpm -E %fedora)-x86_64/pgdg-fedora-repo-latest.noarch.rpm

# Install PostgreSQL
sudo dnf install -y postgresql15-server postgresql15-contrib

# Initialize database
sudo /usr/pgsql-15/bin/postgresql-15-setup initdb

# Start and enable service
sudo systemctl start postgresql-15
sudo systemctl enable postgresql-15
```

### Windows

#### Option 1: Official Installer

1. Download from [https://www.postgresql.org/download/windows/](https://www.postgresql.org/download/windows/)
2. Run the installer
3. Select components: PostgreSQL Server, pgAdmin 4, Command Line Tools
4. Set password for postgres user
5. Set port (default: 5432)
6. Complete installation

#### Option 2: Chocolatey

```powershell
# Install Chocolatey if not already installed
choco install postgresql15 -y

# Add to PATH
$env:Path += ";C:\Program Files\PostgreSQL\15\bin"
```

### Docker (All Platforms)

```bash
# Pull PostgreSQL image
docker pull postgres:15-alpine

# Run PostgreSQL container
docker run -d \
  --name tracertm-postgres \
  -e POSTGRES_USER=tracertm \
  -e POSTGRES_PASSWORD=tracertm_dev_password \
  -e POSTGRES_DB=tracertm \
  -p 5432:5432 \
  -v tracertm-pgdata:/var/lib/postgresql/data \
  postgres:15-alpine

# Verify container is running
docker ps | grep tracertm-postgres

# Connect to PostgreSQL
docker exec -it tracertm-postgres psql -U tracertm -d tracertm
```

#### Docker Compose (Recommended)

Create `docker-compose.yml`:

```yaml
version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: tracertm-postgres
    environment:
      POSTGRES_USER: tracertm
      POSTGRES_PASSWORD: tracertm_dev_password
      POSTGRES_DB: tracertm
      POSTGRES_INITDB_ARGS: "-E UTF8 --locale=en_US.UTF-8"
    ports:
      - "5432:5432"
    volumes:
      - tracertm-pgdata:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U tracertm"]
      interval: 10s
      timeout: 5s
      retries: 5
    restart: unless-stopped

volumes:
  tracertm-pgdata:
    driver: local
```

Start the container:

```bash
docker-compose up -d postgres
```

---

## Database Creation and Configuration

### Create TracerTM Database

#### Method 1: Using psql

```bash
# Connect as postgres superuser
sudo -u postgres psql

# Or on macOS (Homebrew)
psql postgres

# Create database
CREATE DATABASE tracertm
    WITH
    OWNER = postgres
    ENCODING = 'UTF8'
    LC_COLLATE = 'en_US.UTF-8'
    LC_CTYPE = 'en_US.UTF-8'
    TEMPLATE = template0;

# Verify database creation
\l tracertm

# Exit psql
\q
```

#### Method 2: Using createdb Command

```bash
# Create database with specific options
createdb tracertm \
  --owner=postgres \
  --encoding=UTF8 \
  --locale=en_US.UTF-8 \
  --template=template0

# Verify
psql -l | grep tracertm
```

### Create Users and Permissions

```bash
# Connect to PostgreSQL
psql postgres

# Create application user
CREATE USER tracertm_app WITH PASSWORD 'secure_password_here';

# Create read-only user (for reporting/analytics)
CREATE USER tracertm_readonly WITH PASSWORD 'readonly_password_here';

# Grant privileges to application user
GRANT ALL PRIVILEGES ON DATABASE tracertm TO tracertm_app;

# Connect to tracertm database
\c tracertm

# Grant schema privileges
GRANT ALL PRIVILEGES ON SCHEMA public TO tracertm_app;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO tracertm_app;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO tracertm_app;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO tracertm_app;

# Set default privileges for future objects
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO tracertm_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO tracertm_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO tracertm_app;

# Configure read-only user
GRANT CONNECT ON DATABASE tracertm TO tracertm_readonly;
GRANT USAGE ON SCHEMA public TO tracertm_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO tracertm_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO tracertm_readonly;

# Verify permissions
\du
```

### Configure PostgreSQL Authentication

Edit `pg_hba.conf`:

```bash
# Find pg_hba.conf location
psql -U postgres -c 'SHOW hba_file'

# Edit the file (macOS Homebrew example)
sudo nano /opt/homebrew/var/postgresql@15/pg_hba.conf

# Or Ubuntu/Debian
sudo nano /etc/postgresql/15/main/pg_hba.conf
```

Add authentication rules:

```
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# Local connections
local   all             postgres                                peer
local   all             tracertm_app                            md5
local   tracertm        all                                     md5

# IPv4 local connections
host    all             all             127.0.0.1/32            md5
host    tracertm        tracertm_app    127.0.0.1/32            md5
host    tracertm        tracertm_readonly 127.0.0.1/32          md5

# IPv6 local connections
host    all             all             ::1/128                 md5
```

Reload PostgreSQL configuration:

```bash
# macOS (Homebrew)
brew services restart postgresql@15

# Linux (systemd)
sudo systemctl reload postgresql

# Or using pg_ctl
pg_ctl reload -D /path/to/data/directory
```

---

## Connection String Configuration

### Environment Variables

Create or update `.env` file in the project root:

```bash
# Development (local PostgreSQL)
TRACERTM_DATABASE__URL=postgresql://tracertm_app:secure_password_here@localhost:5432/tracertm

# Development (Docker)
TRACERTM_DATABASE__URL=postgresql://tracertm:tracertm_dev_password@localhost:5432/tracertm

# Production example
TRACERTM_DATABASE__URL=postgresql://tracertm_app:${DB_PASSWORD}@db.example.com:5432/tracertm

# Additional database settings
TRACERTM_DATABASE__ECHO=false
TRACERTM_DATABASE__POOL_SIZE=10
TRACERTM_DATABASE__MAX_OVERFLOW=20
```

### Connection String Format

```
postgresql://[user]:[password]@[host]:[port]/[database]?[options]
```

Components:
- **user**: Database username (e.g., `tracertm_app`)
- **password**: User password (URL-encoded if contains special characters)
- **host**: Database server hostname or IP (e.g., `localhost`, `127.0.0.1`)
- **port**: PostgreSQL port (default: `5432`)
- **database**: Database name (e.g., `tracertm`)
- **options**: Query parameters (e.g., `sslmode=require`)

### Connection String Examples

```bash
# Local development
postgresql://tracertm_app:password@localhost:5432/tracertm

# With SSL
postgresql://tracertm_app:password@db.example.com:5432/tracertm?sslmode=require

# Unix socket
postgresql://tracertm_app:password@/tracertm?host=/var/run/postgresql

# Multiple hosts (failover)
postgresql://tracertm_app:password@host1:5432,host2:5432/tracertm

# AWS RDS
postgresql://tracertm_app:password@tracertm.abc123.us-east-1.rds.amazonaws.com:5432/tracertm?sslmode=require

# Google Cloud SQL
postgresql://tracertm_app:password@/tracertm?host=/cloudsql/project:region:instance
```

### Test Connection

```bash
# Using psql
psql "postgresql://tracertm_app:password@localhost:5432/tracertm"

# Or with separate parameters
psql -h localhost -p 5432 -U tracertm_app -d tracertm

# Test from Python
python -c "from tracertm.core.database import get_engine; import asyncio; asyncio.run(get_engine().connect())"
```

---

## pgvector Extension Setup

pgvector enables vector similarity search for AI/ML features like semantic search and embeddings.

### Install pgvector Extension

#### macOS (Homebrew)

```bash
# Install pgvector
brew install pgvector

# Verify installation
psql tracertm -c "SELECT * FROM pg_available_extensions WHERE name = 'vector';"
```

#### Linux (Ubuntu/Debian)

```bash
# Install build dependencies
sudo apt install -y postgresql-server-dev-15 build-essential git

# Clone and build pgvector
git clone https://github.com/pgvector/pgvector.git
cd pgvector
make
sudo make install

# Verify
psql tracertm -c "SELECT * FROM pg_available_extensions WHERE name = 'vector';"
```

#### Docker

Update `docker-compose.yml` to use pgvector image:

```yaml
services:
  postgres:
    image: pgvector/pgvector:pg15
    # ... rest of configuration
```

### Enable pgvector in Database

```sql
-- Connect to tracertm database
\c tracertm

-- Create extension
CREATE EXTENSION IF NOT EXISTS vector;

-- Verify extension
\dx vector

-- Test vector operations
SELECT '[1,2,3]'::vector;
```

### Using pgvector in TracerTM

Example schema for embeddings:

```sql
-- Create embeddings table
CREATE TABLE item_embeddings (
    id SERIAL PRIMARY KEY,
    item_id INTEGER NOT NULL,
    embedding vector(1536),  -- OpenAI ada-002 dimension
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE CASCADE
);

-- Create index for similarity search
CREATE INDEX ON item_embeddings USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);

-- Example similarity query
SELECT item_id, embedding <=> '[0.1, 0.2, ...]'::vector AS distance
FROM item_embeddings
ORDER BY distance
LIMIT 10;
```

---

## Schema Initialization

TracerTM uses SQLAlchemy declarative models to define the database schema.

### Initialize Schema

```bash
# Using Python API
python -c "
from tracertm.core.database import init_db
import asyncio
asyncio.run(init_db())
"

# Or create a script: scripts/init_db.py
cat > scripts/init_db.py << 'EOF'
#!/usr/bin/env python3
"""Initialize TracerTM database schema."""
import asyncio
from tracertm.core.database import init_db

async def main():
    print("Initializing database schema...")
    await init_db()
    print("Database schema created successfully!")

if __name__ == "__main__":
    asyncio.run(main())
EOF

chmod +x scripts/init_db.py
python scripts/init_db.py
```

### Verify Schema

```sql
-- Connect to database
psql -U tracertm_app -d tracertm

-- List all tables
\dt

-- Describe a table
\d items

-- Show all schemas
\dn+

-- List all indexes
\di

-- Show table sizes
SELECT
    schemaname,
    tablename,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) AS size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
```

---

## Running Migrations with Alembic

While TracerTM currently uses SQLAlchemy's `create_all()` for schema creation, Alembic is available for production migrations.

### Initialize Alembic (if not exists)

```bash
# Initialize Alembic in project
alembic init alembic

# Directory structure created:
# alembic/
#   ├── versions/
#   ├── env.py
#   ├── README
#   └── script.py.mako
# alembic.ini
```

### Configure Alembic

Edit `alembic.ini`:

```ini
[alembic]
script_location = alembic
sqlalchemy.url = postgresql://tracertm_app:password@localhost:5432/tracertm

# Or use environment variable
# sqlalchemy.url =

[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
```

Edit `alembic/env.py` to use TracerTM models:

```python
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
import os

# Import TracerTM models
from tracertm.models.base import Base
from tracertm.core.config import get_config

# Alembic Config object
config = context.config

# Get database URL from environment
tracertm_config = get_config()
config.set_main_option("sqlalchemy.url", tracertm_config.database.url)

# Interpret the config file for Python logging
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# Set target metadata
target_metadata = Base.metadata

# ... rest of env.py
```

### Create Migration

```bash
# Auto-generate migration from model changes
alembic revision --autogenerate -m "Initial schema"

# Create empty migration
alembic revision -m "Add custom indexes"

# Edit migration file in alembic/versions/
```

### Apply Migrations

```bash
# Show current migration status
alembic current

# Show migration history
alembic history --verbose

# Upgrade to latest version
alembic upgrade head

# Upgrade to specific revision
alembic upgrade abc123

# Downgrade one version
alembic downgrade -1

# Downgrade to specific revision
alembic downgrade abc123

# Show SQL without executing
alembic upgrade head --sql
```

---

## Database Backup and Restore

### Backup Database

#### Using pg_dump

```bash
# Full database backup (custom format, compressed)
pg_dump -U tracertm_app -d tracertm -F c -f tracertm_backup.dump

# Plain SQL format
pg_dump -U tracertm_app -d tracertm -f tracertm_backup.sql

# Compressed SQL
pg_dump -U tracertm_app -d tracertm | gzip > tracertm_backup.sql.gz

# Schema only
pg_dump -U tracertm_app -d tracertm --schema-only -f tracertm_schema.sql

# Data only
pg_dump -U tracertm_app -d tracertm --data-only -f tracertm_data.sql

# Specific tables
pg_dump -U tracertm_app -d tracertm -t items -t links -f tracertm_partial.sql

# With timestamp
pg_dump -U tracertm_app -d tracertm -F c -f "tracertm_backup_$(date +%Y%m%d_%H%M%S).dump"
```

#### Automated Backup Script

```bash
#!/bin/bash
# scripts/backup_db.sh

BACKUP_DIR="/path/to/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/tracertm_$TIMESTAMP.dump"
RETENTION_DAYS=30

# Create backup
pg_dump -U tracertm_app -d tracertm -F c -f "$BACKUP_FILE"

# Compress
gzip "$BACKUP_FILE"

# Remove old backups
find "$BACKUP_DIR" -name "tracertm_*.dump.gz" -mtime +$RETENTION_DAYS -delete

echo "Backup completed: $BACKUP_FILE.gz"
```

#### Schedule with cron

```bash
# Edit crontab
crontab -e

# Add daily backup at 2 AM
0 2 * * * /path/to/scripts/backup_db.sh >> /var/log/tracertm_backup.log 2>&1
```

### Restore Database

```bash
# Drop existing database (caution!)
dropdb -U postgres tracertm

# Create new database
createdb -U postgres tracertm

# Restore from custom format
pg_restore -U tracertm_app -d tracertm tracertm_backup.dump

# Restore from SQL file
psql -U tracertm_app -d tracertm -f tracertm_backup.sql

# Restore from compressed SQL
gunzip -c tracertm_backup.sql.gz | psql -U tracertm_app -d tracertm

# Restore specific tables only
pg_restore -U tracertm_app -d tracertm -t items -t links tracertm_backup.dump

# Restore with verbose output
pg_restore -U tracertm_app -d tracertm -v tracertm_backup.dump
```

---

## Common PostgreSQL Issues

### Connection Refused

**Symptom:** `psql: error: connection to server at "localhost" (::1), port 5432 failed: Connection refused`

**Solutions:**

```bash
# Check if PostgreSQL is running
sudo systemctl status postgresql  # Linux
brew services list               # macOS

# Start PostgreSQL
sudo systemctl start postgresql  # Linux
brew services start postgresql@15  # macOS

# Check listening port
sudo lsof -i :5432
# or
sudo netstat -tlnp | grep 5432

# Check PostgreSQL logs
tail -f /var/log/postgresql/postgresql-15-main.log  # Linux
tail -f /opt/homebrew/var/log/postgresql@15.log    # macOS
```

### Authentication Failed

**Symptom:** `FATAL: password authentication failed for user "tracertm_app"`

**Solutions:**

```bash
# Reset password
psql -U postgres
ALTER USER tracertm_app WITH PASSWORD 'new_password';

# Check pg_hba.conf authentication method
# Change from 'peer' to 'md5' if needed

# Verify connection string
psql "postgresql://tracertm_app:password@localhost:5432/tracertm"
```

### Peer Authentication Failed

**Symptom:** `FATAL: Peer authentication failed for user "tracertm_app"`

**Solution:** Edit `pg_hba.conf` and change authentication method:

```
# Before
local   all   all   peer

# After
local   all   all   md5
```

Reload PostgreSQL: `sudo systemctl reload postgresql`

### Database Does Not Exist

**Symptom:** `FATAL: database "tracertm" does not exist`

**Solution:**

```bash
# Create database
createdb -U postgres tracertm

# Or in psql
psql -U postgres -c "CREATE DATABASE tracertm;"
```

### Permission Denied

**Symptom:** `ERROR: permission denied for table items`

**Solution:**

```sql
-- Connect as postgres
psql -U postgres tracertm

-- Grant permissions
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO tracertm_app;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO tracertm_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO tracertm_app;
```

### Too Many Connections

**Symptom:** `FATAL: sorry, too many clients already`

**Solution:**

```bash
# Check current connections
psql -U postgres -c "SELECT count(*) FROM pg_stat_activity;"

# Increase max_connections in postgresql.conf
sudo nano /etc/postgresql/15/main/postgresql.conf

# Change:
max_connections = 200  # default is 100

# Restart PostgreSQL
sudo systemctl restart postgresql
```

### Slow Queries

**Solution:**

```sql
-- Enable query logging in postgresql.conf
log_min_duration_statement = 1000  -- log queries > 1 second

-- Check slow queries
SELECT
    pid,
    now() - pg_stat_activity.query_start AS duration,
    query,
    state
FROM pg_stat_activity
WHERE state != 'idle'
ORDER BY duration DESC;

-- Kill slow query
SELECT pg_terminate_backend(pid);
```

---

## Performance Tuning for Development

### PostgreSQL Configuration

Edit `postgresql.conf`:

```bash
# Find postgresql.conf location
psql -U postgres -c 'SHOW config_file'

# Edit configuration
sudo nano /etc/postgresql/15/main/postgresql.conf
```

Recommended development settings:

```ini
# Memory Settings
shared_buffers = 256MB              # 25% of RAM for dedicated server
effective_cache_size = 1GB          # 50-75% of RAM
work_mem = 16MB                     # Per operation
maintenance_work_mem = 128MB        # For VACUUM, CREATE INDEX

# Connections
max_connections = 100               # Adjust based on needs

# Query Planning
random_page_cost = 1.1              # For SSD (default: 4.0)
effective_io_concurrency = 200      # For SSD (default: 1)

# Write-Ahead Logging (WAL)
wal_buffers = 16MB
checkpoint_completion_target = 0.9

# Logging (for development)
log_min_duration_statement = 500    # Log queries > 500ms
log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h '
log_checkpoints = on
log_connections = on
log_disconnections = on
log_lock_waits = on
```

Restart PostgreSQL after changes:

```bash
sudo systemctl restart postgresql
```

### Create Indexes

```sql
-- Example indexes for TracerTM
CREATE INDEX idx_items_project_id ON items(project_id);
CREATE INDEX idx_items_type ON items(type);
CREATE INDEX idx_items_status ON items(status);
CREATE INDEX idx_links_source_target ON links(source_id, target_id);
CREATE INDEX idx_items_created_at ON items(created_at DESC);

-- Full-text search index
CREATE INDEX idx_items_title_fts ON items USING GIN(to_tsvector('english', title));
CREATE INDEX idx_items_description_fts ON items USING GIN(to_tsvector('english', description));

-- Analyze tables
ANALYZE items;
ANALYZE links;
```

### Maintenance Commands

```sql
-- Vacuum (reclaim space and update statistics)
VACUUM ANALYZE;

-- Reindex
REINDEX DATABASE tracertm;

-- Check table bloat
SELECT
    schemaname,
    tablename,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) AS size,
    n_live_tup,
    n_dead_tup,
    ROUND(n_dead_tup * 100.0 / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_ratio
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC;
```

---

## GUI Tools

### pgAdmin 4

**Installation:**

```bash
# macOS
brew install --cask pgadmin4

# Ubuntu/Debian
curl -fsS https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo gpg --dearmor -o /usr/share/keyrings/packages-pgadmin-org.gpg
sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list'
sudo apt update
sudo apt install pgadmin4-desktop

# Windows
# Download from https://www.pgadmin.org/download/windows/
```

**Configuration:**

1. Open pgAdmin 4
2. Right-click "Servers" > "Register" > "Server"
3. General tab: Name = "TracerTM Dev"
4. Connection tab:
   - Host: `localhost`
   - Port: `5432`
   - Database: `tracertm`
   - Username: `tracertm_app`
   - Password: `your_password`
   - Save password: Check
5. Click "Save"

### DBeaver

**Installation:**

```bash
# macOS
brew install --cask dbeaver-community

# Ubuntu/Debian
wget https://dbeaver.io/files/dbeaver-ce_latest_amd64.deb
sudo dpkg -i dbeaver-ce_latest_amd64.deb

# Windows
# Download from https://dbeaver.io/download/
```

**Configuration:**

1. Open DBeaver
2. Database > New Database Connection
3. Select "PostgreSQL"
4. Enter connection details:
   - Host: `localhost`
   - Port: `5432`
   - Database: `tracertm`
   - Username: `tracertm_app`
   - Password: `your_password`
5. Test Connection
6. Click "Finish"

### Command-Line Tools

#### psql (Interactive Terminal)

```bash
# Connect to database
psql -U tracertm_app -d tracertm

# Common psql commands
\l          # List databases
\c dbname   # Connect to database
\dt         # List tables
\d table    # Describe table
\du         # List users
\dp         # List permissions
\timing     # Show query execution time
\x          # Toggle expanded output
\e          # Open query in editor
\q          # Quit

# Execute SQL file
\i /path/to/file.sql

# Output to file
\o output.txt
SELECT * FROM items;
\o
```

#### pgcli (Enhanced psql)

```bash
# Install
pip install pgcli

# Connect
pgcli postgresql://tracertm_app:password@localhost:5432/tracertm

# Features: auto-completion, syntax highlighting, multi-line editing
```

---

## Next Steps

- [Redis Setup](/docs/development/setup/redis-setup) - Configure caching and session storage
- [Environment Configuration](/docs/development/setup/environment-config) - Set up environment variables
- [Running Tests](/docs/development/testing/running-tests) - Test database connectivity
- [API Development](/docs/development/api/overview) - Build API endpoints with database access

## Additional Resources

- [PostgreSQL Documentation](https://www.postgresql.org/docs/15/)
- [SQLAlchemy Async Tutorial](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html)
- [Alembic Tutorial](https://alembic.sqlalchemy.org/en/latest/tutorial.html)
- [pgvector Documentation](https://github.com/pgvector/pgvector)
- [PostgreSQL Performance Tuning](https://wiki.postgresql.org/wiki/Performance_Optimization)
