agentsclimarketplace

Postgresql best practices

Skill ulpi-io/plugin-marketplace/plugins/mindrally/skills/postgresql-best-practices

PostgreSQL 18+ comprehensive best practices for enterprise database development. Provides schema architecture patterns, Table API design, PL/pgSQL coding standards, migrations, and data warehousing. USE THIS SKILL WHEN THE USER: - Creates PostgreSQL schemas, tables, functions, procedures, or triggers - Asks about PostgreSQL data types (uuid, text, timestamptz, jsonb, numeric) - Writes PL/pgSQL code and needs naming conventions (l_, in_, io_, co_ prefixes) - Implements Table API pattern (SECURITY DEFINER functions, schema separation) - Sets up database migrations or schema versioning - Needs index optimization, constraint design, or query performance help - Asks about PostgreSQL 18+ features (uuidv7, virtual columns, temporal constraints) - Builds data warehouses with Medallion Architecture (Bronze/Silver/Gold) - Needs data lineage tracking, ETL patterns, or audit logging - Reviews database code for best practices or anti-patterns - Migrates from Oracle PL/SQL to PostgreSQL PL/pgSQL - Sets up CI/CD pipelines for database changes CORE PATTERNS: - Three-schema separation: data (tables) → private (internal) → api (external) - Table API: All access through SECURITY DEFINER functions with SET search_path - Native migration system: Pure PL/pgSQL alternative to Flyway/Liquibase - Trivadis naming: l_ (local), in_ (input), io_ (inout), co_ (constant)From its SKILL.md

Install
npx -y skills add ulpi-io/plugin-marketplace --skill postgresql-best-practices

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

2 things to look at

  • no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
  • 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

13.1 KB, ~2.8k tokens by cl100k_base, as published. Nobody here has run it

PostgreSQL Advanced Best Practices (PostgreSQL 18+)

Architecture at a Glance

                        ┌─── PostgreSQL Database ──────────────────────────────┐
                        │                                                      │
                        │  ┌──────────────────┐    ┌───────────────────────┐   │
                        │  │   api schema      │    │   private schema      │   │
  ┌─────────────┐       │  │──────────────────│    │───────────────────────│   │
  │ Application │─EXECUTE─▶│ get_customer()   │───▶│ set_updated_at()     │   │
  └─────────────┘       │  │ insert_order()   │    │ hash_password()      │   │
        │               │  └────────┬─────────┘    └──────────┬────────────┘   │
        │               │           │                         │                │
        │               │           │ SECURITY DEFINER        │ triggers       │
        │               │           ▼                         ▼                │
        │               │  ┌──────────────────────────────────────────────┐    │
        │               │  │              data schema                     │    │
     BLOCKED            │  │──────────────────────────────────────────────│    │
        │               │  │  customers    orders    ...                  │    │
        └ ─ ─ ─ ✕       │  └──────────────────────────────────────────────┘    │
                        │                                                      │
                        └──────────────────────────────────────────────────────┘

Skill Contents

🚀 Getting Started (Read These First)

DocumentPurpose
quick-reference.mdQUICK LOOKUP - Single-page cheat sheet (print this!)
schema-architecture.mdSTART HERE - Schema separation pattern (data/private/api)
coding-standards-trivadis.mdCoding standards & naming conventions (l_, g_, co_)

📚 Core Reference (Use Daily)

DocumentPurpose
plpgsql-table-api.mdTable API functions, procedures, triggers
schema-naming.mdNaming conventions for all objects
data-types.mdData type selection (UUIDv7, text, timestamptz)
indexes-constraints.mdIndex types, strategies, constraints
migrations.mdNative migration system documentation
anti-patterns.mdCommon mistakes to avoid
checklists-troubleshooting.mdProject checklists & problem solutions

🔧 Advanced Topics (When Needed)

DocumentPurpose
testing-patterns.mdpgTAP unit testing, test factories
performance-tuning.mdEXPLAIN ANALYZE, query optimization, JIT
row-level-security.mdRLS patterns, multi-tenant isolation
jsonb-patterns.mdJSONB indexing, queries, validation
audit-logging.mdGeneric audit triggers, change tracking
bulk-operations.mdCOPY, batch inserts, upserts
session-management.mdSession variables, connection pooling
transaction-patterns.mdIsolation levels, locking, deadlock prevention
full-text-search.mdtsvector, tsquery, ranking, multi-language
partitioning.mdRange, list, hash partitioning strategies
window-functions.mdFrames, ranking, running calculations
time-series.mdTime-series data patterns, BRIN indexes
event-sourcing.mdEvent store, projections, CQRS
queue-patterns.mdJob queues, SKIP LOCKED, LISTEN/NOTIFY
encryption.mdpgcrypto, column encryption, TLS
vector-search.mdpgvector, embeddings, similarity search
postgis-patterns.mdSpatial data, geographic queries

🚀 DevOps & Migration

DocumentPurpose
oracle-migration-guide.mdPL/SQL to PL/pgSQL conversion
cicd-integration.mdGitHub Actions, GitLab CI, Docker
monitoring-observability.mdpg_stat_statements, metrics, alerting
backup-recovery.mdpg_dump, pg_basebackup, PITR
replication-ha.mdStreaming/logical replication, failover

📊 Data Warehousing

DocumentPurpose
data-warehousing-medallion.mdMedallion Architecture - Bronze/Silver/Gold, data lineage, ETL
analytical-queries.mdAnalytical query patterns, OLAP optimization, GROUPING SETS

