dbt对接PostgreSQL时引用表被误判为列:'section1不存在'错误求助
dbt对接PostgreSQL时模型引用错误排查
错误现象
section2模型中引用section1表时,dbt将其识别为列,报错:column 'section1' does not exist
错误详情
Database Error in model section2 (models\example\section2.sql) column "section1" does not exist LINE 9: FROM ref( section1 ) S1 ^
项目信息
目录结构
/dbtxyz/models/example/section1.sql /dbtxyz/models/example/section2.sql /dbtxyz/project.yml /dbtxyz/profile.yml
profile.yml配置
default: outputs: dev: type: "postgres" host: "localhost" user: "postgres" password: "password" port: 5432 dbname: "myprojectdata" schema: "myprojectdataschema" target: "dev"
project.yml配置
analysis-paths: - analyses clean-targets: - target - dbt_packages config-version: 2 macro-paths: - macros model-paths: - models models: dbtsample: example: +materialized: view name: dbtxyz profile: default seed-paths: - seeds snapshot-paths: - snapshots test-paths: - tests vars: leverage: 123 version: 1.0.0
模型代码
section1.sql
{{ config(materialized='table') }} {% set leverage= var('leverage') %} WITH section1 AS ( SELECT T0.* FROM table0 T0 WHERE T0."leverage" > {{ leverage }} ) SELECT * FROM section1
section2.sql(错误版本)
{{ config(materialized='table') }} WITH section2 AS ( SELECT T1.*, S1.* FROM ref( {{section1}} ) S1 JOIN table1 T1 ON S1."id" = T1."id" ) SELECT * FROM section2
问题原因
- ref函数用法错误:section2中使用
ref( {{section1}} )是错误语法。ref函数需要传入模型名称的字符串(用单引号包裹),而{{section1}}是jinja变量引用,但未定义该变量,导致dbt渲染SQL时,直接将section1作为无引号的标识符传入PostgreSQL,PostgreSQL将其解析为列名而非表名。 - 项目命名空间不匹配:project.yml中
name为dbtxyz,但models配置下的命名空间是dbtsample,这会导致模型完整名称为dbtsample.example.section1,可能影响ref的识别(非本次报错直接原因,但需修正避免后续问题)。
解决方案
1. 修正ref函数调用
将section2.sql中的错误引用改为正确的ref用法:
{{ config(materialized='table') }} WITH section2 AS ( SELECT T1.*, S1.* FROM {{ ref('section1') }} S1 JOIN table1 T1 ON S1."id" = T1."id" ) SELECT * FROM section2
解释:{{ ref('section1') }}是dbt标准的模型引用方式,会自动解析为section1模型对应的数据库表名(包含schema),避免PostgreSQL将其识别为列。
2. 修正project.yml的模型命名空间
将project.yml中models下的dbtsample改为项目名称dbtxyz,确保命名空间一致:
models: dbtxyz: example: +materialized: view
解释:dbt模型命名空间默认与project.yml中的name一致,这样ref可以更准确识别同项目下的模型,避免跨命名空间识别问题。
3. 验证执行
修改完成后,重新执行dbt命令:
dbt run --model section2
内容的提问来源于stack exchange,提问作者bdlock
相关产品推荐
相关产品推荐

