{"canonical_url":"https://engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/","content_markdown":"# PostgreSQL関数中心のデータ層を設計\n\n34スキーマにまたがる1,275個のストアド関数を持つ、PostgreSQL関数中心のデータ層を設計。すべての読み書きをテーブル直接操作ではなく、データベースで実行権限を付与できる関数経由にした。\n\n2025\n\n**状況.** 業務ロジックは漏れ出しやすい。APIの一部や、ハンドラー内で実行するSQLに分散し、同じルールが少しずつ異なる2通り、3通りで書かれ、データをどう扱うシステムかを指し示せる場所がなくなる。そこからバグやセキュリティの穴が生じる。\n\n**課題.** ロジックの置き場を1つにし、すべての読み書きをデータベース経由にして、APIを業務ルールを知らない薄いアダプターに保ち、全体を厳密に制限することを目指した。\n\n**行動.** 関数中心のデータ層にした。スキーマはidentity、organization、review、message、notificationと他29領域、計34に分け、アプリの全操作を1,275個のPostgreSQL関数経由にし、Goからテーブルへ直接アクセスさせない。データベースでこの境界を強制した。APIのログインロールmarinerにはアプリ関数のEXECUTEとスキーマのUSAGEだけを与え、SELECTもINSERTも直接操作も許さない。一括付与でなく約4,000件の明示的な権限を用いた。関数は、ログインできない別ロールfunction_ownerの所有で、固定search_pathを持つSECURITY DEFINERとして実行する。スーパーユーザーはマイグレーションとcron専用にし、稼働アプリから遠ざけた。\n\n**結果.** 監査できる1か所にロジックがまとまり、APIは良い意味で薄く単調に保たれた。境界は全員の記憶でなくPostgres自体が守る。APIが侵害されても関数の許さない操作はできない。1,275関数では規律に実際の費用があり、新項目はクエリの1行でなく、マイグレーションと関数変更を要する。この摩擦が境界を保つ代償だった。\n\n---\n\n- 役割: データベースエンジニア\n- カテゴリー: [プラットフォーム設計](https://data.engineer.company/ja/categories/platform-architecture/), [バックエンド開発](https://data.engineer.company/ja/categories/backend/), [データベース](https://data.engineer.company/ja/categories/databases/), [PostgreSQL](https://data.engineer.company/ja/categories/postgresql/), [SQL](https://data.engineer.company/ja/categories/sql/), [データガバナンス](https://data.engineer.company/ja/categories/data-governance/), [セキュリティ](https://data.engineer.company/ja/categories/security/)\n- サービス: [プラットフォーム・ソリューション設計](https://data.engineer.company/ja/services/platform-architecture/), [バックエンド・API開発](https://data.engineer.company/ja/services/backend-development/), [データベース設計・モデリング](https://data.engineer.company/ja/services/database-design/), [データガバナンス・品質管理](https://data.engineer.company/ja/services/data-governance/)\n\n\u003chttps://engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"34スキーマ・1,275個のストアド関数を持つPostgreSQL関数中心のデータ層を設計し、データベース自体でアクセス境界を適用した。","formats":{"gemtext":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/index.gmi","gopher":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/gophermap","html":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/","json":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/index.json","markdown":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/index.md","pdf":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/index.pdf"},"kind":"page","language":"ja","title":"PostgreSQL関数中心のデータ層を設計","url":"https://data.engineer.company/ja/portfolio/designed-a-function-first-postgresql-data-layer/","version":1}