dbt中latest_partition宏获取最新分区时间戳报错排查
解决dbt宏提取最新分区时间戳的报错问题
问题分析
你当前的宏返回结果是[(datetime.datetime(2022, 10, 26, 0, 0, tzinfo=datetime.timezone.utc),)],但尝试用[0][0]索引提取时出现'None' has no attribute 'data'错误,核心原因是当目标表为空时,MAX(event_timestamp)会返回NULL,导致load_result('latest_partition_query')['data']的值为None,直接索引会触发属性错误。
修改后的宏代码
{% macro latest_partition() %} {%- call statement('latest_partition_query', True) -%} SELECT TIMESTAMP_TRUNC(MAX(event_timestamp), DAY) AS latest_partition FROM {{ this }} {%- endcall -%} {%- set query_result = load_result('latest_partition_query') -%} {%- set max_timestamp = query_result['data'][0][0] if query_result['data'] else none -%} {%- do return(max_timestamp) -%} {% endmacro %}
关键改动说明
- 先把查询结果赋值给
query_result,避免重复调用load_result - 添加条件判断:只有当
query_result['data']不为空时,才执行[0][0]索引提取;如果为空(表无数据),返回none - 这样既可以在表有数据时得到单独的
datetime.datetime对象,也能在表为空时避免报错
额外优化建议
如果需要确保宏在表为空时返回一个默认值(比如当前UTC日期的零点),可以修改条件判断部分:
{%- set default_timestamp = modules.datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) -%} {%- set max_timestamp = query_result['data'][0][0] if query_result['data'] else default_timestamp -%}
内容的提问来源于stack exchange,提问作者Mrinalini Singh
相关产品推荐
相关产品推荐

