postgres-patterns — independently scanned and version-tracked by SaferSkills.
SaferSkills independently audited postgres-patterns (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
@rules/sql/optimalize.mdc — it already owns indexing fundamentals, SARGable WHERE, seek/keyset pagination, EXPLAIN, transactions/locking basics, and batch-over-per-row. Do not re-explain those; defer to it. Note it is written for MySQL — translate engine-specific syntax (EXPLAIN ANALYZE, plan flags) to Postgres equivalents here.@skills/mysql-patterns/SKILL.md. It is for designing features. For diagnosing an existing slow query, the closest fit is @skills/mysql-problem-solver/SKILL.md (apply its method; substitute Postgres EXPLAIN/pg_stat_statements).@rules/laravel/laravel.mdc and @rules/laravel/architecture.mdc.@rules/security/backend.md — parameterized queries / Eloquent only, least-privilege DB users, never hardcode credentials.final classes, declare(strict_types=1), Pest tests for any data-access code added.SELECT version();) before using version-specific features — MERGE (15+), covering INCLUDE indexes (11+), and NULLS NOT DISTINCT (15+) are not in older servers.FOR UPDATE SKIP LOCKED, or paginating large result sets by cursor.ON CONFLICT upserts, Row-Level Security for multi-tenancy, or correct timestamptz/numeric typing.Set DB_CONNECTION=pgsql. These topics complement the query-tuning rules; they are not covered there.
Pick the right type once — wrong choices are expensive to migrate later.
Schema::create('orders', function (Blueprint $table): void {
$table->id(); // bigint identity
$table->decimal('amount', 12, 2); // numeric — never float/double for money
$table->timestampTz('placed_at'); // timestamptz — stores UTC instant
$table->jsonb('meta')->default('{}'); // jsonb (binary, indexable), not json
$table->boolean('is_paid')->default(false);
});timestampTz maps to timestamptz: it stores a UTC instant and converts on read. Plain timestamp drops the zone and is a recurring bug source. Set 'timezone' => 'UTC' server-side.numeric/decimal for money and exact values; float/double lose precision.jsonb over json: binary form supports GIN indexing and @>/? operators; plain json only stores text.text has no performance cost over varchar(n) in Postgres — use text unless a length cap is a real constraint.// Eloquent upsert compiles to INSERT ... ON CONFLICT DO UPDATE.
// 2nd arg = conflict target (must be backed by a unique index); 3rd = columns to overwrite.
Product::upsert(
[['sku' => 'A1', 'price' => 10], ['sku' => 'B2', 'price' => 20]],
uniqueBy: ['sku'],
update: ['price'],
);
// Insert, skip rows that violate a unique constraint:
DB::table('tags')->insertOrIgnore([['name' => 'php'], ['name' => 'sql']]);-- Raw equivalent. EXCLUDED = the row that failed to insert.
INSERT INTO products (sku, price) VALUES ('A1', 10)
ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price;upsert() and insertOrIgnore() are bulk single statements and do not fire model events or set timestamps — set them yourself.updateOrCreate() is per-row, fires events, and is race-prone unless a unique index backs the match columns; wrap concurrent use in a transaction retry.B-tree (the default) covers equality/range. Reach for these when the access pattern differs:
-- GIN: jsonb containment and array/full-text membership.
CREATE INDEX idx_orders_meta ON orders USING gin (meta jsonb_path_ops);
-- BRIN: huge, naturally-ordered columns (append-only time series). Tiny index, range scans only.
CREATE INDEX idx_events_created ON events USING brin (created_at);
-- Partial: index only the rows you actually query — smaller, cheaper to maintain.
CREATE INDEX idx_users_active ON users (email) WHERE deleted_at IS NULL;
-- Covering (11+): satisfy a query from the index alone (index-only scan).
CREATE INDEX idx_orders_lookup ON orders (customer_id) INCLUDE (status, amount);// In a Laravel migration, raw index types go through DB::statement.
DB::statement('CREATE INDEX idx_orders_meta ON orders USING gin (meta jsonb_path_ops)');
DB::statement('CREATE INDEX idx_users_active ON users (email) WHERE deleted_at IS NULL');jsonb_path_ops is smaller and faster for @> containment than the default jsonb_ops (which also supports key-existence ?). Pick by the operators you use.WHERE deleted_at IS NULL) is often the highest-leverage index on a soft-deleted table.CREATE INDEX CONCURRENTLY (cannot run inside a transaction — disable the migration's wrapping transaction with public $withinTransaction = false;).Product::where('meta->color', 'red')->get(); // -> meta->>'color' = 'red'
Product::whereJsonContains('meta->tags', 'sale')->get(); // -> meta @> '{"tags":["sale"]}'-> returns jsonb, ->> returns text. Index and compare on ->> (text) for scalar lookups; use the GIN @> containment path for membership.Lets N workers each grab a distinct unlocked row with no contention or double-processing.
$job = DB::transaction(function () {
$row = DB::table('jobs')
->where('status', 'pending')
->orderBy('id')
->lockForUpdate() // FOR UPDATE
->limit(1)
->skipLocked() // SKIP LOCKED — skip rows another worker holds
->first();
if ($row !== null) {
DB::table('jobs')->where('id', $row->id)->update(['status' => 'processing']);
}
return $row;
});skipLocked() makes workers ignore rows already locked instead of blocking — the core primitive for a Postgres-backed work queue.QUEUE_CONNECTION=database driver already uses this internally; hand-roll only for custom claim logic.For large/deep result sets, keyset (cursor) pagination is O(1) per page vs OFFSET's O(n) scan-and-discard.
// Laravel's built-in keyset paginator (opaque cursor over the ORDER BY columns).
Order::orderBy('id')->cursorPaginate(20);-- Raw seek: carry the last row's key forward instead of OFFSET.
SELECT * FROM orders WHERE id > :last_id ORDER BY id LIMIT 20;ORDER BY and be backed by an index (composite for multi-column sorts, including a unique tiebreaker).@rules/sql/optimalize.mdc; this is its Postgres-native form.Enforce per-tenant isolation in the database so a missing WHERE clause cannot leak rows.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::bigint);// Set the session variable per request before any tenant query.
DB::statement('SET app.tenant_id = ?', [$tenantId]);SELECT of current_setting(...) so the planner caches it once per query rather than re-evaluating per row.BYPASSRLS.// config/database.php — 'pgsql' connection
'options' => [
PDO::ATTR_TIMEOUT => 3,
],
// Per-connection statement guards (also settable via 'options' / a session SET):
// statement_timeout, idle_in_transaction_session_timeoutstatement_timeout and idle_in_transaction_session_timeout so a runaway query or stuck transaction cannot hold locks indefinitely.SET) that outlives a transaction.max_connections to (web workers + queue workers + scheduler) × pool; front it with PgBouncer rather than raising max_connections unbounded.EXPLAIN (ANALYZE, BUFFERS) SELECT ...; -- real plan + actual rows + I/O
-- Top time-consuming queries (extension must be enabled):
SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;
-- Dead-tuple bloat / vacuum health:
SELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC;
-- Unindexed foreign keys and blocking locks:
SELECT * FROM pg_stat_activity WHERE wait_event_type = 'Lock';pg_stat_statements (shared_preload_libraries) to find the queries worth tuning.n_dead_tup — high dead-tuple counts mean autovacuum is falling behind, which degrades plans and inflates table size.timestamptz, numeric, and jsonb correctly; money is never a float.EXPLAIN (ANALYZE).ON CONFLICT statements backed by a unique index; queue claims use SKIP LOCKED in a short transaction.BYPASSRLS.statement_timeout is set; Pest tests cover the new data-access paths; no secrets are hardcoded.@skills/mysql-patterns/SKILL.md — the MySQL counterpart to this skill.@skills/mysql-problem-solver/SKILL.md — method for diagnosing an existing slow query (adapt EXPLAIN/pg_stat_statements for Postgres).@skills/redis-patterns/SKILL.md — caching/locking in front of the database.@skills/latency-critical-systems/SKILL.md — when p95 latency on these query paths matters.INSERT ... ON CONFLICT: https://www.postgresql.org/docs/current/sql-insert.html~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.