【dbt】dbt Macro ~ load_relation ~

◾️はじめに

小ネタ。

dbtマクロ load_relation() について扱う

目次

【1】load_relation()
  1)Relation object
【2】サンプル
【3】使用例

【1】load_relation()

https://docs.getdbt.com/reference/dbt-jinja-functions/adapter#load_relation

* テーブル存在チェックで使用するdbtマクロ
 => あれば Relation object(下記1)参照), なければ、Noneを返す
 => 「【2】サンプル」を見た方が理解が早い

1)Relation object

* dbt 内のDB/Schema/Tableをオブジェクト化したもの?

https://docs.getdbt.com/reference/dbt-classes#relation

class Relation:
  def create(database=None, schema=None, identifier=None,
             type=None):
  """
    database (optional): The name of the database for this relation
    schema (optional): The name of the schema (or dataset, if on BigQuery) for this relation
    identifier (optional): The name of the identifier for this relation
    type (optional): Metadata about this relation, eg: "table", "view", "cte"
  """

【2】サンプル

-- Step1: load_relation() を呼び出す
{% set relation_exists = load_relation(ref('demo_model')) is not none %}
-- {% set relation_exists = load_relation(this) is not none %}

-- Step2: テーブル存在チェック
{% if relation_exists %}
  {{ log("demo_model has already been built", info=true) }}
{% else %}
  {{ log("demo_model doesn't exist in the warehouse. Maybe it was dropped?", info=true) }}
{% endif %}

【3】使用例

* 初回実行時にはテーブルがない場合に、テーブル存在チェックに使う

関連記事

dbt ~ 環境設定編 ~
https://dk521123.hatenablog.com/entry/2023/12/16/152147
dbt ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2023/06/30/000000
dbt ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/05/30/151003
dbt ~ 条件分岐 ~
https://dk521123.hatenablog.com/entry/2024/09/11/003301
dbt Macro ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/11/29/003751
dbt ~ 更新 / DROP + CTAS ~
https://dk521123.hatenablog.com/entry/2023/12/04/000000
dbt ~ materialized='incremental'で更新前データを使用したい場合 ~
https://dk521123.hatenablog.com/entry/2025/09/04/000906