Repository navigation
Closed
Labels
Milestone
Description
note to users
a fix here is targeted at 2.0. for a decent engine-level configuration to work around this on PostgreSQL, MySQL/MariaDB, SQLite for 1.4/1.3, see #7471 (comment)
Describe the bug
When you have
- two tables with the same name
- one of those tables lives in the public schema
- the other is some other schema
- and both tables show up in a join on a query
the public one does not qualify itself, and becomes ambiguous in the query
I would ideally want this to qualify the query with public. (either through the dialect's default schema or i guess perhaps this relates to the search_path), or else for sqlalchemy to realize this is about to happen and internally alias the ambiguous table
To Reproduce
from sqlalchemy import Column, create_engine, ForeignKey, Integer
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm.session import sessionmaker
Base = declarative_base()
class Foo(Base):
__tablename__ = "foo"
__table_args__ = dict(schema="foo")
id = Column(Integer, primary_key=True)
class Bar(Base):
__tablename__ = "foo"
id = Column(ForeignKey("foo.foo.id"), primary_key=True)
foo = relationship("Foo", uselist=False)
engine = create_engine(
URL(
host="localhost",
drivername="postgresql+psycopg2",
username="user",
password="password",
database="postgres",
port="5532",
)
)
engine.execute("drop schema if exists foo cascade")
engine.execute("create schema foo")
Base.metadata.create_all(engine)
Session = sessionmaker()
session = Session(bind=engine)
session.query(Bar).join(Foo).all()Error
/foo/meow.py:26: SADeprecationWarning: Calling URL() directly is deprecated and will be disabled in a future release. The public constructor for URL is now the URL.create() method.
URL(
Traceback (most recent call last):
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.AmbiguousAlias: table reference "foo" is ambiguous
LINE 2: FROM foo JOIN foo.foo ON foo.foo.id = foo.id
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/foo/meow.py", line 43, in <module>
session.query(Bar).join(Foo).all()
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 2759, in all
return self._iter().all()
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 2894, in _iter
result = self.session.execute(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 1689, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement
ret = self._execute_context(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1845, in _execute_context
self._handle_dbapi_exception(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "/foo/.venv/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.AmbiguousAlias) table reference "foo" is ambiguous
LINE 2: FROM foo JOIN foo.foo ON foo.foo.id = foo.id
^
[SQL: SELECT foo.id AS foo_id
FROM foo JOIN foo.foo ON foo.foo.id = foo.id]
Versions
- Python: 3.7+
- SQLAlchemy: 1.3+
- Database: postgres
- DBAPI: psycopg2
Additional context
No response
Reacted by Tanmay Shishodia, Angel Angelov, Akash Agarwal and Matthias
Activity
zzzeek commentedon Dec 17, 2021
confirmed PostgreSQL doesn't want to assume "public" for the non-qualified table, which is unfortunate.
this is a very unusual use case and you certainly can schema-qualify tables as public, just set up the mapping as such and your MCVE (works perfectly, thanks) works fine
[-]Tables with the same name (in different schemas) emit ambiguous joins[/-][+]Tables with the same name (in different schemas) doesn't schema-qualifiy the local table which seems to fail on PostgreSQL[/+]zzzeek commentedon Dec 17, 2021
Okey doke mysql has the same problem
[-]Tables with the same name (in different schemas) doesn't schema-qualifiy the local table which seems to fail on PostgreSQL[/-][+]Tables with the same name (in different schemas) doesn't schema-qualifiy the local table which seems to fail on PostgreSQL/mysql/ others?[/+]CaselIT commentedon Dec 17, 2021
I think this may be uncommon enough that the solution could be to qualify the schema in both tables
zzzeek commentedon Dec 17, 2021
good news, the behavior can be reproduced with any schema name, it's just the two tables in same schema that have the problem, which eases testing burden. can target this sooner as a result.
9 remaining items
zzzeek commentedon Dec 18, 2021
to add automatic aliasing into the compiler, rather than at the SQL construction level which is where we've historically done this (the whole adapt() thing), is somewhat doable but it would add a burden to all table rendering everywhere, that this additional context has to be passed through and checked in the same way we do for columns etc., it would be all over the place. doesn't feel worth it yet though it would be more consistent for how we alias same-named columns.
DanCardin commentedon Dec 18, 2021
For what it's worth, we went to go qualify it first. Although I think we were qualifying the foreign key, i dont recall if we also qualified the table, i can try to check later. But we noticed a similar issue to https://stackoverflow.com/questions/53523529/alembic-revision-autogenerate-produces-redundant-foreign-key-migrations, wherein alembic would start autogenerating a drop/create index statement that you couldn't resolve.
(and i dont personally care whatsoever about modified search_paths, if that makes any difference to you 😝)
zzzeek commentedon Dec 18, 2021
the alembic thing is a completely different issue and they are needing to configure their autogenerate correctly, that has nothing to do with the issue here of a statement with two same-named tables.
Since the schema qualify fix does not work on SQL Server or Oracle and probably other database, and additionally wont work with PostgreSQL multiple search path tokens, and also that we do similar aliasing with columns in any case, I think it's more appropriate that this uses an anomized alias name in the SQL statement as we can in fact do that here now that I looked. the one thing I can see going wrong is if we have an alias name like "mytable_1" and there's also a table named "mytable_1" that's used in the statement explicitly, we aren't checking for that right now, but in fact that potential bug isn't new at all as that would already happen with any anonymous alias() construct anyway.
the bad news here is that I think this should be targeted at 2.0 and not 1.4 as 1.4 is already up to 1.4.29 and there's a chance this behavioral change will cause regressions. so for the time being you'll need to stick with workarounds of using "public" schema or using aliases for that table.
[-]Tables with the same name (in different schemas) doesn't schema-qualifiy the local table which seems to fail on PostgreSQL/mysql/ others?[/-][+]Tables with the same name (in different schemas) doesn't schema-qualifiy or disambiguate the local table name[/+]DanCardin commentedon Dec 18, 2021
As suggested, the only update I make to the MCVE is:
Can you explain what's wrong with the following setup then? (and perhaps, i should bring this to alembic, but it's related to this overall issue regardless, i think)
I just quickly ran
alembic initagainst this, with just 2 changes:context.configure(connection=connection, target_metadata=target_metadata, include_schemas=True)First revision:
looks great!
from then on, every subsequent autogenerate will generate:
zzzeek commentedon Dec 18, 2021
OK the problem with Alembic and "public" is because of how SQLAlchemy implements table reflection, where it considers the default schema on the database connection, in this case the value of
current_schema()which ispublic, to be special . so when tables are reflected that have foreign keys to other tables in "public", things can get confusing. I've recently updated the docs to be extremely in-depth on this issue which you can see here: https://docs.sqlalchemy.org/en/14/core/reflection.html#interaction-of-schema-qualified-reflection-with-the-default-schema .now if your alembic setup is working fine, then that's great, this is only autogenerate, it's not something you run in "production".
I would add that another way to get the "public" schema in your application without it being in your table metadata is to use the schema_translate_map feature, and in fact you might like this a lot better because it's essentially an engine option. We can write your program above as:
I think that's likely your best option here, that way you can change that schema name if you wanted to run on another kind of database or schema structure, and you also can use Alembic in plain vanilla mode without the chance of foreign key constraints coming out wrong.
DanCardin commentedon Dec 18, 2021
We run pytest-alembic which, for better or worse, asserts that our autogenerate remains empty (plus it'd otherwise be an annoyance we'd have to ignore/remove every time)
But can confirm that
schema_translate_mapat least seems to work with the test case, including appeasing alembic's autogenerate. So that seems like the solution for now, thanks!zzzeek commentedon Dec 18, 2021
it's gotten as far as a legit pytest plugin now huh. a cautionary tale to anyone who wants to write some code that will "save some typing for developers" :)
ok great. schema translate map has been a tricky feature to get right so let me know if it screws anything up