主题: postgresql
-
Managing PostgreSQL extensions: installing, versioning, updating and dumping them
An extension packages SQL objects and often a shared library under one name with a control file and versioned scripts; CREATE EXTENSION installs it per database, ALTER EXTENSION UPDATE applies the author's update scripts, and pg_dump emits only the CREATE EXTENSION line. Keep the installed files, the catalog version and the loaded library in step, especially across package upgrades and pg_upgrade.
-
在 PostgreSQL 中设计仅追加的时间序列表
将测量值存入按时间范围分区的表,使用 timestamptz、由序列与时间组成的复合键,以及匹配查询方式的索引:单序列查询使用 B-tree,全表时间扫描使用 BRIN。保留期通过分离并删除分区实现,而不是 DELETE。这些选择源于数据按时间顺序到达,并按完整时间片移除。
-
在 PostgreSQL 中存储派生数据:生成列与物化视图
生成列仅根据本行数据为每行派生一个值,可采用虚拟形式(读取时计算)或存储形式(写入时计算),且只能使用不可变表达式;物化视图存储任意查询的结果,其新鲜度仅截至上次 REFRESH。需要索引的逐行规范化适合存储生成列,允许滞后的昂贵聚合适合物化视图,两者都不合适时则维护汇总表。
-
VACUUM、autovacuum 与表膨胀
PostgreSQL 的 MVCC 在更新和删除后会留下失效的行版本;VACUUM 回收这些版本,维护统计信息,并防止事务 ID 回卷。应保持 autovacuum 启用,并针对繁忙表进行调优。
-
使用容器中的临时数据库进行集成测试
每次测试运行都在一次性容器中启动真实数据库引擎,将数据保存在内存中,只对模板数据库执行一次迁移,再为每个测试文件复制模板。这样测试检查的就是真实的规划器、约束和隔离行为,而不是内存替代品。
-
Upsert, row limits and identifier quoting across PostgreSQL, MySQL, SQLite and SQL Server
PostgreSQL's ON CONFLICT, MySQL's ON DUPLICATE KEY UPDATE, SQLite's PostgreSQL-style ON CONFLICT and SQL Server's MERGE are three families of upsert syntax, LIMIT/OFFSET has at least three shapes, and a quoted identifier means double quotes, backticks or square brackets depending on the engine.
-
事务隔离级别的实际应用
读已提交、可重复读和可串行化在并发性与一致性之间作出权衡;了解各级别允许哪些异常,才能决定何时需要显式加锁或重试。
-
Datenbankänderungen ohne Ausfall: Expand und Contract
Ein Schema in drei einzeln auslieferbaren Schritten ändern: erweitern (neue Spalte oder Tabelle anlegen, alte behalten), migrieren (doppelt schreiben und in Häppchen nachfüllen), zusammenziehen (Altes entfernen, sobald aller Code das Neue nutzt); lange Sperren vermeiden, indem keine Tabelle in einem Statement umgeschrieben wird und lock_timeout jede Wartezeit begrenzt.
-
使用 WITH 编写公共表表达式与递归查询
WITH 为子查询命名,供语句的其余部分引用。WITH RECURSIVE 先计算非递归项,再重复计算递归项,直到不再产生新行,从而用一次查询遍历任意深度的树和图。只引用一次且无副作用的 CTE 会折叠进外层查询,除非指定 MATERIALIZED;SEARCH 和 CYCLE 子句负责排序与循环处理。
-
JSONB columns: what they are good for and when a column is better
jsonb stores parsed JSON in a binary form that can be indexed with GIN and queried with containment and path operators; it suits sparse, externally defined or genuinely variable attributes. Data with a fixed shape, data that needs constraints, foreign keys or per-field updates, and large frequently changed documents belong in ordinary columns.
-
数据库连接池及其限制
每个 PostgreSQL 连接都是一个消耗内存的进程。应用应根据实际并发量保持较小的连接池,设置获取连接的超时,并禁止请求处理程序临时自行打开连接。
-
Measured PostgreSQL SKIP LOCKED claims with four concurrent queue consumers
Four concurrent transactions each claimed 25 synthetic jobs in PostgreSQL 16.15. The returned 100 IDs were unique and no jobs remained unclaimed; this verifies one bounded claim phase, not exactly-once processing or broker replacement.
-
PostgreSQL 规划器统计:统计目标、相关列与估算偏差
规划器根据 ANALYZE 采样得到的列统计信息估算行数,包括常见值、直方图和不同值数量,并假设列彼此独立。过时统计、偏斜列的统计条目不足、相关列和表达式都会导致误估。应提高特定列的统计目标,为相关列或表达式创建扩展统计,重新分析,再比较估算行数与实际行数。
-
NULL in SQL: dreiwertige Logik und ihre Fallen
NULL bedeutet unbekannt, darum ergibt jeder Vergleich mit NULL weder wahr noch falsch, sondern unbekannt; WHERE verwirft unbekannte Zeilen, NOT IN mit einem NULL trifft nichts, Aggregate überspringen NULL, und ein Unique-Constraint lässt mehrere NULL zu. IS NULL, IS DISTINCT FROM und COALESCE bewusst einsetzen.
-
Schema migrations run with a short lock_timeout and automatic retry cause fewer deploy-time incidents than migrations without one
Hypothesis: because most ALTER TABLE forms take an ACCESS EXCLUSIVE lock that queues behind any long transaction while blocking every later query, migrations executed with a lock_timeout of a few seconds and a bounded retry loop produce fewer and shorter deploy-time outages than the same migrations run with the default unlimited wait, at the cost of a few migrations that need a manual rerun.
-
Row-level security policies reduce cross-tenant data leaks compared with application-side filtering
Hypothesis: multi-tenant services that enforce tenant isolation with PostgreSQL row-level security policies (a per-connection tenant setting checked by the database) have fewer cross-tenant exposure bugs than services that add a tenant_id predicate to every query, because a query that forgets the tenant predicate still sees only the current tenant's rows, and a request that never sets the tenant gets nothing or an error instead of every tenant's rows.
-
Savepoints and the aborted-transaction state in PostgreSQL
After any error inside a transaction block PostgreSQL rejects every further command until the block is rolled back; a savepoint set before a risky statement lets ROLLBACK TO SAVEPOINT discard only that part and continue. Use savepoints deliberately and sparingly, and make error handlers roll back instead of retrying on the same connection.
-
Logical replication in PostgreSQL: publications, subscriptions and how it differs from streaming replication
Streaming (physical) replication ships write-ahead log to a byte-identical standby of the same major version and architecture; logical replication publishes row changes from selected tables to a subscriber that may run a different major version and can hold its own data. Logical replication needs a replica identity, carries neither DDL nor sequence values, and its slot retains WAL on the publisher while the subscriber is behind.
-
Read replicas and replication lag: what stale reads look like and how to bound them
A streaming replica applies the primary's log with some delay, so a read right after a write may not see the write. Route reads by how much staleness each caller tolerates, use synchronous replication modes only where their latency is acceptable, and understand that replaying the log can cancel long queries on the replica.
-
Long-running and idle-in-transaction sessions in PostgreSQL: what they block and how to bound them
An open transaction holds its locks and pins the xmin horizon, so VACUUM cannot remove rows deleted after it began and DDL queues behind it; the worst case is a session idle in transaction because a client never committed. Find them in pg_stat_activity by xact_start and state, and bound them per role with idle_in_transaction_session_timeout, transaction_timeout and statement_timeout.
机器可读: JSON