@jgamaraalv/ts-dev-kit 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +24 -0
- package/.claude-plugin/plugin.json +24 -0
- package/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +128 -0
- package/agents/accessibility-pro.md +139 -0
- package/agents/api-builder.md +110 -0
- package/agents/code-reviewer.md +190 -0
- package/agents/database-expert.md +138 -0
- package/agents/debugger.md +241 -0
- package/agents/docker-expert.md +51 -0
- package/agents/multi-agent-coordinator.md +378 -0
- package/agents/nextjs-expert.md +136 -0
- package/agents/performance-engineer.md +138 -0
- package/agents/playwright-expert.md +126 -0
- package/agents/react-specialist.md +97 -0
- package/agents/security-scanner.md +105 -0
- package/agents/test-generator.md +221 -0
- package/agents/typescript-pro.md +253 -0
- package/agents/ux-optimizer.md +93 -0
- package/docs/rules/orchestration.md.template +126 -0
- package/package.json +28 -0
- package/skills/bullmq/SKILL.md +225 -0
- package/skills/bullmq/references/flows-and-schedulers.md +186 -0
- package/skills/bullmq/references/job-types-and-options.md +163 -0
- package/skills/bullmq/references/patterns.md +273 -0
- package/skills/bullmq/references/production.md +308 -0
- package/skills/composition-patterns/SKILL.md +58 -0
- package/skills/composition-patterns/references/architecture-avoid-boolean-props.md +87 -0
- package/skills/composition-patterns/references/architecture-compound-components.md +107 -0
- package/skills/composition-patterns/references/patterns-children-over-render-props.md +77 -0
- package/skills/composition-patterns/references/patterns-explicit-variants.md +87 -0
- package/skills/composition-patterns/references/react19-no-forwardref.md +37 -0
- package/skills/composition-patterns/references/state-context-interface.md +194 -0
- package/skills/composition-patterns/references/state-decouple-implementation.md +96 -0
- package/skills/composition-patterns/references/state-lift-state.md +126 -0
- package/skills/conventional-commits/SKILL.md +148 -0
- package/skills/docker/SKILL.md +55 -0
- package/skills/docker/references/compose-configs.md +95 -0
- package/skills/docker/references/monorepo-dockerfile.md +111 -0
- package/skills/drizzle-pg/SKILL.md +202 -0
- package/skills/drizzle-pg/references/advanced.md +299 -0
- package/skills/drizzle-pg/references/migrations.md +214 -0
- package/skills/drizzle-pg/references/queries.md +321 -0
- package/skills/drizzle-pg/references/relations.md +272 -0
- package/skills/drizzle-pg/references/schema-pg.md +256 -0
- package/skills/drizzle-pg/references/sql-operator.md +215 -0
- package/skills/fastify-best-practices/SKILL.md +143 -0
- package/skills/fastify-best-practices/references/hooks-and-lifecycle.md +122 -0
- package/skills/fastify-best-practices/references/plugins-and-encapsulation.md +137 -0
- package/skills/fastify-best-practices/references/request-reply-errors.md +189 -0
- package/skills/fastify-best-practices/references/routes-and-handlers.md +134 -0
- package/skills/fastify-best-practices/references/server-and-options.md +127 -0
- package/skills/fastify-best-practices/references/typescript-and-logging.md +223 -0
- package/skills/fastify-best-practices/references/validation-and-serialization.md +190 -0
- package/skills/ioredis/SKILL.md +51 -0
- package/skills/ioredis/references/advanced-patterns.md +312 -0
- package/skills/ioredis/references/cluster-sentinel.md +280 -0
- package/skills/ioredis/references/connection-options.md +187 -0
- package/skills/ioredis/references/core-api.md +179 -0
- package/skills/nextjs-best-practices/SKILL.md +194 -0
- package/skills/nextjs-best-practices/references/async-patterns.md +84 -0
- package/skills/nextjs-best-practices/references/bundling.md +192 -0
- package/skills/nextjs-best-practices/references/data-patterns.md +310 -0
- package/skills/nextjs-best-practices/references/debug-tricks.md +127 -0
- package/skills/nextjs-best-practices/references/directives.md +74 -0
- package/skills/nextjs-best-practices/references/error-handling.md +237 -0
- package/skills/nextjs-best-practices/references/file-conventions.md +152 -0
- package/skills/nextjs-best-practices/references/font.md +175 -0
- package/skills/nextjs-best-practices/references/functions.md +116 -0
- package/skills/nextjs-best-practices/references/hydration-error.md +86 -0
- package/skills/nextjs-best-practices/references/image.md +184 -0
- package/skills/nextjs-best-practices/references/metadata.md +305 -0
- package/skills/nextjs-best-practices/references/parallel-routes.md +299 -0
- package/skills/nextjs-best-practices/references/route-handlers.md +154 -0
- package/skills/nextjs-best-practices/references/rsc-boundaries.md +168 -0
- package/skills/nextjs-best-practices/references/runtime-selection.md +40 -0
- package/skills/nextjs-best-practices/references/scripts.md +148 -0
- package/skills/nextjs-best-practices/references/self-hosting.md +210 -0
- package/skills/nextjs-best-practices/references/suspense-boundaries.md +67 -0
- package/skills/owasp-security-review/SKILL.md +98 -0
- package/skills/owasp-security-review/references/a01-broken-access-control.md +78 -0
- package/skills/owasp-security-review/references/a02-security-misconfiguration.md +81 -0
- package/skills/owasp-security-review/references/a03-supply-chain-failures.md +65 -0
- package/skills/owasp-security-review/references/a04-cryptographic-failures.md +82 -0
- package/skills/owasp-security-review/references/a05-injection.md +106 -0
- package/skills/owasp-security-review/references/a06-insecure-design.md +76 -0
- package/skills/owasp-security-review/references/a07-authentication-failures.md +83 -0
- package/skills/owasp-security-review/references/a08-integrity-failures.md +72 -0
- package/skills/owasp-security-review/references/a09-logging-alerting-failures.md +76 -0
- package/skills/owasp-security-review/references/a10-exceptional-conditions.md +131 -0
- package/skills/postgresql/SKILL.md +50 -0
- package/skills/postgresql/references/ddl-schema.md +300 -0
- package/skills/postgresql/references/indexes.md +257 -0
- package/skills/postgresql/references/jsonb.md +261 -0
- package/skills/postgresql/references/performance.md +291 -0
- package/skills/postgresql/references/psql-cli.md +153 -0
- package/skills/postgresql/references/queries.md +287 -0
- package/skills/postgresql/references/transactions.md +280 -0
- package/skills/react-best-practices/SKILL.md +110 -0
- package/skills/react-best-practices/references/advanced-patterns.md +91 -0
- package/skills/react-best-practices/references/async-patterns.md +233 -0
- package/skills/react-best-practices/references/bundle-optimization.md +201 -0
- package/skills/react-best-practices/references/client-patterns.md +178 -0
- package/skills/react-best-practices/references/js-performance.md +210 -0
- package/skills/react-best-practices/references/rendering-performance.md +209 -0
- package/skills/react-best-practices/references/rerender-optimization.md +316 -0
- package/skills/react-best-practices/references/server-performance.md +274 -0
- package/skills/service-worker/SKILL.md +195 -0
- package/skills/service-worker/references/api-reference.md +114 -0
- package/skills/service-worker/references/caching-strategies.md +202 -0
- package/skills/service-worker/references/push-and-sync.md +261 -0
- package/skills/typescript-conventions/SKILL.md +51 -0
- package/skills/ui-ux-guidelines/SKILL.md +105 -0
- package/skills/ui-ux-guidelines/references/accessibility-and-interaction.md +74 -0
- package/skills/ui-ux-guidelines/references/forms-content-checklist.md +126 -0
- package/skills/ui-ux-guidelines/references/layout-typography-animation.md +95 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# PostgreSQL Performance Reference
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
|
|
5
|
+
1. [EXPLAIN basics](#explain)
|
|
6
|
+
2. [Reading EXPLAIN output](#reading-explain)
|
|
7
|
+
3. [Common bad plans and fixes](#bad-plans)
|
|
8
|
+
4. [Statistics and planner](#statistics)
|
|
9
|
+
5. [VACUUM and ANALYZE](#vacuum)
|
|
10
|
+
6. [Configuration knobs](#configuration)
|
|
11
|
+
7. [Bulk loading](#bulk-loading)
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## EXPLAIN
|
|
16
|
+
|
|
17
|
+
Always use `EXPLAIN (ANALYZE, BUFFERS)` for real data — plain `EXPLAIN` shows only planner estimates.
|
|
18
|
+
|
|
19
|
+
```sql
|
|
20
|
+
-- Full diagnostic
|
|
21
|
+
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
|
|
22
|
+
|
|
23
|
+
-- JSON format (machine-parseable, tools like pev2 use this)
|
|
24
|
+
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT ...;
|
|
25
|
+
|
|
26
|
+
-- With settings
|
|
27
|
+
EXPLAIN (ANALYZE, BUFFERS, SETTINGS) SELECT ...;
|
|
28
|
+
|
|
29
|
+
-- Verbose (shows output column list per node)
|
|
30
|
+
EXPLAIN (ANALYZE, VERBOSE, BUFFERS) SELECT ...;
|
|
31
|
+
|
|
32
|
+
-- Auto-explain slow queries (postgresql.conf)
|
|
33
|
+
-- shared_preload_libraries = 'auto_explain'
|
|
34
|
+
-- auto_explain.log_min_duration = '1s'
|
|
35
|
+
-- auto_explain.log_analyze = on
|
|
36
|
+
-- auto_explain.log_buffers = on
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Reading EXPLAIN output
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
Seq Scan on orders (cost=0.00..45231.00 rows=2000001 width=88)
|
|
45
|
+
(actual time=0.028..312.483 rows=2000001 loops=1)
|
|
46
|
+
Buffers: shared hit=22727 read=4615
|
|
47
|
+
Planning Time: 0.086 ms
|
|
48
|
+
Execution Time: 401.123 ms
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Cost components
|
|
52
|
+
|
|
53
|
+
`(cost=startup_cost..total_cost rows=estimated_rows width=avg_row_bytes)`
|
|
54
|
+
|
|
55
|
+
- **startup_cost**: cost before first row is returned (sorting, aggregation have high startup)
|
|
56
|
+
- **total_cost**: estimated total cost (arbitrary planner units)
|
|
57
|
+
- **rows**: planner's row estimate — compare to `actual rows` to spot bad estimates
|
|
58
|
+
- **width**: average row size in bytes
|
|
59
|
+
|
|
60
|
+
### Actual vs estimated
|
|
61
|
+
|
|
62
|
+
`(actual time=first_row_ms..last_row_ms rows=actual_rows loops=N)`
|
|
63
|
+
|
|
64
|
+
- `rows` vs `actual rows`: large discrepancy → stale stats → run `ANALYZE`
|
|
65
|
+
- `loops`: node executes N times (multiply time by loops for total cost of that node)
|
|
66
|
+
- Total actual time = `time * loops`
|
|
67
|
+
|
|
68
|
+
### Buffer hits
|
|
69
|
+
|
|
70
|
+
`Buffers: shared hit=N read=M written=K`
|
|
71
|
+
|
|
72
|
+
- **hit**: pages from shared buffer (RAM) — fast
|
|
73
|
+
- **read**: pages from disk — slow
|
|
74
|
+
- **written**: dirty pages flushed
|
|
75
|
+
- High `read` = data not cached, consider increasing `shared_buffers` or adding indexes
|
|
76
|
+
|
|
77
|
+
### Node types
|
|
78
|
+
|
|
79
|
+
| Node | Meaning |
|
|
80
|
+
| ---------------------------------------- | ----------------------------------------------------------------- |
|
|
81
|
+
| `Seq Scan` | Full table scan — fine for small tables or large fraction of rows |
|
|
82
|
+
| `Index Scan` | Uses index, fetches heap for each row |
|
|
83
|
+
| `Index Only Scan` | Uses covering index, no heap fetch — fastest |
|
|
84
|
+
| `Bitmap Index Scan` + `Bitmap Heap Scan` | Batches index hits, then fetches heap — good for many rows |
|
|
85
|
+
| `Nested Loop` | Good for small inner sets |
|
|
86
|
+
| `Hash Join` | Builds hash table on smaller side — good for medium sets |
|
|
87
|
+
| `Merge Join` | Both sides pre-sorted — good for large sorted sets |
|
|
88
|
+
| `Sort` | Explicit sort (check if an index can eliminate) |
|
|
89
|
+
| `Hash` | Build phase of Hash Join |
|
|
90
|
+
| `Aggregate` | GROUP BY or aggregate function |
|
|
91
|
+
| `Limit` | Stop after N rows |
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Common bad plans and fixes
|
|
96
|
+
|
|
97
|
+
### Sequential scan instead of index scan
|
|
98
|
+
|
|
99
|
+
```sql
|
|
100
|
+
-- Problem: planner chose Seq Scan despite index existing
|
|
101
|
+
-- Causes:
|
|
102
|
+
-- 1. Low selectivity (returning >10-20% of rows) — Seq Scan is correct
|
|
103
|
+
-- 2. Stale statistics → run ANALYZE
|
|
104
|
+
-- 3. Query prevents index use (function on column, implicit cast)
|
|
105
|
+
|
|
106
|
+
-- Bad (function on indexed column prevents index use):
|
|
107
|
+
WHERE date_trunc('day', created_at) = '2025-01-01'
|
|
108
|
+
-- Fix: use range query instead:
|
|
109
|
+
WHERE created_at >= '2025-01-01' AND created_at < '2025-01-02'
|
|
110
|
+
|
|
111
|
+
-- Bad (implicit cast):
|
|
112
|
+
WHERE user_id = '123' -- user_id is integer, '123' is text
|
|
113
|
+
-- Fix: use correct type:
|
|
114
|
+
WHERE user_id = 123
|
|
115
|
+
|
|
116
|
+
-- Force index for testing (don't do in production):
|
|
117
|
+
SET enable_seqscan = off;
|
|
118
|
+
EXPLAIN SELECT ...;
|
|
119
|
+
SET enable_seqscan = on;
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Bad row estimate
|
|
123
|
+
|
|
124
|
+
```sql
|
|
125
|
+
-- symptoms: estimated rows=1000, actual rows=1000000
|
|
126
|
+
-- fix:
|
|
127
|
+
ANALYZE tablename;
|
|
128
|
+
-- or update stats target for this column:
|
|
129
|
+
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;
|
|
130
|
+
ANALYZE orders;
|
|
131
|
+
-- default is 100; higher = more samples, better estimates, slower ANALYZE
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Slow Hash Join (out-of-memory)
|
|
135
|
+
|
|
136
|
+
```sql
|
|
137
|
+
-- In EXPLAIN output: "Batches: 8" means hash table spilled to disk
|
|
138
|
+
-- Fix: increase work_mem (per-session, per-sort/hash operation)
|
|
139
|
+
SET work_mem = '64MB';
|
|
140
|
+
-- Or globally in postgresql.conf: work_mem = 64MB
|
|
141
|
+
-- Warning: work_mem applies per operation per query, can multiply quickly
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### N+1 queries
|
|
145
|
+
|
|
146
|
+
Not a planner issue — fix in application. Use JOINs or `jsonb_agg` instead of per-row queries.
|
|
147
|
+
|
|
148
|
+
### Slow COUNT(\*)
|
|
149
|
+
|
|
150
|
+
```sql
|
|
151
|
+
-- Fast approximate count (no lock needed):
|
|
152
|
+
SELECT reltuples::bigint AS approx_count FROM pg_class WHERE relname = 'orders';
|
|
153
|
+
|
|
154
|
+
-- Fast exact count on filtered data — use a partial index condition:
|
|
155
|
+
CREATE INDEX idx_orders_pending ON orders (id) WHERE status = 'pending';
|
|
156
|
+
SELECT COUNT(*) FROM orders WHERE status = 'pending'; -- Index Only Scan
|
|
157
|
+
|
|
158
|
+
-- Avoid COUNT(*) on entire large table; use triggers or materialized counters instead
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Missing index for ORDER BY + LIMIT
|
|
162
|
+
|
|
163
|
+
```sql
|
|
164
|
+
-- Slow: Seq Scan + Sort + Limit
|
|
165
|
+
SELECT * FROM orders ORDER BY created_at DESC LIMIT 20;
|
|
166
|
+
|
|
167
|
+
-- Fix: index with matching sort order
|
|
168
|
+
CREATE INDEX idx_orders_created_desc ON orders (created_at DESC);
|
|
169
|
+
-- Now: Index Scan Backward → Limit (no sort step needed)
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## Statistics and planner
|
|
175
|
+
|
|
176
|
+
```sql
|
|
177
|
+
-- View planner statistics for a column
|
|
178
|
+
SELECT * FROM pg_stats WHERE tablename = 'orders' AND attname = 'status';
|
|
179
|
+
-- most_common_vals, most_common_freqs, n_distinct, histogram_bounds
|
|
180
|
+
|
|
181
|
+
-- Extended statistics (cross-column correlations)
|
|
182
|
+
CREATE STATISTICS stat_orders_user_status ON user_id, status FROM orders;
|
|
183
|
+
ANALYZE orders;
|
|
184
|
+
-- Helps planner when filtering on multiple columns with correlated values
|
|
185
|
+
|
|
186
|
+
-- Force specific join strategy (debugging only)
|
|
187
|
+
SET enable_hashjoin = off;
|
|
188
|
+
SET enable_mergejoin = off;
|
|
189
|
+
SET enable_nestloop = off;
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## VACUUM and ANALYZE
|
|
195
|
+
|
|
196
|
+
```sql
|
|
197
|
+
-- Manual vacuum (removes dead tuples, no lock)
|
|
198
|
+
VACUUM orders;
|
|
199
|
+
VACUUM VERBOSE orders; -- show progress
|
|
200
|
+
|
|
201
|
+
-- Vacuum + update stats
|
|
202
|
+
VACUUM ANALYZE orders;
|
|
203
|
+
|
|
204
|
+
-- Full vacuum (rewrites table, reclaims disk, EXCLUSIVE LOCK — use rarely)
|
|
205
|
+
VACUUM FULL orders;
|
|
206
|
+
|
|
207
|
+
-- Update stats only (lightweight, no dead tuple removal)
|
|
208
|
+
ANALYZE orders;
|
|
209
|
+
ANALYZE orders (status, user_id); -- specific columns
|
|
210
|
+
|
|
211
|
+
-- Monitor autovacuum health
|
|
212
|
+
SELECT
|
|
213
|
+
schemaname, relname,
|
|
214
|
+
n_live_tup, n_dead_tup,
|
|
215
|
+
ROUND(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
|
|
216
|
+
last_autovacuum, last_autoanalyze,
|
|
217
|
+
autovacuum_count
|
|
218
|
+
FROM pg_stat_user_tables
|
|
219
|
+
ORDER BY n_dead_tup DESC;
|
|
220
|
+
|
|
221
|
+
-- Table bloat: if dead_pct > 20% and autovacuum hasn't run recently, investigate
|
|
222
|
+
-- Check autovacuum config:
|
|
223
|
+
SHOW autovacuum_vacuum_scale_factor; -- default 0.2 (20% dead rows triggers vacuum)
|
|
224
|
+
SHOW autovacuum_vacuum_threshold; -- default 50 (minimum dead rows)
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## Configuration
|
|
230
|
+
|
|
231
|
+
Key settings (set in `postgresql.conf` or per-session):
|
|
232
|
+
|
|
233
|
+
| Parameter | Default | Recommended | Notes |
|
|
234
|
+
| ------------------------------ | ------- | ------------------ | ------------------------------------- |
|
|
235
|
+
| `shared_buffers` | 128MB | 25% of RAM | Main cache; requires restart |
|
|
236
|
+
| `work_mem` | 4MB | 16–64MB | Per operation, per query — be careful |
|
|
237
|
+
| `maintenance_work_mem` | 64MB | 256MB–1GB | For VACUUM, CREATE INDEX |
|
|
238
|
+
| `effective_cache_size` | 4GB | 75% of RAM | Planner hint only (no allocation) |
|
|
239
|
+
| `max_connections` | 100 | 20–100 + pgBouncer | Each connection uses ~5MB |
|
|
240
|
+
| `random_page_cost` | 4.0 | 1.1–2.0 for SSD | Lower = planner favors indexes |
|
|
241
|
+
| `effective_io_concurrency` | 1 | 200 for SSD | Enables prefetching |
|
|
242
|
+
| `max_wal_size` | 1GB | 2–4GB | Larger = less WAL checkpoints |
|
|
243
|
+
| `checkpoint_completion_target` | 0.5 | 0.9 | Spread checkpoint I/O |
|
|
244
|
+
| `wal_compression` | off | on | Reduces WAL size, small CPU cost |
|
|
245
|
+
|
|
246
|
+
```sql
|
|
247
|
+
-- Check current settings
|
|
248
|
+
SHOW work_mem;
|
|
249
|
+
SHOW all;
|
|
250
|
+
SELECT name, setting, unit FROM pg_settings WHERE name IN ('work_mem', 'shared_buffers');
|
|
251
|
+
|
|
252
|
+
-- Change for current session
|
|
253
|
+
SET work_mem = '64MB';
|
|
254
|
+
|
|
255
|
+
-- Change permanently (needs reload, not restart)
|
|
256
|
+
ALTER SYSTEM SET work_mem = '64MB';
|
|
257
|
+
SELECT pg_reload_conf();
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
|
+
## Bulk loading
|
|
263
|
+
|
|
264
|
+
```sql
|
|
265
|
+
-- Fastest bulk insert
|
|
266
|
+
COPY orders FROM '/path/to/data.csv' WITH (FORMAT csv, HEADER true);
|
|
267
|
+
-- Or from stdin:
|
|
268
|
+
COPY orders FROM STDIN WITH (FORMAT csv);
|
|
269
|
+
|
|
270
|
+
-- Speed up bulk loading:
|
|
271
|
+
BEGIN;
|
|
272
|
+
-- 1. Disable autocommit (batch in one transaction)
|
|
273
|
+
-- 2. Drop indexes before load, recreate after
|
|
274
|
+
DROP INDEX idx_orders_created;
|
|
275
|
+
-- 3. Disable FK checks temporarily
|
|
276
|
+
ALTER TABLE order_items DISABLE TRIGGER ALL;
|
|
277
|
+
-- 4. Set maintenance_work_mem high
|
|
278
|
+
SET maintenance_work_mem = '1GB';
|
|
279
|
+
|
|
280
|
+
COPY orders FROM '/path/data.csv' WITH (FORMAT csv);
|
|
281
|
+
|
|
282
|
+
ALTER TABLE order_items ENABLE TRIGGER ALL;
|
|
283
|
+
CREATE INDEX idx_orders_created ON orders (created_at);
|
|
284
|
+
COMMIT;
|
|
285
|
+
|
|
286
|
+
-- 5. Run ANALYZE after
|
|
287
|
+
ANALYZE orders;
|
|
288
|
+
|
|
289
|
+
-- INSERT ... SELECT (fast for transformations)
|
|
290
|
+
INSERT INTO orders_archive SELECT * FROM orders WHERE created_at < '2024-01-01';
|
|
291
|
+
```
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# psql CLI Reference
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
|
|
5
|
+
1. [Inspection commands](#inspection)
|
|
6
|
+
2. [Query execution](#query-execution)
|
|
7
|
+
3. [Import / export](#import-export)
|
|
8
|
+
4. [Useful quick queries](#useful-quick-queries)
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Inspection
|
|
13
|
+
|
|
14
|
+
```sql
|
|
15
|
+
-- Databases
|
|
16
|
+
\l -- list databases
|
|
17
|
+
\l+ -- with sizes
|
|
18
|
+
|
|
19
|
+
-- Schemas
|
|
20
|
+
\dn -- list schemas
|
|
21
|
+
\dn+ -- with owners
|
|
22
|
+
|
|
23
|
+
-- Tables
|
|
24
|
+
\dt -- tables in current schema
|
|
25
|
+
\dt schema.* -- tables in specific schema
|
|
26
|
+
\dt *.* -- all tables
|
|
27
|
+
\dt+ -- with sizes
|
|
28
|
+
|
|
29
|
+
-- Table structure
|
|
30
|
+
\d orders -- columns, indexes, constraints
|
|
31
|
+
\d+ orders -- verbose (with storage, stats target)
|
|
32
|
+
|
|
33
|
+
-- Indexes
|
|
34
|
+
\di orders -- indexes on table
|
|
35
|
+
\di+ -- with sizes
|
|
36
|
+
|
|
37
|
+
-- Views
|
|
38
|
+
\dv -- views
|
|
39
|
+
\dm -- materialized views
|
|
40
|
+
|
|
41
|
+
-- Functions
|
|
42
|
+
\df -- list functions
|
|
43
|
+
\df+ funcname -- function definition
|
|
44
|
+
|
|
45
|
+
-- Sequences
|
|
46
|
+
\ds -- sequences
|
|
47
|
+
|
|
48
|
+
-- Roles / users
|
|
49
|
+
\du -- list roles
|
|
50
|
+
\du myuser -- specific role
|
|
51
|
+
|
|
52
|
+
-- Extensions
|
|
53
|
+
\dx -- installed extensions
|
|
54
|
+
|
|
55
|
+
-- Describe a type
|
|
56
|
+
\dT enum_name
|
|
57
|
+
|
|
58
|
+
-- Show foreign tables
|
|
59
|
+
\det
|
|
60
|
+
|
|
61
|
+
-- Search in object names
|
|
62
|
+
\dt *order* -- tables containing "order" in name
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Query execution
|
|
68
|
+
|
|
69
|
+
```sql
|
|
70
|
+
-- Run a single command and exit (shell)
|
|
71
|
+
psql -c "SELECT COUNT(*) FROM users"
|
|
72
|
+
|
|
73
|
+
-- Run a file
|
|
74
|
+
psql -f script.sql
|
|
75
|
+
\i /path/to/script.sql -- from inside psql
|
|
76
|
+
|
|
77
|
+
-- Repeat last query
|
|
78
|
+
\g -- re-execute
|
|
79
|
+
\g output.txt -- re-execute and write to file
|
|
80
|
+
\gx -- re-execute in expanded mode
|
|
81
|
+
|
|
82
|
+
-- Timing
|
|
83
|
+
\timing -- toggle execution time display
|
|
84
|
+
\timing on
|
|
85
|
+
|
|
86
|
+
-- Edit query in $EDITOR then execute
|
|
87
|
+
\e
|
|
88
|
+
|
|
89
|
+
-- Edit a function
|
|
90
|
+
\ef function_name
|
|
91
|
+
|
|
92
|
+
-- Watch (re-run query every N seconds)
|
|
93
|
+
\watch 2 -- re-run last query every 2 seconds
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Import / export
|
|
99
|
+
|
|
100
|
+
```sql
|
|
101
|
+
-- Import CSV (client-side, works over network)
|
|
102
|
+
\copy tablename FROM 'file.csv' WITH (FORMAT csv, HEADER true)
|
|
103
|
+
\copy (SELECT col1, col2) FROM 'file.csv' WITH (FORMAT csv)
|
|
104
|
+
|
|
105
|
+
-- Import with null handling
|
|
106
|
+
\copy orders FROM 'data.csv' WITH (FORMAT csv, HEADER true, NULL '')
|
|
107
|
+
|
|
108
|
+
-- Export query result
|
|
109
|
+
\copy (SELECT * FROM users WHERE active) TO 'users.csv' WITH (FORMAT csv, HEADER true)
|
|
110
|
+
|
|
111
|
+
-- Server-side COPY (faster, requires file on server)
|
|
112
|
+
COPY orders FROM '/tmp/data.csv' WITH (FORMAT csv, HEADER true);
|
|
113
|
+
COPY (SELECT * FROM orders) TO '/tmp/export.csv' WITH (FORMAT csv, HEADER true);
|
|
114
|
+
|
|
115
|
+
-- Import SQL dump
|
|
116
|
+
\i dump.sql
|
|
117
|
+
-- Or from shell:
|
|
118
|
+
psql -d mydb -f dump.sql
|
|
119
|
+
|
|
120
|
+
-- pg_dump / pg_restore (shell)
|
|
121
|
+
pg_dump -Fc mydb > mydb.dump -- custom format
|
|
122
|
+
pg_restore -d mydb mydb.dump -- restore
|
|
123
|
+
pg_dump -h prod -d mydb | psql -h dev -d mydb -- copy between servers
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Useful quick queries
|
|
129
|
+
|
|
130
|
+
```sql
|
|
131
|
+
-- Database size
|
|
132
|
+
SELECT pg_size_pretty(pg_database_size(current_database()));
|
|
133
|
+
|
|
134
|
+
-- Table sizes (top 10)
|
|
135
|
+
SELECT tablename, pg_size_pretty(pg_total_relation_size(tablename::regclass)) AS size
|
|
136
|
+
FROM pg_tables WHERE schemaname = 'public'
|
|
137
|
+
ORDER BY pg_total_relation_size(tablename::regclass) DESC LIMIT 10;
|
|
138
|
+
|
|
139
|
+
-- Long-running queries
|
|
140
|
+
SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state
|
|
141
|
+
FROM pg_stat_activity
|
|
142
|
+
WHERE (now() - pg_stat_activity.query_start) > INTERVAL '1 minute';
|
|
143
|
+
|
|
144
|
+
-- Kill a query
|
|
145
|
+
SELECT pg_cancel_backend(pid); -- sends SIGINT (cancel)
|
|
146
|
+
SELECT pg_terminate_backend(pid); -- sends SIGTERM (disconnect)
|
|
147
|
+
|
|
148
|
+
-- Connections by state
|
|
149
|
+
SELECT state, COUNT(*) FROM pg_stat_activity GROUP BY state;
|
|
150
|
+
|
|
151
|
+
-- Check replication lag
|
|
152
|
+
SELECT now() - pg_last_xact_replay_timestamp() AS replication_lag;
|
|
153
|
+
```
|