惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Microsoft Azure Blog
Microsoft Azure Blog
N
Netflix TechBlog - Medium
M
MIT News - Artificial intelligence
GbyAI
GbyAI
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园_首页
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
L
LangChain Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
Y
Y Combinator Blog
L
LINUX DO - 热门话题
Project Zero
Project Zero
罗磊的独立博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MongoDB | Blog
MongoDB | Blog
Spread Privacy
Spread Privacy
S
Schneier on Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
J
Java Code Geeks
P
Palo Alto Networks Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - Franky
T
Threat Research - Cisco Blogs
D
Docker
Hugging Face - Blog
Hugging Face - Blog
S
Securelist
Google DeepMind News
Google DeepMind News
T
The Exploit Database - CXSecurity.com
L
Lohrmann on Cybersecurity
月光博客
月光博客
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
V
Visual Studio Blog
AWS News Blog
AWS News Blog
I
Intezer
T
The Blog of Author Tim Ferriss
P
Privacy International News Feed
T
Tor Project blog
F
Full Disclosure
P
Proofpoint News Feed
SecWiki News
SecWiki News
H
Heimdal Security Blog
Help Net Security
Help Net Security
The Hacker News
The Hacker News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
PostgreSQL centric - Planetary Architecture
Ryo Suwito · 2026-05-18 · via DEV Community

Product Requirements Document

PostgreSQL is not the persistence layer. It is the application. Everything else is orbit.


1. Vision

Modern web stacks treat the database as a dumb filing cabinet at the end of a long chain — request → router → controller → service → ORM → DB. Business logic is smeared across every layer. Security is enforced in the app. Permissions live in middleware. Mutations go through serializers. The database just executes INSERT and stays quiet.

Planetary Architecture inverts this.

PostgreSQL is the sun. Every other component — the admin dashboard, the HTTP adapter, the frontend, the external services — orbits it. Business logic, authorization, validation, transformation, and auditing all live inside Postgres. Downstream layers are deliberately dumb: they render, they route, they receive webhooks. They do not own logic.

The platform — django-pg-planetary — is the control plane that makes this architecture operable without writing a single line of SQL. It extends Django admin into a full database operations dashboard, serving every persona involved in building and running a Planetary stack.


2. The Stack

┌─────────────────────────────────────────────────────────────┐
│                      CONTROL PLANE                          │
│         django-pg-planetary (Django Admin Extension)        │
│         Karen · Bob · Senior Dev — one unified dashboard    │
└──────────────────────────┬──────────────────────────────────┘
                           │  DDL only · metadata only
                           │  never raw table data
┌──────────────────────────▼──────────────────────────────────┐
│                   ☀️  POSTGRESQL (the app)                   │
│                                                             │
│  raw tables      — superadmin only, REVOKE ALL on everyone  │
│  views           — DTOs, redacted, role-scoped              │
│  INSTEAD OF      — the only way CUD ever happens            │
│  functions       — business logic, overloaded by signature  │
│  RLS policies    — authorization at the row level           │
│  triggers        — mutations, audits, notifications         │
│  types/domains   — validated, reusable data shapes          │
│  FDW             — forensic audit to separate DB            │
│  pg_notify       — async event emission                     │
└────────┬────────────────────────────────────────────────────┘
         │                              │
         │ pg_notify / pg_net           │ SQL over HTTP
         │                  ┌───────────▼──────────┐
         │                  │       PostgREST       │
         │                  │   dumb HTTP adapter   │
         │                  │   exposes views +     │
         │                  │   functions as REST   │
         │                  └───────────┬──────────┘
         │                              │ REST + JWT
         │                  ┌───────────▼──────────┐
         │                  │     Next.js BFF       │
         │                  │  renders · consumes   │
         │                  │  zero business logic  │
         │                  └───────────┬──────────┘
         │                              │
