[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D1TAR3F262WW3XZE7JSTP1":3,"skill-same:01M6D1TAR3F262WW3XZE7JSTP1":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":45,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6D1TAR3F262WW3XZE7JSTP1","database-postgres",null,"PostgreSQL specifics: the types worth using (jsonb, arrays, ranges, uuid, citext), extensions (pg_trgm, pgvector, PostGIS, pg_stat_statements), row-level security, generated columns, LISTEN and NOTIFY, partitioning, vacuum, connection pooling, roles, configuration basics, and managed providers. Read when the project uses Postgres.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fdatabase-postgres\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"database","postgres","database postgres","security","postgresql","Providers","read","generated","basics","listen","configuration","arrays","notify","project","connection pooling","roles","2026-11-10 10:12:30",false,"---\nname: database-postgres\ndescription: \"PostgreSQL specifics: the types worth using (jsonb, arrays, ranges, uuid, citext), extensions (pg_trgm, pgvector, PostGIS, pg_stat_statements), row-level security, generated columns, LISTEN and NOTIFY, partitioning, vacuum, connection pooling, roles, configuration basics, and managed providers. Read when the project uses Postgres.\"\n---\n\n# PostgreSQL\n\nThe generated Postgres: `serial` ids and `timestamp` columns, `json` instead\nof `jsonb`, the app connecting as `postgres`, default settings on a 16 GB\nserver, hundreds of direct connections from serverless functions, no\n`pg_stat_statements`, a transaction left idle for a day while tables bloat,\nand LISTEN\u002FNOTIFY used as a job queue. This skill is what is specific to\nPostgres; schema, queries, indexes and transactions in general are in the\nother `database-*` skills.\n\n## 1. Versions\n\n17 and 18 are the current majors in 2026 (18 shipped in September 2025); a\nnew major comes each autumn and is supported for five years. Start on the\nnewest major your host offers; apply minor releases routinely (fixes only, a\nrestart). What changed that matters:\n\n| Version | Worth knowing |\n|---|---|\n| 18 | `uuidv7()`; virtual generated columns (the new default); B-tree skip scan; asynchronous I\u002FO; `OLD` and `NEW` in `RETURNING`; `pg_upgrade` keeps planner statistics; `EXPLAIN ANALYZE` shows buffers |\n| 17 | `MERGE ... RETURNING`; `JSON_TABLE`; incremental base backups; `transaction_timeout`; vacuum needs far less memory |\n| 16 | `pg_stat_io`; logical replication from standbys; `IS JSON` and SQL\u002FJSON constructors |\n| 15 | `MERGE`; `UNIQUE NULLS NOT DISTINCT`; `CREATE` on schema `public` no longer granted to all |\n| 14 | Multiranges; `idle_session_timeout`; `DETACH PARTITION CONCURRENTLY` |\n| 13 | `gen_random_uuid()` in core; B-tree deduplication |\n| 12 | Stored generated columns; CTE inlining; `REINDEX CONCURRENTLY` |\n\n## 2. Types worth using\n\n- Keys `bigint generated always as identity`; `uuid` for UUIDs\n  (`gen_random_uuid()` for v4, `uuidv7()` from 18).\n- `timestamptz`, `date`, `interval`; `numeric(p, s)` for exact decimals;\n  never the `money` type (it follows the server's locale).\n- `text` with a CHECK rather than `varchar(n)`; `citext` for emails and\n  usernames, so equality and unique constraints ignore case.\n- `jsonb` (binary, indexable) rather than `json`: `->`, `->>`, `@>`, `?`,\n  `jsonb_path_query`. `jsonb_set` rewrites the whole value, so large\n  documents updated often are slow and bloat the table.\n- Arrays (`text[]`) with GIN for tags; ranges (`tstzrange`, `daterange`)\n  with `&&`, `@>` and exclusion constraints; `inet` for addresses;\n  `tsvector` for full text; `bytea` only for small binaries.\n- Generated columns: `GENERATED ALWAYS AS (expr) STORED` (12+) or `VIRTUAL`\n  (18, computed on read); STORED when you index it.\n- Enums: `ALTER TYPE ... ADD VALUE` is fast, but the new value cannot be\n  used in the same transaction, and values cannot be removed.\n\n## 3. Extensions\n\n| Extension | For | Notes |\n|---|---|---|\n| `pg_stat_statements` | Statistics per query | Always on: `shared_preload_libraries`, then `CREATE EXTENSION` |\n| `pg_trgm` | `ILIKE '%x%'`, fuzzy search, `similarity()` | GIN with `gin_trgm_ops` |\n| `vector` (pgvector) | Embeddings and similarity search | HNSW index, below |\n| `postgis` | Geography and geometry | `geography(Point, 4326)`, GiST, `ST_DWithin` |\n| `citext` | Case-insensitive text | Unique constraints ignore case |\n| `btree_gist` | Exclusion constraints mixing `=` and ranges | Bookings |\n| `pgcrypto` | `gen_random_bytes()`, `digest()` | Hash passwords in the app (argon2id), not with `crypt()` |\n| `unaccent` | Accent-insensitive search | Wrap in an immutable function to index it |\n| `pg_partman`, `pg_cron` | Partition upkeep, jobs in the database | Where the host offers them |\n\nManaged hosts allow a fixed list (`SELECT name FROM pg_available_extensions;`).\nAfter upgrading an extension's package, `ALTER EXTENSION vector UPDATE;`.\n\n```sql\nCREATE EXTENSION IF NOT EXISTS vector;\nALTER TABLE documents ADD COLUMN embedding vector(1536);\nCREATE INDEX CONCURRENTLY idx_documents_embedding\n  ON documents USING hnsw (embedding vector_cosine_ops);\nSELECT id FROM documents ORDER BY embedding \u003C=> $1 LIMIT 10;\n```\n\n- `\u003C->` L2, `\u003C#>` negative inner product, `\u003C=>` cosine distance; the index's\n  operator class must match the query's operator.\n- HNSW (`m = 16`, `ef_construction = 64`; raise `hnsw.ef_search` from 40 for\n  recall) rather than IVFFlat, which needs the data loaded first. `vector`\n  indexes up to 2,000 dimensions, `halfvec` up to 4,000. A `WHERE` filter can\n  return fewer than `LIMIT` rows; pgvector 0.8+ has iterative scans\n  (`SET hnsw.iterative_scan = relaxed_order`).\n\n## 4. Row-level security\n\nThe second wall for tenant data: the database hides another tenant's rows\neven when a query forgets its `WHERE`.\n\n```sql\nALTER TABLE projects ENABLE ROW LEVEL SECURITY;\nALTER TABLE projects FORCE ROW LEVEL SECURITY;   -- the table owner too\nCREATE POLICY tenant_isolation ON projects\n  USING (tenant_id = current_setting('app.tenant_id', true)::bigint)\n  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);\n```\n\n- Set the tenant per transaction, first thing:\n  `SELECT set_config('app.tenant_id', $1, true);` (`true`: local to the\n  transaction, so safe behind a transaction pooler). A session-level `SET`\n  leaks to the next client of a pooled connection.\n- A missing setting makes `current_setting(..., true)` NULL and the policy\n  matches nothing: it fails closed.\n- Superusers and `BYPASSRLS` roles skip policies, and so does the owner\n  without `FORCE`. Views run with their owner's rights unless created with\n  `security_invoker = true` (15+). Lead indexes with `tenant_id`.\n\n## 5. LISTEN\u002FNOTIFY and queues\n\n- `NOTIFY` (payload up to 8,000 bytes) reaches sessions listening at the\n  moment of commit; nothing is stored, so a listener that is down misses it.\n  Use it to wake workers or drop caches, carrying ids, never as the queue.\n  A listener needs its own session connection, not a transaction-pooled one.\n- A committing transaction that sent a NOTIFY takes a database-wide lock\n  during commit; at high write rates that serialises commits.\n- The durable queue is a table read with `FOR UPDATE SKIP LOCKED`\n  (`database-transactions`) or a library on it: pgmq, pg-boss,\n  graphile-worker, River, Procrastinate.\n\n## 6. Partitioning\n\nFor tables in the hundreds of gigabytes, or data dropped by age (events,\nlogs, metrics): removing a month becomes dropping a partition instead of a\nhuge `DELETE`.\n\n```sql\nCREATE TABLE events (\n  id         bigint GENERATED ALWAYS AS IDENTITY,\n  created_at timestamptz NOT NULL,\n  payload    jsonb NOT NULL,\n  PRIMARY KEY (id, created_at)       -- must include the partition key\n) PARTITION BY RANGE (created_at);\nCREATE TABLE events_2026_10 PARTITION OF events\n  FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');\n```\n\n- Unique constraints must include the partition key, and queries that do\n  not filter on it visit every partition. Create partitions ahead\n  (pg_partman or a scheduled job); retire old ones with\n  `DETACH PARTITION ... CONCURRENTLY`, then drop.\n- Not for a table of a few million rows, nor as a speed-up: that is an index.\n\n## 7. Vacuum and bloat\n\n- Updates and deletes leave old row versions; autovacuum reclaims them once\n  no transaction can still see them. The enemy is whatever holds that\n  horizon back: a session `idle in transaction` for hours, an abandoned\n  replication slot, a long query on a replica with `hot_standby_feedback`.\n  Set `idle_in_transaction_session_timeout`, watch `xact_start` in\n  `pg_stat_activity`, drop replication slots no longer active.\n- Autovacuum starts when 20% of a table has changed; on large busy tables\n  lower it per table:\n  `ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.02, autovacuum_analyze_scale_factor = 0.01);`\n- Transaction id age (`SELECT datname, age(datfrozenxid) FROM pg_database;`)\n  must stay far from the 2 billion limit: autovacuum forces a freeze at 200\n  million per table by default; alert well before 1 billion, since near the\n  limit Postgres stops accepting writes.\n- Bloated tables: `pg_repack` rebuilds online; `VACUUM FULL` locks the table\n  for the whole rewrite. Indexes: `REINDEX INDEX CONCURRENTLY`.\n\n## 8. Connections and pooling\n\n- Each connection is a server process costing megabytes; past a few hundred\n  active ones throughput drops. `max_connections` defaults to 100.\n- Add it up: pool size times instances, plus workers, migrations and admin,\n  under `max_connections`. Pools of 5 to 20 per instance; for the whole\n  server, about twice the CPU cores in active connections is a good start.\n- A pooler in front of many instances or serverless functions: PgBouncer, or\n  the host's (Supabase Supavisor, Neon's pooled host, RDS Proxy). In\n  transaction mode session state breaks: `SET` (use `SET LOCAL` or\n  `set_config(..., true)`), session advisory locks, `LISTEN`, temporary\n  tables, `WITH HOLD` cursors. Prepared statements work from PgBouncer 1.21\n  with `max_prepared_statements` set; older setups disable them in the\n  driver.\n- Migrations and listeners connect directly or in session mode. Serverless\n  and edge runtimes use an HTTP or WebSocket driver\n  (`@neondatabase\u002Fserverless`), Cloudflare Hyperdrive, or the pooled URL\n  with a pool of 1 per instance.\n\n## 9. Configuration basics\n\n| Setting | Default | Start with |\n|---|---|---|\n| `shared_buffers` | 128MB | 25% of RAM |\n| `effective_cache_size` | 4GB | 50 to 75% of RAM (a planner hint) |\n| `work_mem` | 4MB | 16 to 64MB; per sort or hash per query, so mind the connections |\n| `maintenance_work_mem` | 64MB | 512MB to 2GB, for vacuum and index builds |\n| `random_page_cost` | 4.0 | 1.1 on SSD |\n| `statement_timeout` | 0, none | Per role: 15s for the web app, longer for jobs |\n| `idle_in_transaction_session_timeout` | 0, none | 60s for app roles |\n| `log_min_duration_statement` | -1, off | 500ms to 1s |\n| `shared_preload_libraries` | empty | `pg_stat_statements`, and `auto_explain` if wanted |\n\nSet per role where it differs (`ALTER ROLE app SET statement_timeout =\n'15s';`). Managed hosts expose these as parameter groups or flags.\n\n## 10. Roles and privileges\n\n```sql\nCREATE ROLE app_owner LOGIN;   -- owns the schema; migrations run as it\nCREATE ROLE app LOGIN;         -- the running app: rows only\nCREATE ROLE app_readonly LOGIN;\n-- passwords are set by the operator from the secret store, never committed\nCREATE SCHEMA app AUTHORIZATION app_owner;\nGRANT USAGE ON SCHEMA app TO app, app_readonly;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT USAGE, SELECT ON SEQUENCES TO app;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT SELECT ON TABLES TO app_readonly;\n```\n\n- Default privileges apply to objects that role creates: run migrations as\n  `app_owner` (or `SET ROLE app_owner` first), or new tables end up\n  unreadable by the app.\n- No superuser, `CREATEROLE` or table ownership for the app.\n  `pg_read_all_data` (14+) is a quick read-only grant, across every schema.\n  `scram-sha-256` passwords (default since 14); `sslmode=verify-full` from\n  outside a private network.\n\n## 11. Providers and local development\n\n| Provider | Know before choosing |\n|---|---|\n| Amazon RDS, Aurora | No true superuser (`rds_superuser`); parameter groups; RDS Proxy; Multi-AZ failover |\n| Google Cloud SQL, AlloyDB | Connect through the Cloud SQL Auth Proxy or private IP; flags for settings |\n| Supabase | Pooler on 6543 (transaction) and 5432 (session); client access leans on RLS |\n| Neon | Branches per preview, scale to zero with a cold start; a `-pooler` host for pooled connections |\n\nCompare the extensions allowed, connection limits per plan, backup and\npoint-in-time windows, regions, and whether logical replication is\navailable for moving out later. Locally, the production major in Docker,\nbound to localhost:\n\n```yaml\nservices:\n  db:\n    image: postgres:17\n    environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: app, POSTGRES_DB: app }\n    ports: [\"127.0.0.1:5432:5432\"]\n    volumes: [\"pgdata:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata\"]\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"]\n      interval: 5s\n      retries: 10\nvolumes:\n  pgdata:\n```\n\nFrom the `postgres:18` image on, mount the volume at `\u002Fvar\u002Flib\u002Fpostgresql`:\nthe data directory moved to a versioned path beneath it. Backups\n(`pg_dump -Fc`, pgBackRest, point-in-time recovery) are in\n`database-operations`.\n\n## Check it\n\n```sql\nSELECT version();\nSELECT name, setting, unit FROM pg_settings\nWHERE name IN ('shared_buffers', 'work_mem', 'max_connections', 'statement_timeout');\nSELECT query, calls, round(mean_exec_time) AS mean_ms, round(total_exec_time) AS total_ms\nFROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;\nSELECT state, count(*) FROM pg_stat_activity GROUP BY state;\nSELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolcanlogin;\n```\n\n- The app's role is neither superuser nor owner; as that role, another\n  tenant's rows are invisible and inserting one fails.\n- No `idle in transaction` session over a minute; no inactive slot.\n\n## Avoid\n\n`serial`, `timestamp`, `json` and `money`; the app as superuser or owner;\ndefault memory settings in production; running without\n`pg_stat_statements`; hundreds of direct connections from functions;\nsession `SET` or advisory locks behind a transaction pooler; LISTEN\u002FNOTIFY\nas a queue; transactions left idle; `VACUUM FULL` on a live table;\npartitioning a small table; RLS without `FORCE` or with the tenant set per\nsession; a local database on another major version than production.\n","# PostgreSQL\n\nThe generated Postgres: `serial` ids and `timestamp` columns, `json` instead\nof `jsonb`, the app connecting as `postgres`, default settings on a 16 GB\nserver, hundreds of direct connections from serverless functions, no\n`pg_stat_statements`, a transaction left idle for a day while tables bloat,\nand LISTEN\u002FNOTIFY used as a job queue. This skill is what is specific to\nPostgres; schema, queries, indexes and transactions in general are in the\nother `database-*` skills.\n\n## 1. Versions\n\n17 and 18 are the current majors in 2026 (18 shipped in September 2025); a\nnew major comes each autumn and is supported for five years. Start on the\nnewest major your host offers; apply minor releases routinely (fixes only, a\nrestart). What changed that matters:\n\n| Version | Worth knowing |\n|---|---|\n| 18 | `uuidv7()`; virtual generated columns (the new default); B-tree skip scan; asynchronous I\u002FO; `OLD` and `NEW` in `RETURNING`; `pg_upgrade` keeps planner statistics; `EXPLAIN ANALYZE` shows buffers |\n| 17 | `MERGE ... RETURNING`; `JSON_TABLE`; incremental base backups; `transaction_timeout`; vacuum needs far less memory |\n| 16 | `pg_stat_io`; logical replication from standbys; `IS JSON` and SQL\u002FJSON constructors |\n| 15 | `MERGE`; `UNIQUE NULLS NOT DISTINCT`; `CREATE` on schema `public` no longer granted to all |\n| 14 | Multiranges; `idle_session_timeout`; `DETACH PARTITION CONCURRENTLY` |\n| 13 | `gen_random_uuid()` in core; B-tree deduplication |\n| 12 | Stored generated columns; CTE inlining; `REINDEX CONCURRENTLY` |\n\n## 2. Types worth using\n\n- Keys `bigint generated always as identity`; `uuid` for UUIDs\n  (`gen_random_uuid()` for v4, `uuidv7()` from 18).\n- `timestamptz`, `date`, `interval`; `numeric(p, s)` for exact decimals;\n  never the `money` type (it follows the server's locale).\n- `text` with a CHECK rather than `varchar(n)`; `citext` for emails and\n  usernames, so equality and unique constraints ignore case.\n- `jsonb` (binary, indexable) rather than `json`: `->`, `->>`, `@>`, `?`,\n  `jsonb_path_query`. `jsonb_set` rewrites the whole value, so large\n  documents updated often are slow and bloat the table.\n- Arrays (`text[]`) with GIN for tags; ranges (`tstzrange`, `daterange`)\n  with `&&`, `@>` and exclusion constraints; `inet` for addresses;\n  `tsvector` for full text; `bytea` only for small binaries.\n- Generated columns: `GENERATED ALWAYS AS (expr) STORED` (12+) or `VIRTUAL`\n  (18, computed on read); STORED when you index it.\n- Enums: `ALTER TYPE ... ADD VALUE` is fast, but the new value cannot be\n  used in the same transaction, and values cannot be removed.\n\n## 3. Extensions\n\n| Extension | For | Notes |\n|---|---|---|\n| `pg_stat_statements` | Statistics per query | Always on: `shared_preload_libraries`, then `CREATE EXTENSION` |\n| `pg_trgm` | `ILIKE '%x%'`, fuzzy search, `similarity()` | GIN with `gin_trgm_ops` |\n| `vector` (pgvector) | Embeddings and similarity search | HNSW index, below |\n| `postgis` | Geography and geometry | `geography(Point, 4326)`, GiST, `ST_DWithin` |\n| `citext` | Case-insensitive text | Unique constraints ignore case |\n| `btree_gist` | Exclusion constraints mixing `=` and ranges | Bookings |\n| `pgcrypto` | `gen_random_bytes()`, `digest()` | Hash passwords in the app (argon2id), not with `crypt()` |\n| `unaccent` | Accent-insensitive search | Wrap in an immutable function to index it |\n| `pg_partman`, `pg_cron` | Partition upkeep, jobs in the database | Where the host offers them |\n\nManaged hosts allow a fixed list (`SELECT name FROM pg_available_extensions;`).\nAfter upgrading an extension's package, `ALTER EXTENSION vector UPDATE;`.\n\n```sql\nCREATE EXTENSION IF NOT EXISTS vector;\nALTER TABLE documents ADD COLUMN embedding vector(1536);\nCREATE INDEX CONCURRENTLY idx_documents_embedding\n  ON documents USING hnsw (embedding vector_cosine_ops);\nSELECT id FROM documents ORDER BY embedding \u003C=> $1 LIMIT 10;\n```\n\n- `\u003C->` L2, `\u003C#>` negative inner product, `\u003C=>` cosine distance; the index's\n  operator class must match the query's operator.\n- HNSW (`m = 16`, `ef_construction = 64`; raise `hnsw.ef_search` from 40 for\n  recall) rather than IVFFlat, which needs the data loaded first. `vector`\n  indexes up to 2,000 dimensions, `halfvec` up to 4,000. A `WHERE` filter can\n  return fewer than `LIMIT` rows; pgvector 0.8+ has iterative scans\n  (`SET hnsw.iterative_scan = relaxed_order`).\n\n## 4. Row-level security\n\nThe second wall for tenant data: the database hides another tenant's rows\neven when a query forgets its `WHERE`.\n\n```sql\nALTER TABLE projects ENABLE ROW LEVEL SECURITY;\nALTER TABLE projects FORCE ROW LEVEL SECURITY;   -- the table owner too\nCREATE POLICY tenant_isolation ON projects\n  USING (tenant_id = current_setting('app.tenant_id', true)::bigint)\n  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);\n```\n\n- Set the tenant per transaction, first thing:\n  `SELECT set_config('app.tenant_id', $1, true);` (`true`: local to the\n  transaction, so safe behind a transaction pooler). A session-level `SET`\n  leaks to the next client of a pooled connection.\n- A missing setting makes `current_setting(..., true)` NULL and the policy\n  matches nothing: it fails closed.\n- Superusers and `BYPASSRLS` roles skip policies, and so does the owner\n  without `FORCE`. Views run with their owner's rights unless created with\n  `security_invoker = true` (15+). Lead indexes with `tenant_id`.\n\n## 5. LISTEN\u002FNOTIFY and queues\n\n- `NOTIFY` (payload up to 8,000 bytes) reaches sessions listening at the\n  moment of commit; nothing is stored, so a listener that is down misses it.\n  Use it to wake workers or drop caches, carrying ids, never as the queue.\n  A listener needs its own session connection, not a transaction-pooled one.\n- A committing transaction that sent a NOTIFY takes a database-wide lock\n  during commit; at high write rates that serialises commits.\n- The durable queue is a table read with `FOR UPDATE SKIP LOCKED`\n  (`database-transactions`) or a library on it: pgmq, pg-boss,\n  graphile-worker, River, Procrastinate.\n\n## 6. Partitioning\n\nFor tables in the hundreds of gigabytes, or data dropped by age (events,\nlogs, metrics): removing a month becomes dropping a partition instead of a\nhuge `DELETE`.\n\n```sql\nCREATE TABLE events (\n  id         bigint GENERATED ALWAYS AS IDENTITY,\n  created_at timestamptz NOT NULL,\n  payload    jsonb NOT NULL,\n  PRIMARY KEY (id, created_at)       -- must include the partition key\n) PARTITION BY RANGE (created_at);\nCREATE TABLE events_2026_10 PARTITION OF events\n  FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');\n```\n\n- Unique constraints must include the partition key, and queries that do\n  not filter on it visit every partition. Create partitions ahead\n  (pg_partman or a scheduled job); retire old ones with\n  `DETACH PARTITION ... CONCURRENTLY`, then drop.\n- Not for a table of a few million rows, nor as a speed-up: that is an index.\n\n## 7. Vacuum and bloat\n\n- Updates and deletes leave old row versions; autovacuum reclaims them once\n  no transaction can still see them. The enemy is whatever holds that\n  horizon back: a session `idle in transaction` for hours, an abandoned\n  replication slot, a long query on a replica with `hot_standby_feedback`.\n  Set `idle_in_transaction_session_timeout`, watch `xact_start` in\n  `pg_stat_activity`, drop replication slots no longer active.\n- Autovacuum starts when 20% of a table has changed; on large busy tables\n  lower it per table:\n  `ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.02, autovacuum_analyze_scale_factor = 0.01);`\n- Transaction id age (`SELECT datname, age(datfrozenxid) FROM pg_database;`)\n  must stay far from the 2 billion limit: autovacuum forces a freeze at 200\n  million per table by default; alert well before 1 billion, since near the\n  limit Postgres stops accepting writes.\n- Bloated tables: `pg_repack` rebuilds online; `VACUUM FULL` locks the table\n  for the whole rewrite. Indexes: `REINDEX INDEX CONCURRENTLY`.\n\n## 8. Connections and pooling\n\n- Each connection is a server process costing megabytes; past a few hundred\n  active ones throughput drops. `max_connections` defaults to 100.\n- Add it up: pool size times instances, plus workers, migrations and admin,\n  under `max_connections`. Pools of 5 to 20 per instance; for the whole\n  server, about twice the CPU cores in active connections is a good start.\n- A pooler in front of many instances or serverless functions: PgBouncer, or\n  the host's (Supabase Supavisor, Neon's pooled host, RDS Proxy). In\n  transaction mode session state breaks: `SET` (use `SET LOCAL` or\n  `set_config(..., true)`), session advisory locks, `LISTEN`, temporary\n  tables, `WITH HOLD` cursors. Prepared statements work from PgBouncer 1.21\n  with `max_prepared_statements` set; older setups disable them in the\n  driver.\n- Migrations and listeners connect directly or in session mode. Serverless\n  and edge runtimes use an HTTP or WebSocket driver\n  (`@neondatabase\u002Fserverless`), Cloudflare Hyperdrive, or the pooled URL\n  with a pool of 1 per instance.\n\n## 9. Configuration basics\n\n| Setting | Default | Start with |\n|---|---|---|\n| `shared_buffers` | 128MB | 25% of RAM |\n| `effective_cache_size` | 4GB | 50 to 75% of RAM (a planner hint) |\n| `work_mem` | 4MB | 16 to 64MB; per sort or hash per query, so mind the connections |\n| `maintenance_work_mem` | 64MB | 512MB to 2GB, for vacuum and index builds |\n| `random_page_cost` | 4.0 | 1.1 on SSD |\n| `statement_timeout` | 0, none | Per role: 15s for the web app, longer for jobs |\n| `idle_in_transaction_session_timeout` | 0, none | 60s for app roles |\n| `log_min_duration_statement` | -1, off | 500ms to 1s |\n| `shared_preload_libraries` | empty | `pg_stat_statements`, and `auto_explain` if wanted |\n\nSet per role where it differs (`ALTER ROLE app SET statement_timeout =\n'15s';`). Managed hosts expose these as parameter groups or flags.\n\n## 10. Roles and privileges\n\n```sql\nCREATE ROLE app_owner LOGIN;   -- owns the schema; migrations run as it\nCREATE ROLE app LOGIN;         -- the running app: rows only\nCREATE ROLE app_readonly LOGIN;\n-- passwords are set by the operator from the secret store, never committed\nCREATE SCHEMA app AUTHORIZATION app_owner;\nGRANT USAGE ON SCHEMA app TO app, app_readonly;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT USAGE, SELECT ON SEQUENCES TO app;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT SELECT ON TABLES TO app_readonly;\n```\n\n- Default privileges apply to objects that role creates: run migrations as\n  `app_owner` (or `SET ROLE app_owner` first), or new tables end up\n  unreadable by the app.\n- No superuser, `CREATEROLE` or table ownership for the app.\n  `pg_read_all_data` (14+) is a quick read-only grant, across every schema.\n  `scram-sha-256` passwords (default since 14); `sslmode=verify-full` from\n  outside a private network.\n\n## 11. Providers and local development\n\n| Provider | Know before choosing |\n|---|---|\n| Amazon RDS, Aurora | No true superuser (`rds_superuser`); parameter groups; RDS Proxy; Multi-AZ failover |\n| Google Cloud SQL, AlloyDB | Connect through the Cloud SQL Auth Proxy or private IP; flags for settings |\n| Supabase | Pooler on 6543 (transaction) and 5432 (session); client access leans on RLS |\n| Neon | Branches per preview, scale to zero with a cold start; a `-pooler` host for pooled connections |\n\nCompare the extensions allowed, connection limits per plan, backup and\npoint-in-time windows, regions, and whether logical replication is\navailable for moving out later. Locally, the production major in Docker,\nbound to localhost:\n\n```yaml\nservices:\n  db:\n    image: postgres:17\n    environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: app, POSTGRES_DB: app }\n    ports: [\"127.0.0.1:5432:5432\"]\n    volumes: [\"pgdata:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata\"]\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"]\n      interval: 5s\n      retries: 10\nvolumes:\n  pgdata:\n```\n\nFrom the `postgres:18` image on, mount the volume at `\u002Fvar\u002Flib\u002Fpostgresql`:\nthe data directory moved to a versioned path beneath it. Backups\n(`pg_dump -Fc`, pgBackRest, point-in-time recovery) are in\n`database-operations`.\n\n## Check it\n\n```sql\nSELECT version();\nSELECT name, setting, unit FROM pg_settings\nWHERE name IN ('shared_buffers', 'work_mem', 'max_connections', 'statement_timeout');\nSELECT query, calls, round(mean_exec_time) AS mean_ms, round(total_exec_time) AS total_ms\nFROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;\nSELECT state, count(*) FROM pg_stat_activity GROUP BY state;\nSELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolcanlogin;\n```\n\n- The app's role is neither superuser nor owner; as that role, another\n  tenant's rows are invisible and inserting one fails.\n- No `idle in transaction` session over a minute; no inactive slot.\n\n## Avoid\n\n`serial`, `timestamp`, `json` and `money`; the app as superuser or owner;\ndefault memory settings in production; running without\n`pg_stat_statements`; hundreds of direct connections from functions;\nsession `SET` or advisory locks behind a transaction pooler; LISTEN\u002FNOTIFY\nas a queue; transactions left idle; `VACUUM FULL` on a live table;\npartitioning a small table; RLS without `FORCE` or with the tenant set per\nsession; a local database on another major version than production.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Fdatabase-postgres",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add enowdev\u002Fenowxcli --skill database-postgres",{"tool":55,"command":56},"bunx","bunx skills add enowdev\u002Fenowxcli --skill database-postgres",{"tool":58,"command":59},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill database-postgres","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fdatabase-postgres\u002FSKILL.md",true,[],[64,74,91,104,125,144],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":35},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[],[71,72,73,32,25],"demo skill","demo","tests",{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":35},"01M6D2HM0GCPM0TM2HPG9HHR2R","writing","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[],[76,81,82,83,84,85,25,86,87,88,89,90],"text","emails","empty","drop","document","page","voice","notifications","documentation","translate",{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":35},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[],[93,98,99,100,101,86,102,25,103],"icons","components","SET","responsive","layout","before building",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":35},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[],[93,111,112,113,114,115,116,117,118,25,103,119,86,120,121,122,98,123,124],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","code","Charts","content","screenshots","logo",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":35},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[],[132,93,133,99,134,135,120,136,137,138,102,114,139,140,141,25,103,86,142,143],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":35},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[],[93,151,152,153,154,155,156,157,102,32,158,159,25,160,161,162,163,164,165,166],"vue","stack","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","config","directory","testing"]