Executable Scripts

ScriptPurpose
001_install_migration_system.sqlInstall migration system (core functions)
002_migration_runner_helpers.sqlHelper procedures (run_versioned, run_repeatable)
003_example_migrations.sqlExample migration patterns
999_uninstall_migration_system.sqlClean removal of migration system

Core Architecture

Schema Separation Pattern

Application → api schema → data schema
                ↓
            private schema (triggers, helpers)
SchemaContainsAccessPurpose
dataTables, indexesNoneData storage
privateTriggers, helpersNoneInternal logic
apiFunctions, proceduresApplicationsExternal interface
app_auditAudit tablesAdminsChange tracking
app_migrationMigration trackingAdminsSchema versioning

Security Model

All api functions MUST have:

SECURITY DEFINER
SET search_path = data, private, pg_temp

Quick Reference

Create Table Pattern

CREATE TABLE data.{table_name} (
    id              uuid PRIMARY KEY DEFAULT uuidv7(),
    -- columns...
    created_at      timestamptz NOT NULL DEFAULT now(),
    updated_at      timestamptz NOT NULL DEFAULT now()
);

CREATE TRIGGER {table}_bu_updated_trg
    BEFORE UPDATE ON data.{table_name}
    FOR EACH ROW EXECUTE FUNCTION private.set_updated_at();

API Function Pattern

CREATE FUNCTION api.{action}_{entity}(in_param type)
RETURNS TABLE (col1 type, col2 type)
LANGUAGE sql STABLE
SECURITY DEFINER
SET search_path = data, private, pg_temp
AS $$
    SELECT col1, col2 FROM data.{table} WHERE ...;
$$;

API Procedure Pattern

CREATE PROCEDURE api.{action}_{entity}(
    in_param type,
    INOUT io_id uuid DEFAULT NULL
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = data, private, pg_temp
AS $$
BEGIN
    INSERT INTO data.{table} (...) VALUES (...) RETURNING id INTO io_id;
END;
$$;

Migration Pattern

SELECT app_migration.acquire_lock();

CALL app_migration.run_versioned(
    in_version := '001',
    in_description := 'Description',
    in_sql := $mig$ ... $mig$,
    in_rollback_sql := '...'
);

SELECT app_migration.release_lock();

Naming Conventions

Trivadis-Style Variable Prefixes

PrefixTypeExample
l_Local variablel_customer_count
g_Session/global variableg_current_user_id
co_Constantco_max_retries
in_IN parameterin_customer_id
out_OUT parameter (functions only)out_total
io_INOUT parameter (procedures)io_id
c_Cursorc_active_orders
r_Recordr_customer
t_Array/tablet_order_ids
e_Exceptione_not_found

Note: PostgreSQL procedures only support INOUT parameters, not OUT. Use io_ prefix for all procedure output parameters.

Database Objects

ObjectPatternExample
Tablesnake_case, pluralorders, order_items
Columnsnake_casecustomer_id, created_at
Primary Keyidid
Foreign Key{table_singular}_idcustomer_id
Index{table}_{cols}_idxorders_customer_id_idx
Unique{table}_{cols}_keyusers_email_key
Function{action}_{entity}get_customer, select_orders
Procedure{action}_{entity}insert_order, update_status
Trigger{table}_{timing}{event}_trgorders_bu_trg

Data Type Recommendations

UseInstead Of
textchar(n), varchar(n)
numeric(p,s)money, float
timestamptztimestamp
booleaninteger flags
uuidv7()serial, uuid_generate_v4()
GENERATED ALWAYS AS IDENTITYserial, bigserial
jsonbjson, EAV pattern

Critical Anti-Patterns

  1. ❌ Direct table access from applications
  2. ❌ RETURNS SETOF table (exposes all columns)
  3. ❌ Missing SET search_path with SECURITY DEFINER
  4. ❌ timestamp without timezone
  5. ❌ NOT IN with subqueries (use NOT EXISTS)
  6. ❌ BETWEEN with timestamps (use >= AND <)
  7. ❌ Missing indexes on foreign keys
  8. ❌ serial/bigserial (use IDENTITY)
  9. ❌ varchar(n) arbitrary limits (use text)
  10. ❌ SELECT FOR UPDATE without NOWAIT/SKIP LOCKED

PostgreSQL 18+ Features

FeatureUsage
uuidv7()id uuid DEFAULT uuidv7() - timestamp-ordered UUIDs
Virtual generated columnscol type GENERATED ALWAYS AS (expr) - computed at query time
OLD/NEW in RETURNINGUPDATE ... RETURNING OLD.col, NEW.col
Temporal constraintsPRIMARY KEY (id) WITHOUT OVERLAPS
NOT VALID constraintsAdd constraints without full table scan

File Organization

db/
├── migrations/
│   ├── V001__create_schemas.sql
│   ├── V002__create_tables.sql
│   └── repeatable/
│       ├── R__private_triggers.sql
│       └── R__api_functions.sql
├── schemas/
│   ├── data/           # Table definitions
│   ├── private/        # Internal functions
│   └── api/            # External interface
└── seeds/              # Reference data

What ships with it: 98 files

1414.3 KB alongside SKILL.md, 3 of them executable

58 more files not listed here. See all 98 in the repository.

Keep looking

Skills are one crate of 325,949. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.