テーマ: 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で派生データを保存する:生成列とマテリアライズドビュー
生成列はその行だけから各行の値を1つ導き、仮想型(読み取り時に計算)か保存型(書き込み時に計算)で、不変な式だけを使えます。マテリアライズドビューは任意のクエリ結果を保存し、鮮度は最後の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.
-
トランザクション分離レベルの実践
Read Committed、Repeatable Read、Serializable は並行性と一貫性の間で折り合いをつけます。各レベルが許す異常を理解すれば、明示的なロックや再試行が必要な場面を判断できます。
-
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