Skip to content

Commit

Permalink
fix(postgres): do not use schema when renaming a table for overwrite …
Browse files Browse the repository at this point in the history
…purposes (#10771)
  • Loading branch information
cpcloud authored Feb 1, 2025
1 parent 3c13d67 commit c7ea505
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
24 changes: 11 additions & 13 deletions ibis/backends/postgres/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,6 @@ def create_table(
overwrite
If `True`, replace the table if it already exists, otherwise fail
if the table exists
"""
if obj is None and schema is None:
raise ValueError("Either `obj` or `schema` must be specified")
Expand Down Expand Up @@ -654,31 +653,30 @@ def create_table(
if not schema:
schema = table.schema()

table_expr = sg.table(temp_name, db=database, quoted=self.compiler.quoted)
target = sge.Schema(
this=table_expr, expressions=schema.to_sqlglot(self.dialect)
)
quoted = self.compiler.quoted
dialect = self.dialect

table_expr = sg.table(temp_name, db=database, quoted=quoted)
target = sge.Schema(this=table_expr, expressions=schema.to_sqlglot(dialect))

create_stmt = sge.Create(
kind="TABLE",
this=target,
properties=sge.Properties(expressions=properties),
)

this = sg.table(name, catalog=database, quoted=self.compiler.quoted)
this = sg.table(name, catalog=database, quoted=quoted)
this_no_catalog = sg.table(name, quoted=quoted)

with self._safe_raw_sql(create_stmt) as cur:
if query is not None:
insert_stmt = sge.Insert(this=table_expr, expression=query).sql(
self.dialect
)
insert_stmt = sge.Insert(this=table_expr, expression=query).sql(dialect)
cur.execute(insert_stmt)

if overwrite:
cur.execute(sge.Drop(kind="TABLE", this=this, exists=True).sql(dialect))
cur.execute(
sge.Drop(kind="TABLE", this=this, exists=True).sql(self.dialect)
)
cur.execute(
f"ALTER TABLE IF EXISTS {table_expr.sql(self.dialect)} RENAME TO {this.sql(self.dialect)}"
f"ALTER TABLE IF EXISTS {table_expr.sql(dialect)} RENAME TO {this_no_catalog.sql(dialect)}"
)

if schema is None:
Expand Down
14 changes: 14 additions & 0 deletions ibis/backends/postgres/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,3 +438,17 @@ def test_parsing_oid_dtype(con):
# Load a table that uses the OID type and check that we map it to Int64
t = con.table("pg_class", database="pg_catalog")
assert t.oid.type() == ibis.dtype("int64")


@pytest.fixture
def tmp_db(con):
name = gen_name("tmp_db")
con.create_database(name)
yield name
con.drop_database(name, cascade=True)


def test_create_table_overwrite(con, tmp_db):
name = gen_name("overwrite_test")
t = con.create_table(name, schema={"id": "int32"}, database=tmp_db, overwrite=True)
assert t.schema() == ibis.schema({"id": dt.int32})

0 comments on commit c7ea505

Please sign in to comment.