## What — 主キーの書き方は3パターン **方法1: `primary_key` テストを使用(推奨、dbt-core 1.5以降)** ```yaml columns: - name: id description: "Primary key" tests: - primary_key ``` **方法2: `unique` と `not_null` を組み合わせる(従来の方法)** ```yaml columns: - name: id description: "Primary key" tests: - unique - not_null ``` **複合主キーの場合**は、カラム単体ではなくモデルレベルでテストを定義する。 ```yaml columns: - name: id description: "Part of composite primary key" - name: tenant_id description: "Part of composite primary key" # モデルレベルでテストを定義 tests: - dbt_utils.unique_combination_of_columns: combination_of_columns: - id - tenant_id ``` `primary_key` テストは `unique` と `not_null` の両方をチェックする。dbt-core 1.5未満なら方法2に落とす。複合主キーの場合は `dbt_utils` パッケージが必要。 ## How — モデル定義に組み込んだ例 ```yaml version: 2 models: - name: sample_model description: "Sample data with deduplication" config: materialized: table # pre-hook は使わない(SQLファイル内で処理) columns: - name: id description: "Primary key" tests: - primary_key # または unique + not_null - name: user_id description: "User identifier" tests: - not_null - name: created_at description: "Creation timestamp" tests: - not_null ``` 書いたら `dbt test --select sample_model` で回して確認する。 ## 関連 - [[データ基盤]] - [[dbtのYAMLファイルの書き方手順]] — source と model の使い分け・基本構造 - [[dbtでpre-hookを使わずSQL側で処理する]] — 重複排除を前処理でやらない書き方 - [[BigQuery]] — テストが実際に走る先