Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions sqlglot/dialects/duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,3 +1164,12 @@ def numbertostr_sql(self, expression: exp.NumberToStr) -> str:
def autoincrementcolumnconstraint_sql(self, _) -> str:
self.unsupported("The AUTOINCREMENT column constraint is not supported by DuckDB")
return ""

def detach_sql(self, expression: exp.Detach) -> str:
this = self.sql(expression, "this")
# the DATABASE keyword is required if IF EXISTS is set
# without it, DuckDB throws an error: Parser Error: syntax error at or near "exists" (Line Number: 1)
# ref: https://duckdb.org/docs/stable/sql/statements/attach.html#detach-syntax
exists_sql = " DATABASE IF EXISTS" if expression.args.get("exists") else ""

return f"DETACH{exists_sql} {this}"
6 changes: 5 additions & 1 deletion tests/dialects/test_duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1494,7 +1494,11 @@ def test_attach_detach(self):

# DETACH
self.validate_identity("DETACH new_database")
self.validate_identity("DETACH IF EXISTS file")

# when 'if exists' is set, the syntax is DETACH DATABASE, not DETACH
# ref: https://duckdb.org/docs/stable/sql/statements/attach.html#detach-syntax
self.validate_identity("DETACH IF EXISTS file", "DETACH DATABASE IF EXISTS file")
self.validate_identity("DETACH DATABASE IF EXISTS file", "DETACH DATABASE IF EXISTS file")

self.validate_identity("DETACH DATABASE db", "DETACH db")

Expand Down