■ はじめに
Python から dbt を使う必要がでてきたので、メモ。
目次
【1】環境設定 【2】dbt の Python モジュール 1)dbtRunner 2)dbtRunnerResult 【3】補足1:tags
【1】環境設定
* 今回は、以下の構成で行う
| Items | Values | Memo |
|---|---|---|
| OS | Windows11 | |
| DB | PostgreSQL 16.1 | select version(); で確認 |
| DBT | dbt v1.8.3 | |
| Python | Python v3.12.4 |
* DBTのインストールについては、以下の関連記事を参照のこと
dbt ~ 環境設定編 ~
https://dk521123.hatenablog.com/entry/2023/12/16/152147
# より抜粋 # インストール pip install dbt-core dbt-postgres
【2】dbt の Python モジュール
* まずは、実行の流れを以下の公式ドキュメントより抜粋
https://docs.getdbt.com/reference/programmatic-invocations
from dbt.cli.main import dbtRunner, dbtRunnerResult # initialize dbt = dbtRunner() # create CLI args as a list of strings # 詳細は 「【3】補足1:tags」参照 cli_args = ["run", "--select", "tag:my_tag"] # run the command res: dbtRunnerResult = dbt.invoke(cli_args) # inspect the results for r in res.result: print(f"{r.node.name}: {r.status}")
1)dbtRunner
* DBT 実行クラス
invoke()
* 実行関数
例
dbt.invoke(["--fail-fast", "run", "--select", "tag:my_tag"]) dbt.invoke(["run"], select=["tag:my_tag"], fail_fast=True)
2)dbtRunnerResult
* 実行結果クラス
https://docs.getdbt.com/reference/programmatic-invocations#dbtrunnerresult
adapter_response
* アダプタによって異なるが、データベースから返されるメタデータの辞書 => たとえば、成功コードや影響を受けた行数、処理したバイト数など
例
{'_message': 'SELECT 5', 'code': 'SELECT', 'rows_affected': 5} # 詳細は、以下の関連記事を参照のこと
Python with dbt ~ rows_affected ~
https://dk521123.hatenablog.com/entry/2024/09/02/234559
【3】補足1:tags
* tagを付与することにより、 各種dbtコマンド実行時に実行対象とすることができる
https://docs.getdbt.com/reference/resource-configs/tags
https://dev.classmethod.jp/articles/dbt-tag-check-detailed-behavior/
関連記事
dbt ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2023/06/30/000000
dbt ~ 環境設定編 ~
https://dk521123.hatenablog.com/entry/2023/12/16/152147
dbt ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/05/30/151003
dbt CLI ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2024/07/21/234811
Python with dbt ~基本編 ~
https://dk521123.hatenablog.com/entry/2025/04/26/234102
Python with dbt ~ rows_affected ~
https://dk521123.hatenablog.com/entry/2024/09/02/234559