使用 dbt 从雪花 information_schema 中检索 table 名称

Retrieving table name from snowflake information_schema using dbt

我已经为 returns 创建了一个宏 table 来自 Snowflake 中 INFORMATION_SCHEMA 的名称。

我有 tables in snowflake 如下

------------
|  TABLES  |
------------
|   ~one   |
|   ~two   |
|  ~three  |
------------

我想将 table 类型即 one 传递到宏中并获取实际的 table 名称即 ~one

这是我在 DBT 中的宏 (get_table.sql),它接受参数和 returns table 名称

{%- macro get_table(table_type) -%}
    
    {%- set table_result -%}
        select distinct TABLE_NAME from "DEMO_DB"."INFORMATION_SCHEMA"."TABLES" where TABLE_NAME like '\~%{{table_type}}%'
    {%- endset -%}
    
    {%- set table_name = run_query(table_result).columns[0].values() -%}
  
  {{ return(table_name) }}
{%- endmacro -%}

这是调用上述宏的 DBT 模型

{{ config(materialized='table',full_refresh=true) }}

select * from {{get_table("one")}}

但是我得到一个错误:

模型编译错误

'None' 没有属性 'table'

> 在宏中 get_table (macros\get_table.sql)

我不明白错误在哪里

您需要使用执行上下文变量来防止此错误,如下所述:

https://discourse.getdbt.com/t/help-with-call-statement-error-none-has-no-attribute-table/602

您还要注意您的查询,table 名称是大写的。所以你最好用“ilike”而不是“like”。

另一个重点是,“run_query(table_result).columns[0].values()” returns 一个数组,所以我在最后添加了索引。

这是你的模块的修改版本,我在我的测试环境中成功运行它:

{% macro get_table(table_name) %}
    
    {% set table_query %}
        select distinct TABLE_NAME from "DEMO_DB"."INFORMATION_SCHEMA"."TABLES" where TABLE_NAME ilike '%{{ table_name }}%'
    {% endset %}

    {% if execute %}
        {%- set result = run_query(table_query).columns[0].values()[0] -%}
        {{return( result )}}
    {% else %}
        {{return( false ) }}
    {% endif %}
    
{% endmacro %}