dbt Classes

dbt Classes

dbt는 데이터 웨어하우스의 객체, dbt 프로젝트의 일부, 그리고 명령어의 결과를 나타내는 여러 클래스(class)를 갖고 있어요. 이 클래스들은 고급 dbt 모델과 매크로를 만들 때 자주 유용해요.

출처: 문서

본문

Relation

Relation 객체는 적절한 quoting(인용)으로 스키마와 테이블 이름을 SQL 코드에 보간(interpolate)하는 데 사용돼요. {{ schema }}.{{ table }} 값을 직접 보간하는 대신 항상 이 객체를 사용해야 해요. Relation 객체의 quoting은 quoting config로 구성할 수 있어요.

Relation 만들기 (Creating relations)

Relation은 Relation 클래스의 create 클래스 메서드를 호출해서 만들 수 있어요.

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"
  """

Relation 사용하기 (Using relations)

api.Relation.create 외에도, ref, source 또는 this를 사용할 때 dbt는 Relation을 반환해요.

relation_usage.sql:

{% set relation = api.Relation.create(schema='snowplow', identifier='events') %}

-- Return the `database` for this relation
{{ relation.database }}

-- Return the `schema` (or dataset) for this relation
{{ relation.schema }}

-- Return the `identifier` for this relation
{{ relation.identifier }}

-- Return relation name without the database
{{ relation.include(database=false) }}

-- Return true if the relation is a table
{{ relation.is_table }}

-- Return true if the relation is a view
{{ relation.is_view }}

-- Return true if the relation is a cte
{{ relation.is_cte }}

Column

Column 객체는 relation 안의 컬럼에 대한 정보를 인코딩하는 데 사용돼요.

column.py:

class Column(object):
  def __init__(self, column, dtype, char_size=None, numeric_size=None):
    """
      column: The name of the column represented by this object
      dtype: The data type of the column (database-specific)
      char_size: If dtype is a variable width character type, the size of the column, or else None
      numeric_size: If dtype is a fixed precision numeric type, the size of the column, or else None
   """


# Example usage:
col = Column('name', 'varchar', 255)
col.is_string() # True
col.is_numeric() # False
col.is_number() # False
col.is_integer() # False
col.is_float() # False
col.string_type() # character varying(255)
col.numeric_type('numeric', 12, 4) # numeric(12,4)

Column API

Properties

  • char_size: character varying 컬럼의 최대 크기를 반환해요
  • column: 컬럼의 이름을 반환해요
  • data_type: 컬럼의 데이터 타입을 반환해요(크기/정밀도/스케일 포함)
  • dtype: 컬럼의 데이터 타입을 반환해요(크기/정밀도/스케일 제외)
  • name: 컬럼의 이름을 반환해요(column과 동일하며, 별칭으로 제공돼요)
  • numeric_precision: 고정 소수 컬럼의 최대 정밀도를 반환해요
  • numeric_scale: 고정 소수 컬럼의 최대 스케일을 반환해요
  • quoted: 따옴표로 감싼 컬럼 이름을 반환해요

Instance methods

  • is_string(): 컬럼이 String 타입(예: text, varchar)이면 True, 아니면 False를 반환해요
  • is_numeric(): 컬럼이 고정 정밀도 Numeric 타입(예: numeric)이면 True, 아니면 False를 반환해요
  • is_number(): 컬럼이 number 계열 타입(예: numeric, int, float 등)이면 True, 아니면 False를 반환해요
  • is_integer(): 컬럼이 정수(예: int, bigint, serial 등)이면 True, 아니면 False를 반환해요
  • is_float(): 컬럼이 float 타입(예: float, float64 등)이면 True, 아니면 False를 반환해요
  • string_size(): 컬럼이 문자열 타입이면 그 폭(width)을 반환하고, 아니면 예외를 발생시켜요

Static methods

  • string_type(size): 데이터베이스에서 사용 가능한 문자열 타입 표현을 반환해요(예: character varying(255))
  • numeric_type(dtype, precision, scale): 데이터베이스에서 사용 가능한 numeric 타입 표현을 반환해요(예: numeric(12, 4))

Column 사용하기 (Using columns)

column_usage.sql:

-- String column
{%- set string_column = api.Column('name', 'varchar', char_size=255) %}

-- Return true if the column is a string
{{ string_column.is_string() }}

-- Return true if the column is a numeric
{{ string_column.is_numeric() }}

-- Return true if the column is a number
{{ string_column.is_number() }}

-- Return true if the column is an integer
{{ string_column.is_integer() }}

-- Return true if the column is a float
{{ string_column.is_float() }}

-- Numeric column
{%- set numeric_column = api.Column('distance_traveled', 'numeric', numeric_precision=12, numeric_scale=4) %}

-- Return true if the column is a string
{{ numeric_column.is_string() }}

-- Return true if the column is a numeric
{{ numeric_column.is_numeric() }}

-- Return true if the column is a number
{{ numeric_column.is_number() }}

-- Return true if the column is an integer
{{ numeric_column.is_integer() }}

-- Return true if the column is a float
{{ numeric_column.is_float() }}

-- Static methods

-- Return the string data type for this database adapter with a given size
{{ api.Column.string_type(255) }}

-- Return the numeric data type for this database adapter with a given precision and scale
{{ api.Column.numeric_type('numeric', 12, 4) }}

BigQuery columns

BigQuery dbt 프로젝트에서는 Column 타입이 BigQueryColumn으로 오버라이드돼요. 이 객체는 위에서 설명한 Column 타입과 동일하게 동작하며, 추가 properties와 methods만 더해져요.

Properties

  • fields: 컬럼이 STRUCT라면 필드 안에 포함된 하위 필드(subfield) 목록을 반환해요
  • mode: 컬럼의 "mode"를 반환해요, 예: REPEATED

Instance methods

flatten(): 하위 필드를 각각 자신의 컬럼으로 확장한 BigQueryColumn의 평면화된(flattened) 목록을 반환해요. 예를 들어 이 중첩 필드:

[{"hits": {"pageviews": 1, "bounces": 0}}]

는 다음과 같이 확장돼요:

[{"hits.pageviews": 1, "hits.bounces": 0}]

Result objects

dbt에서 리소스를 실행하면 Result 객체가 생성돼요. 이 객체는 실행된 노드, 타이밍, 상태(status), 어댑터가 반환한 메타데이터에 대한 정보를 포함해요. 호출(invocation)이 끝나면 dbt는 이 객체들을 run_results.json에 기록해요.

  • node: 실행된 dbt 리소스(모델, 시드, 스냅샷, 테스트)의 전체 객체 표현으로, unique_id를 포함해요
  • status: 런타임 성공·실패·에러에 대한 dbt의 해석이에요
  • thread_id: 이 노드를 실행한 스레드는 무엇인가요? 예: Thread-1
  • execution_time: 이 노드를 실행하는 데 소요된 총 시간으로, 초 단위예요
  • timing: 실행 시간을 단계로 나눈 배열이에요(보통 compile + execute)
  • message: 데이터베이스에서 반환된 정보에 기반해 dbt가 CLI에서 이 결과를 어떻게 보고할지예요
  • adapter_response: 어댑터에 따라 달라지는, 데이터베이스에서 반환된 메타데이터 사전이에요. 예를 들어 성공 코드, rows_affected 수, total bytes_processed 등이에요. 데이터 테스트에는 적용되지 않아요.
  • rows_affected: 마지막으로 실행된 문장에 의해 수정된 행 수를 반환해요. 쿼리의 행 수를 알 수 없거나 적용할 수 없는 경우(예: 뷰를 만들 때) rowcount에 표준 값 -1이 반환돼요.

더 알아보기 (Learn more)

  • 관계와 컬럼 API를 사용한 고급 매크로는 Jinja reference 문서를 참고하세요.