Constraint already exists error for v2 materialization and safer flag
Describe the bug
When having persist_docs true for both relationship and column, using use_materialization_v2: true and +use_safer_relation_operations: true in dbt_project.yml, re-running a model with existing constraints results in the error:
Constraint '<table_name>__dbt_stg_pk' already exists in database
This occurs even though the model was previously built successfully. It seems that the safer relation operations do not handle existing constraints gracefully.
Steps To Reproduce
- Configure dbt_project.yml:
flags:
use_materialization_v2: true
models:
my_schema:
+use_safer_relation_operations: true
+persist_docs:
relation: true
columns: true
- Create two models:
primary_table.sql:
{{
config(
materialized='table',
schema='my_schema'
)
}}
SELECT 1 AS col_id, 'value1' AS col_value
UNION ALL
SELECT 2 AS col_id, 'value2' AS col_value
foreign_table.sql:
{{
config(
materialized='table',
schema='my_schema'
)
}}
SELECT 1 AS col_id, 'value1' AS col_value
UNION ALL
SELECT 2 AS col_id, 'value2' AS col_value
- Define constraints in my_schema.yml:
version: 2
models:
- name: primary_table
description: "A test table with primary key constraint."
columns:
- name: col_id
description: "Primary key column."
tests:
- unique
- not_null
constraints:
- type: not_null
- type: primary_key
- name: col_value
description: "A test value column."
- name: foreign_table
description: "A test table with a foreign key to primary_table."
columns:
- name: col_id
description: "Foreign key referencing primary_table.col_id."
tests:
- not_null
constraints:
- type: not_null
- type: foreign_key
to: ref('primary_table')
to_columns: [col_id]
- name: col_value
description: "A test value column."
- Run the models:
dbt run --select primary_table dbt run --select foreign_table dbt run --select primary_table (This run fails with the constraint already exists error.)
Expected behavior
Rerunning the primary_table model should succeed without errors, even when constraints are already present.
Screenshots and log output
If applicable, add screenshots or log output to help explain your problem.
System information
The output of dbt --version:
Core:
- installed: 1.9.4
- latest: 1.10.3 - Update available!
Plugins:
- databricks: 1.10.1 - Update available!
- spark: 1.9.2 - Up to date!
The operating system you're using:
The output of python --version:
Additional context
This issue seems related to the interaction between use_materialization_v2 and use_safer_relation_operations. When use_safer_relation_operations is enabled, dbt creates a staging table and then renames it to replace the target table. However, if constraints already exist, the process fails during the rename operation due to existing constraints.
According to the Databricks adapter behavior changes documentation, the use_safer_relation_operations flag is intended to prevent partial failures by using a staging-and-rename approach. However, it appears that existing constraints are not being handled gracefully during this process.
I believe this will be fixed in 1.10.5. @ericj-db to confirm.
@benc-db this is a different issue from https://github.com/databricks/dbt-databricks/issues/1081. But I am currently taking a look and aiming to fix in 1.10.5 as well
@DanyloAntsybor would you be able to share the full dbt.log? I tried to reproduce this issue using the same dbt-databricks version and setup as you, but the model runs are successful (repro attempt: https://github.com/databricks/dbt-databricks/commit/3514c298ed96aac8ab33a16829416b226168b124)
@ericj-db something very weird is happening here. Likely there is some lag or kind of internal DataBricks system process behind the scenes.
So what I did in my dev env:
- created same folders and config.
- executed
dbt run -s primary_table foreign_tablefor thefirsttime - Successfully as expected - executed
dbt run -s primary_table foreign_tablefor thesecondtime - what a surprise also succesfully (here is when I got confused) - executed
dbt run -s primary_table foreign_tablefor thethirdtime - now the Error: Constraint 'primary_table__dbt_stg_pk' already exists in database 'development_modeled'.'danylo_test'is here
Attaching dbt.log
Hey @ericj-db 👋 Were you able to reproduce the issue?
I believe that it works two times because you did not put a name on your pk, it then infer the name of the pk based on the relation name. What _ use_safer_relation_operations_ does is :
- First run: create the actual table and creates primary_table_pk
- Second run: creates a staging table called primary_table__dbt_stg and its corresponding pk primary_table__dbt_stg_pk then does its renaming relations BUT the pk name of the now called primary_table is still primary_table__dbt_stg_pk
- Third run: tries to recreate primary_table__dbt_stg and its corresponding pk primary_table__dbt_stg_pk but it already exists.
If you name your pk it should fail on the second run. @ericj-db in your repro attempt, you ran the model "only" two times so it worked.
One of the workarounds we are using now for small number of tables: Adding a pre-hook that does DROP primary key CASCADE. The thing is, that this will drop all foreign-key constraints for other tables that have fk on that table. And then those fk will be recreated only later when the dbt will run those tables. Or we need to do some system tables search to recreate them as part of post-hook.
As we orchestrate our dbt jobs in Airflow it adds complexity also to add those dependencies so that fk tables are executed after pk tables, which doesn't always needed/wanted behaviour.
I believe this is happening due to how constraints.py adds the primary key. When you run a model with the full refresh and safer relations
It does a create or replace table statement where it adds the primary like PRIMARY KEY (column_name) to the sql, when it's added like this PRIMARY KEY (dim_territory_sk)
, it's created with the default name based on the table. When the table gets renamed, the constraint does not, so the next time it runs, and the stg relation gets created it will create the constraint with the same name therefore failing.
https://github.com/databricks/dbt-databricks/blob/main/dbt/adapters/databricks/constraints.py#L98
I am currently facing the same issue on version 1.11.0 of the adapter.
@ericj-db I saw earlier that you thought there was a fix, do you know if this has a fix?
An example of the sql generated for the stg relation when doing a create or replace.
Hey @benc-db @ericj-db could you please provide some update to this issue?
@sd-db viz
I am still seeing this issue in 1.11.6 if not mistaken?
Do we have any news on this regard?
#1561 should resolve this issue as well. Looking to merge this week and have initial cut for v1.13.0. FYI @cpuerto-addi @MCRE-BE
#1561 should resolve this issue as well. Looking to merge this week and have initial cut for
v1.13.0. FYI @cpuerto-addi @MCRE-BE
Amazing, ty man