imu-note
いむたろ
いむたろ
@imutaroh
新卒エンジニア / データ基盤 × AI

What — 主キーの書き方は3パターン

方法1: primary_key テストを使用(推奨、dbt-core 1.5以降)

columns:
  - name: id
    description: "Primary key"
    tests:
      - primary_key

方法2: uniquenot_null を組み合わせる(従来の方法)

columns:
  - name: id
    description: "Primary key"
    tests:
      - unique
      - not_null

複合主キーの場合は、カラム単体ではなくモデルレベルでテストを定義する。

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 テストは uniquenot_null の両方をチェックする。dbt-core 1.5未満なら方法2に落とす。複合主キーの場合は dbt_utils パッケージが必要。

How — モデル定義に組み込んだ例

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 で回して確認する。

関連