Skip to content

Tables with the same name (in different schemas) doesn't schema-qualifiy or disambiguate the local table name #7471

Closed

Description

@DanCardin

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

Activity

  1. added
    requires triage
    on Dec 17, 2021
  2. added
    bug
    and removed
    requires triage
    on Dec 17, 2021
  3. added this to the 1.x.xx milestone on Dec 17, 2021
  4. zzzeek commented on Dec 17, 2021

    @zzzeek
    Member

    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

    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"
        __table_args__ = dict(schema="public")
    
        id = Column(ForeignKey("foo.foo.id"), primary_key=True)
    
        foo = relationship("Foo", uselist=False)
    
    
    engine = create_engine(
        "postgresql://scott:tiger@localhost/test", echo='debug'
    )
    
    
    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()
  5. added
    great mcve
    on Dec 17, 2021
  6. changed the title [-]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[/+] on Dec 17, 2021
  7. zzzeek commented on Dec 17, 2021

    @zzzeek
    Member

    Okey doke mysql has the same problem

    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"
        
        # same issue on MySQL if this is not present
        #__table_args__ = dict(schema="test")
    
        id = Column(ForeignKey("foo.foo.id"), primary_key=True)
    
        foo = relationship("Foo", uselist=False)
    
    
    
    #engine = create_engine("postgresql://scott:tiger@localhost/test", echo='debug')
    #with engine.begin() as conn:
    #    conn.execute("drop schema if exists foo cascade")
     #   conn.execute("create schema foo")
    
    engine = create_engine("mysql://scott:tiger@localhost/test", echo='debug')
    with engine.begin() as conn:
        conn.execute("create database if not exists foo")
    Base.metadata.create_all(engine)
    Session = sessionmaker()
    session = Session(bind=engine)
    
    session.query(Bar).join(Foo).all()
  8. changed the title [-]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?[/+] on Dec 17, 2021
  9. CaselIT commented on Dec 17, 2021

    @CaselIT
    Member

    I think this may be uncommon enough that the solution could be to qualify the schema in both tables

  10. zzzeek commented on Dec 17, 2021

    @zzzeek
    Member

    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.

  11. removed this from the 1.x.xx milestone on Dec 17, 2021
  12. 9 remaining items

  13. zzzeek commented on Dec 18, 2021

    @zzzeek
    Member

    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.

  14. modified the milestones: 1.4.x, 2.0 on Dec 18, 2021
  15. DanCardin commented on Dec 18, 2021

    @DanCardin
    Author

    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 😝)

  16. zzzeek commented on Dec 18, 2021

    @zzzeek
    Member

    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.

  17. changed the title [-]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[/+] on Dec 18, 2021
  18. DanCardin commented on Dec 18, 2021

    @DanCardin
    Author

    As suggested, the only update I make to the MCVE is:

    class Bar(Base):
        __tablename__ = "foo"
        __table_args__ = dict(schema="public")

    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 init against this, with just 2 changes:

    • update the alembic.ini to point at the database
    • update env.py to set context.configure(connection=connection, target_metadata=target_metadata, include_schemas=True)

    First revision:

    def upgrade():
        op.execute("create schema foo") # manually added this, obviously
        op.create_table("foo", sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), schema="foo")
        op.create_table(
            "foo",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.ForeignKeyConstraint(
                ["id"],
                ["foo.foo.id"],
            ),
            sa.PrimaryKeyConstraint("id"),
        )

    looks great!

    from then on, every subsequent autogenerate will generate:

    def upgrade():
        op.drop_constraint('foo_id_fkey', 'foo', type_='foreignkey')
        op.create_foreign_key(None, 'foo', 'foo', ['id'], ['id'], source_schema='public', referent_schema='foo')
  19. zzzeek commented on Dec 18, 2021

    @zzzeek
    Member

    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 is public, 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:

    from sqlalchemy import Column
    from sqlalchemy import create_engine
    from sqlalchemy import ForeignKey
    from sqlalchemy import Integer
    from sqlalchemy import text
    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(
        "postgresql://scott:tiger@localhost/test",
        echo="debug",
        execution_options={"schema_translate_map": {None: "public"}},
    )
    with engine.begin() as conn:
        conn.execute(text("drop schema if exists foo cascade"))
        conn.execute(text("create schema foo"))
    
    Base.metadata.create_all(engine)
    Session = sessionmaker()
    session = Session(bind=engine)
    
    session.query(Bar).join(Foo).all()

    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.

  20. DanCardin commented on Dec 18, 2021

    @DanCardin
    Author

    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_map at least seems to work with the test case, including appeasing alembic's autogenerate. So that seems like the solution for now, thanks!

  21. zzzeek commented on Dec 18, 2021

    @zzzeek
    Member

    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)

    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" :)

    But can confirm that schema_translate_map at least seems to work with the test case, including appeasing alembic's autogenerate. So that seems like the solution for now, thanks!

    ok great. schema translate map has been a tricky feature to get right so let me know if it screws anything up

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggreat mcvesql

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions