Skip to main content

PostgreSQL schema management toolkit with YAML-based definitions

Project description

pg-schema-toolkit

A self-contained PostgreSQL schema management toolkit with YAML-based definitions, automatic audit tables, and intelligent schema change tracking.

Philosophy: Schema-first design. Define your database structure in YAML, generate clean DDL, track changes, and maintain complete audit trails.


๐Ÿš€ Quick Start

# Install
pip install -e .

# Optional: Install with tab completion support
pip install -e ".[completion]"
activate-global-python-argcomplete --user
# Then restart your shell or source ~/.bashrc

# Validate a schema
pg-schema validate examples/schemas/users.yaml

# Generate DDL
pg-schema generate examples/schemas/users.yaml -o create_users.sql

# Compare YAML with database
pg-schema diff examples/schemas/users.yaml

# Generate schema change SQL
pg-schema generate-change examples/schemas/users.yaml \
    -m "Add status column" \
    -o schema_changes/002_add_status.sql

# Apply change to database
psql < schema_changes/002_add_status.sql

๐Ÿ“ฆ Core Features

  • โœ… YAML Schema Definitions - Define tables declaratively
  • โœ… Schema Inheritance - Reusable templates and field types
  • โœ… DDL Generation - Generate clean CREATE TABLE statements
  • โœ… Automatic Audit Tables - Track all changes with triggers
  • โœ… Database Introspection - Read current database schema
  • โœ… Schema Diffing - Compare YAML vs. database state
  • โœ… Change Generation - Generate ALTER TABLE statements
  • โœ… Safety Classification - SAFE/WARNING/DESTRUCTIVE labels
  • โœ… CLI Interface - Complete command-line tooling

๐Ÿ”„ Schema Change Workflow

Philosophy: Generate-First with Optional Execution

Core Principle: All schema changes are SQL files. Never execute DDL without a reviewed file.

Complete Workflow

1. Modify YAML Schema

# examples/schemas/users.yaml
tables:
  - name: users
    columns:
      - name: status
        type: TEXT
        default: "'active'"

2. Generate Change File

pg-schema generate-change examples/schemas/users.yaml \
  -m "Add status column" \
  -o schema_changes/005_add_status.sql

3. Review Generated SQL

cat schema_changes/005_add_status.sql

4. Apply Change

# Manual (recommended for production)
psql < schema_changes/005_add_status.sql

Safety Classification

SAFE โœ“

  • Add nullable column
  • Add index
  • Add column with default

WARNING โš 

  • Add NOT NULL column
  • Change column type
  • Type conversions

DESTRUCTIVE โœ—

  • Drop column
  • Drop table
  • Data loss possible

๐Ÿ—๏ธ Example Schema

# examples/schemas/users.yaml
schema: public
extends: base_definitions.yaml
description: "User accounts with full audit history"

tables:
  - name: users
    extends: audited_table  # Gets audit fields + audit table + trigger
    description: "Application users"
    
    columns:
      - name: email
        field_type: email
        description: "User email address"
      
      - name: username
        field_type: slug
        description: "Unique username"
      
      - name: full_name
        field_type: name
        description: "User's full name"
      
      - name: is_active
        field_type: is_active
        description: "Account active status"
    
    indexes:
      - columns: [email]
      - columns: [username]
      - columns: [is_active]
        where: "deleted_at IS NULL"

Generates:

  • public.users table with audit fields
  • public.users_audr audit table
  • audit_users() trigger function
  • audit_users_trigger trigger
  • All indexes and constraints

๐Ÿ”ง Configuration

Uses standard PostgreSQL environment variables:

export PGHOST=localhost
export PGPORT=5432
export PGDATABASE=mydb
export PGUSER=myuser
# Password from ~/.pgpass (secure)

Optional:

export DB_SCHEMA=public              # Default schema
export DB_CONNECT_TIMEOUT=10         # Connection timeout (seconds)
export ENVIRONMENT=development       # Environment name

๐ŸŽฏ Usage Patterns

1. As Command-Line Tool

# Validate schema
pg-schema validate examples/schemas/users.yaml

# Generate DDL
pg-schema generate examples/schemas/users.yaml -o /tmp/create_users.sql

# Apply to database
psql -f /tmp/create_users.sql

2. As Python Library

from pg_schema_toolkit import SchemaLoader, DDLGenerator, load_config_from_env
import psycopg2

# Load schema
loader = SchemaLoader()
schema = loader.load_schema('examples/schemas/users.yaml')

# Generate DDL
generator = DDLGenerator(schema)
ddl = generator.generate_all()

# Connect to database
config = load_config_from_env()
conn = psycopg2.connect(**config.psycopg2_params)

๐Ÿ“‚ Project Structure