┌────────▼──────────────────────────────▼──────────────────────┐
│                   SERVICES (dumb, isolated)                   │
│     pdf-export · email · payment · sms · storage · etc.      │
│     receive payload · do one thing · return result           │
│     know nothing about the DB schema                         │
└──────────────────────────────────────────────────────────────┘
         │
┌────────▼──────────────────────────────────────────────────────┐
│                    AUDIT DB (FDW shadow)                       │
│     separate server · append-only · forensic isolation        │
│     full before/after JSON trail per row per operation        │
└────────────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode


3. Personas

Karen — Business Operations

Uses Django admin to browse and manage data rows. Her experience is unchanged from standard Django admin. She interacts with views only — never raw tables. RLS ensures she sees exactly what her role allows, automatically.

Bob — DevOps / DB Administrator

Uses the planetary extension to manage the full Postgres security and infrastructure layer. Zero SQL written. He manages roles, grants, policies, table health, scheduled jobs, replication, and configuration through GUI forms that generate and execute SQL behind the scenes.

Senior Developer

Uses the extension to design and apply the Postgres application layer. Writes function bodies, designs view schemas, declares protected tables, manages types, configures FTS, and controls the audit setup. The platform scaffolds everything; Senior fills in the business logic.

PostgREST (system actor)

Watches Postgres. Exposes whatever views and functions exist as REST endpoints, scoped by JWT role claims. Picks up every change Senior makes automatically. No configuration required per new view or function.

Next.js BFF (system actor)

Consumes PostgREST endpoints. Renders data. Calls service endpoints for non-DB operations. Has no knowledge of the underlying schema, RLS rules, or function signatures.


4. Core Principles

4.1 The Protected Table Contract

Every raw table in a Planetary stack follows this contract:

  1. REVOKE ALL ON raw_table FROM PUBLIC — no one touches data directly
  2. REVOKE ALL ON raw_table FROM app_role — includes the Django DB user
  3. One or more views declared as the only access points
  4. INSTEAD OF triggers on each view — the only mutation path
  5. Overloaded functions per operation type — validation and transformation
  6. RLS on views — row-level authorization per role/claim

The platform scaffolds steps 1–6 from a single "Protect this table" action. Senior fills in function bodies. Everything else is generated.

4.2 Views as DTOs

A view is not a convenience — it is an explicit API contract. One raw table can have many views:

invoice_raw          ← locked, superadmin only
  invoice_v          ← standard ops view, status + amounts
  invoice_v_finance  ← finance role, full breakdown
  invoice_v_redacted ← public-facing, PII masked
  invoice_v_audit    ← compliance, all fields + metadata

Enter fullscreen mode Exit fullscreen mode

PostgREST exposes each view as a separate endpoint. RLS on each view enforces who can query what. No app-layer serializers needed.

4.3 Metadata ≠ Data Privileges

Revoking data access from the Django DB user does NOT revoke metadata access. The platform can fully introspect any table's columns, types, constraints, indexes, policies, and triggers via pg_catalog and information_schema — without ever reading a row of actual data. This is the foundation of the view builder, policy editor, and trigger scaffolder.

4.4 Functions as the Business Logic Layer

Postgres functions are:

  • Overloadable by signature — process_invoice(a) and process_invoice(a, b) coexist
  • Transactional — they run inside the trigger's transaction
  • Testable — callable directly via PostgREST or SELECT
  • Replaceable — CREATE OR REPLACE with no downtime

All validation, transformation, computed fields, and side-effect orchestration live in functions. The app layer calls views. It never implements business logic.

4.5 FDW Forensic Audit

Audit triggers write to a foreign table backed by a separate database server via postgres_fdw. The audit DB is:

  • On a different host (optionally different provider)
  • Append-only by policy — no UPDATE, no DELETE
  • Invisible to application roles
  • Full row_to_json(OLD) / row_to_json(NEW) per operation

If the main DB is compromised, wiped, or ransomwared — the audit trail is untouched on a completely separate server. The platform wires this up per table with a toggle.


5. Platform Features

5.1 Introspection Engine

