Retrieving table name from snowflake information_schema using dbt

R0b*_*ert 2 sql snowflake-cloud-data-platform dbt

I have created a macro to returns a table name from the INFORMATION_SCHEMA in Snowflake.

I have tables in snowflake as follows

------------
|  TABLES  |
------------
|   ~one   |
|   ~two   |
|  ~three  |
------------
Run Code Online (Sandbox Code Playgroud)

I want to pass the table type i.e. one into the macro and get the actual table name i.e. ~one

Here is my macro(get_table.sql) in DBT that takes in parameter and returns the table name

{%- 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 -%}
Run Code Online (Sandbox Code Playgroud)

Here is my DBT Model that calls the above macro

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

select * from {{get_table("one")}}
Run Code Online (Sandbox Code Playgroud)

But I am getting an error:

Compilation Error in model

'None' has no attribute 'table'

> in macro get_table (macros\get_table.sql)

I don't understand where the error is

Gok*_*til 5

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

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

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

另一个重要的点是,“run_query(table_result).columns[0].values()”返回一个数组,所以我在末尾添加了索引。

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

{% 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 %}
Run Code Online (Sandbox Code Playgroud)