pg-schema-toolkit/
โ”œโ”€โ”€ pg_schema_toolkit/          # Main package
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ cli.py                  # Command-line interface
โ”‚   โ””โ”€โ”€ scripts/                # Core functionality
โ”‚       โ”œโ”€โ”€ schema_loader.py    # Load and parse YAML
โ”‚       โ”œโ”€โ”€ ddl_generator.py    # Generate CREATE TABLE
โ”‚       โ”œโ”€โ”€ audit_generator.py  # Generate audit infrastructure
โ”‚       โ”œโ”€โ”€ introspector.py     # Read database schema
โ”‚       โ”œโ”€โ”€ differ.py           # Compare YAML vs database
โ”‚       โ”œโ”€โ”€ change_generator.py # Generate ALTER TABLE
โ”‚       โ””โ”€โ”€ db_config.py        # Database connection
โ”œโ”€โ”€ examples/
โ”‚   โ””โ”€โ”€ schemas/                # Example schemas
โ”‚       โ”œโ”€โ”€ base_definitions.yaml
โ”‚       โ”œโ”€โ”€ users.yaml
โ”‚       โ””โ”€โ”€ products.yaml
โ”œโ”€โ”€ pyproject.toml              # Package configuration
โ”œโ”€โ”€ setup.py                    # Setup script
โ”œโ”€โ”€ requirements.txt            # Dependencies
โ””โ”€โ”€ README.md                   # This file

๐Ÿ” Audit Table System

Every table marked with generate_audit_table: true automatically gets:

  • {table_name}_audr audit table
  • Trigger function to capture INSERT/UPDATE/DELETE
  • Complete change history with timestamps, users, and operation types
  • Indexes on audit_row_id, audit_timestamp, audit_operation, audit_user

Example

-- Main table
INSERT INTO users (email, username) VALUES ('user@example.com', 'john');

-- Audit table automatically populated
SELECT * FROM users_audr;
-- audit_id | audit_timestamp | audit_user | audit_operation | audit_row_id | email | username
-- 1        | 2026-01-17...   | myuser     | INSERT          | 1            | user@... | john

-- Update tracked
UPDATE users SET username = 'john_doe' WHERE id = 1;

SELECT * FROM users_audr ORDER BY audit_id;
-- Shows both INSERT and UPDATE operations with full snapshots

๐Ÿ“š Best Practices

Schema Changes

  1. Small, Incremental Changes

    • Prefer many small changes over one large change
  2. Always Use Transactions

    • Wrap related changes in BEGIN/COMMIT
  3. Test in Staging First

    • Never apply untested changes to production
  4. Backwards Compatibility

    • Add nullable column first
    • Backfill data
    • Then make NOT NULL
  5. Version Control

    git add schema_changes/005_add_field.sql
    git commit -m "Schema change: add status field"
    

Development Workflow

  1. Edit YAML schema - Make changes declaratively
  2. Generate change - Tool creates SQL file
  3. Review SQL - Always review before applying
  4. Test locally - Apply to dev database
  5. Commit SQL file - Track in git
  6. Apply to staging - Test in staging environment
  7. Apply to production - Manual execution recommended

๐Ÿšฆ Status

Production Ready โœ…

  • Comprehensive feature set
  • Clean, maintainable code
  • Schema-first design philosophy
  • Safe for production use

๐Ÿ“– CLI Reference

# Validate schema
pg-schema validate <schema_file>

# Generate DDL
pg-schema generate <schema_file> [-o output.sql]

# Show database info
pg-schema info

# Compare with database
pg-schema diff <schema_file>

# Generate change file
pg-schema generate-change <schema_file> -m "message" [-o output.sql]

๐ŸŽ“ Why Schema-First?

Data Integrity = Business Rules

  • Constraints enforced at DB level, not app level
  • Single source of truth
  • Multi-client safety
  • Audit from day one

For ERP Systems:

  • Financial/regulatory data needs complete history
  • Can't retrofit audit tables later
  • Database enforces rules even with multiple apps
  • Future integrations are safe

๐Ÿ“„ License

MIT License


Questions? Check the examples! The examples/schemas/ directory contains working examples of every feature.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pg_schema_toolkit-0.1.0.tar.gz (30.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pg_schema_toolkit-0.1.0-py3-none-any.whl (29.5 kB view details)

Uploaded Python 3

File details

Details for the file pg_schema_toolkit-0.1.0.tar.gz.

File metadata

  • Download URL: pg_schema_toolkit-0.1.0.tar.gz
  • Upload date:
  • Size: 30.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for pg_schema_toolkit-0.1.0.tar.gz
Algorithm Hash digest
SHA256 767cad11feed337ceeee062171f79fd9fe1228d66b76e8eddf3a0d5d6905b48c
MD5 8d6bd97058173d36182dc4403784869c
BLAKE2b-256 cb8e7668a448674f9215c00f0b1ebbfc0a9d6b21c8acaae28e6cdf0f29336b28

See more details on using hashes here.

File details

Details for the file pg_schema_toolkit-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pg_schema_toolkit-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f2fdf9502f6c24bad4bf75d0ea3444e248b69f7e4cf30dbf3b86036bc0c69cd3
MD5 052f96b8d87e001c63192432f3f53175
BLAKE2b-256 55c55d8685e96ad57b5909aa6de2cf527c772af68049db2fda3a212d06267a99

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page