The foundation. Pure pg_catalog + information_schema queries. Returns structured metadata the UI builds on. No data access required.

  • Tables, columns, data types, nullability, defaults
  • Constraints — PK, FK, unique, check, exclusion
  • Indexes — type, columns, partial condition, expression
  • Views + materialized views — definition, dependencies
  • Stored functions + procedures — signature, language, body, security
  • Triggers — timing, event, level, condition, function
  • Policies — command, roles, USING, WITH CHECK expressions
  • Roles + grants — membership, table/column/schema privileges
  • Extensions — installed, available, version
  • FDW servers + foreign tables
  • Publications + subscriptions
  • Table health — live tuples, dead tuples, bloat, last vacuum/analyze

5.2 Protected Table Manager (Senior + Bob)

The core workflow of the platform.

Declare a table as protected:

  • Select table from introspected list
  • Platform generates REVOKE statements for all non-superadmin roles
  • Column picker: drag-drop columns into one or more named views
  • Per-column: include / exclude / apply redaction function
  • Platform generates CREATE VIEW for each declared view
  • INSTEAD OF trigger skeleton auto-generated per view
  • Senior writes function body in inline editor
  • One-click apply — REVOKE + views + triggers executed in single transaction

View builder:

  • Visual column selector from introspected schema
  • Redaction function picker (mask_pan, mask_email, hash, nullify, etc.)
  • Live SQL preview
  • Role assignment — which PostgREST role sees this view
  • RLS policy generator — column picker for USING expression

5.3 Policy Manager — RLS / RBAC / ABAC / PBAC (Bob + Senior)

RLS Policies:

  • Enable/disable RLS per table/view — toggle
  • Create policy: name, table, command (ALL/SELECT/INSERT/UPDATE/DELETE)
  • USING expression builder — column picker + operator + value/function
  • WITH CHECK expression builder
  • PERMISSIVE vs RESTRICTIVE toggle
  • Role assignment
  • Live SQL preview
  • Active policies list with enable/disable per policy

Role Management (RBAC):

  • Create / rename / drop roles
  • Role membership — assign roles to roles (hierarchy)
  • Grant / revoke table privileges per role
  • Grant / revoke column-level privileges
  • Grant / revoke schema privileges
  • Grant / revoke function execute privileges
  • Role matrix view — roles × tables × privileges grid

Session Claims (ABAC):

  • Define current_setting('app.x') claim variables used in policies
  • JWT claim → set_config mapping documentation per role
  • Policy expression helpers using claim variables

Policy Templates (PBAC):

  • User-owns-row: user_id = current_setting('app.user_id')::uuid
  • Tenant isolation: tenant_id = (auth.jwt() ->> 'tenant_id')::uuid
  • Soft-delete filter: deleted_at IS NULL
  • Time-bounded: valid_from <= now() AND valid_to >= now()
  • Save custom templates — reusable across tables

5.4 Function & Trigger Manager (Senior)

Functions:

  • List all stored functions with signature, language, security mode
  • Create / edit function — inline code editor with syntax highlighting
  • Language picker — plpgsql, sql, python (plpython3u)
  • SECURITY INVOKER vs SECURITY DEFINER toggle
  • Parameter builder — name, type, default, mode (IN/OUT/INOUT)
  • Return type picker — scalar, setof, table, trigger, void
  • Function overload group view — all signatures for same name
  • Test runner — call function with sample args, see output

Triggers:

  • List all triggers per table with status
  • Create trigger: timing (BEFORE/AFTER/INSTEAD OF), event (INSERT/UPDATE/DELETE/TRUNCATE)
  • Column-specific UPDATE trigger (OF col1, col2)
  • FOR EACH ROW vs FOR EACH STATEMENT toggle
  • WHEN condition builder
  • Function picker from existing trigger functions
  • Enable / disable per trigger
  • Deferrable + deferred toggle

Event Triggers (DDL-level):

  • Fire on CREATE TABLE, ALTER TABLE, DROP, etc.
  • Auto-attach audit triggers to any new table — set-and-forget for Bob
  • Enforce naming conventions on DDL operations

5.5 Schema Object Manager (Senior + Bob)

Views:

  • List all views with definition preview
  • Create / edit view — column picker + SQL editor
  • Dependency graph — which tables/functions a view uses
  • Drop cascade safety — shows what breaks before executing

Materialized Views:

  • Create materialized view from view or raw SQL
  • Refresh strategy — manual / pg_cron scheduled
  • Refresh schedule builder (cron expression)
  • Index management on materialized view columns
  • Concurrent refresh toggle

Custom Types:

  • ENUM types — create, add values, rename, drop
  • Composite types — field builder with name + type
  • Domain types — base type + CHECK constraint
  • Range types — subtype + canonical function

Extensions:

  • Available extensions list with description
  • Install / drop per extension
  • Version display
  • Commonly useful: uuid-ossp, pgcrypto, pg_stat_statements, pg_cron, pg_net, postgres_fdw, postgis, unaccent, btree_gin

Sequences:

  • List, create, alter (start, increment, min, max, cycle)
  • Current value display
  • Owned-by column display

Schemas:

  • Create / drop schemas
  • search_path configuration per role
  • Move tables between schemas

5.6 Index Manager (Bob + Senior)

  • List all indexes — type, columns, size, usage stats
  • Detect unused indexes via pg_stat_user_indexes (idx_scan = 0)
  • Create index — type picker (B-tree, GIN, GiST, BRIN, Hash)
  • Partial index — WHERE clause builder
  • Expression index — expression input with column picker
  • Concurrent build toggle (non-blocking)
  • Index size vs query benefit display

5.7 Full Text Search (Senior)

  • Text search configuration manager
  • Dictionary management
  • tsvector column setup — which columns, which config
  • to_tsvector expression builder
  • GIN index auto-suggestion on tsvector columns
  • Test query — enter search terms, preview ranked results

5.8 Audit Layer (Bob)

  • Enable audit per table — toggle
  • FDW server configuration — host, dbname, credentials
  • Foreign table auto-creation on audit DB
  • Audit trigger auto-generated and attached
  • Audit log viewer (reads from foreign table — read-only)
  • Audit DB health status
  • Retention policy — pg_cron job to prune old audit records (on audit DB side)

5.9 Replication & CDC (Bob)

  • Publications — create, add/remove tables, manage row filters
  • Subscriptions — create, monitor lag, enable/disable
  • Logical replication slot monitoring
  • FDW connections — list, test, drop

5.10 Scheduled Jobs — pg_cron (Bob)

  • List all cron jobs with schedule, last run, status
  • Create job — SQL input + cron expression builder
  • Enable / disable per job
  • Run now (immediate one-off execution)
  • Job run history + error log

5.11 Notifications — pg_notify / pg_net (Senior)

  • NOTIFY channels in use — list active LISTEN connections
  • pg_net webhook trigger builder — target URL, payload template
  • Outbound webhook log (via net._http_response)

5.12 Performance & Health (Bob)

  • Table stats — live tuples, dead tuples, bloat %, last vacuum/analyze
  • pg_stat_statements — top queries by total time, calls, mean time
  • Cache hit ratio — buffer hits vs disk reads
  • Connection stats — active, idle, idle-in-transaction, by role
  • Lock monitor — active locks, blocking queries, wait graph
  • VACUUM / ANALYZE — trigger manually per table or ALL
  • Autovacuum settings — per-table overrides (fillfactor, thresholds)
  • Table size breakdown — table + indexes + toast

5.13 Configuration (Bob)

  • ALTER SYSTEM GUI — categorized parameter list
  • Search params by name or description
  • Current vs pending (requires reload) indicator
  • pg_reload_conf() trigger button
  • Per-database and per-role parameter overrides via ALTER DATABASE SET / ALTER ROLE SET

5.14 PostgREST Integration

  • View → PostgREST endpoint mapping display
  • Function → RPC endpoint display (/rpc/function_name)
  • JWT role claim → Postgres role mapping documentation
  • Schema cache reload trigger (NOTIFY pgrst, 'reload schema')
  • Endpoint health check per view

6. Non-Goals

  • Not a data browser. Django admin owns rows and data management. This platform does not display table contents except for the audit log viewer.
  • Not a query editor. Not a replacement for psql, DBeaver, or TablePlus. Senior who needs raw SQL uses those tools.
  • Not an ORM. No model abstraction. Everything is native Postgres SQL, generated and executed directly.
  • Not a migration framework. No Alembic/django-migrate style versioned migrations. DDL changes are applied directly. Event triggers handle DDL auditing.
  • Not a connection pooler. PgBouncer / Supavisor are separate infrastructure concerns.

7. Privilege Architecture

superadmin         → everything. raw tables, DDL, pg_catalog, config
senior_dev role    → DDL via platform, metadata, no raw table data
bob_devops role    → platform UI operations, metadata, health stats
django_app role    → metadata on raw tables, data on views only
postgrest role     → data on views, scoped by JWT sub-role
karen role         → rows in views, filtered by RLS
audit_writer role  → INSERT only on foreign audit tables

Enter fullscreen mode Exit fullscreen mode

The platform authenticates as django_app for introspection. DDL operations are executed via a separate platform_ddl role with elevated privileges, scoped to specific operations, never exposed to the HTTP layer.


8. Package Design

django-pg-planetary/
├── planetary/
│   ├── apps.py                  ← PlanetaryConfig, auto-registers admin
│   ├── introspect/
│   │   ├── tables.py            ← columns, types, constraints
│   │   ├── policies.py          ← pg_policies queries
│   │   ├── roles.py             ← pg_roles, memberships, grants
│   │   ├── routines.py          ← functions, triggers, event triggers
│   │   ├── objects.py           ← views, matviews, types, sequences
│   │   ├── indexes.py           ← index stats, usage
│   │   ├── health.py            ← pg_stat_*, vacuum, bloat
│   │   └── replication.py       ← publications, subscriptions, slots
│   ├── builders/
│   │   ├── policy_builder.py    ← CREATE/ALTER/DROP POLICY → SQL
│   │   ├── role_builder.py      ← GRANT/REVOKE/CREATE ROLE → SQL
│   │   ├── trigger_builder.py   ← CREATE/DROP TRIGGER → SQL
│   │   ├── view_builder.py      ← CREATE VIEW / INSTEAD OF → SQL
│   │   ├── function_builder.py  ← CREATE OR REPLACE FUNCTION → SQL
│   │   └── audit_builder.py     ← FDW setup, audit trigger → SQL
│   ├── executor.py              ← safe DDL execution, transaction wrapper
│   ├── admin/
│   │   ├── policy_admin.py
│   │   ├── role_admin.py
│   │   ├── schema_admin.py
│   │   ├── trigger_admin.py
│   │   ├── function_admin.py
│   │   ├── health_admin.py
│   │   ├── audit_admin.py
│   │   └── cron_admin.py
│   ├── templates/
│   │   └── admin/planetary/     ← per-view HTML templates
│   └── static/
│       └── planetary/           ← JS for live SQL preview, editors
└── setup.py

Enter fullscreen mode Exit fullscreen mode

Installation:

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'planetary',               # adds Planetary section to admin
    ...
]

PLANETARY = {
    'DDL_ROLE': 'platform_ddl',          # elevated role for DDL ops
    'AUDIT_SERVER': 'audit_db_server',   # FDW server name for audit
    'POSTGREST_URL': 'http://localhost:3000',
}

Enter fullscreen mode Exit fullscreen mode


9. The Paradigm in One Sentence

Karen checks the data. Bob secures the database. Senior encodes the rules. Postgres enforces everything. PostgREST exposes it. Next.js renders it. Services handle the side effects. Nobody writes middleware.