Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NoReferencedTableError with schema #668

Closed
halfdan opened this issue Jan 26, 2019 · 2 comments
Closed

NoReferencedTableError with schema #668

halfdan opened this issue Jan 26, 2019 · 2 comments

Comments

@halfdan
Copy link

halfdan commented Jan 26, 2019

Similar issues:

Traceback (most recent call last):
  File "app.py", line 63, in <module>
    db.create_all()
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 963, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 955, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 4005, in create_all
    tables=tables)
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1940, in _run_visitor
    conn._run_visitor(visitorcallable, element, **kwargs)
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1549, in _run_visitor
    **kwargs).traverse_single(element)
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/sql/ddl.py", line 736, in visit_metadata
    [t for t in tables if self._can_create_table(t)])
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/sql/ddl.py", line 1101, in sort_tables_and_constraints
    dependent_on = fkc.referred_table
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 3003, in referred_table
    return self.elements[0].column.table
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 767, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/Users/halfdan/flsqla-schema/.venv/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 1892, in column
    tablekey)
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'company_list_item.company_id' could not find table 'companies' with which to generate a foreign key to target column 'id'

Code that reproduces the error:


from flask import Flask
from sqlalchemy import (
    Column,
    Integer,
    Text,
    func,
    String,
    Boolean,
    DateTime,
    Date,
    TIMESTAMP,
    ForeignKey,
    or_,
    and_,
    UniqueConstraint,
)
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import expression
from sqlalchemy.ext.declarative import AbstractConcreteBase
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost/flsqla"
db = SQLAlchemy()

class List(db.Model):
    __tablename__ = "lists"
    __table_args__ = {"schema": "public"}

    id = Column(Integer, primary_key=True)
    label = Column(String(50), nullable=False)
    items = relationship("ListItem", back_populates="llist")


class Company(db.Model):
    __tablename__ = "companies"
    __table_args__ = {"schema": "public"}

    id = Column(Integer, primary_key=True)
    label = Column(String(50), nullable=False)
    tracked = Column(Boolean, server_default=expression.true(), nullable=False)


class ListItem(db.Model):
    __abstract__ = True
    id = Column(Integer, primary_key=True)


class CompanyListItem(ListItem):
    __tablename__ = "company_list_item"
    __table_args__ = {"schema": "public"}

    company_id = Column(ForeignKey("companies.id", deferrable=True, initially="DEFERRED"), nullable=False)
    company = relationship("Company", primaryjoin="CompanyListItem.company_id == Company.id")

    __mapper_args__ = {"polymorphic_identity": "company_item", "concrete": True}


with app.app_context():
    db.init_app(app)
    db.create_all()

Removing the table args fixes the problem but it's clearly a bug that even though all models live in the same schema it can't resolve the foreign keys.

@davidism
Copy link
Member

davidism commented Jan 26, 2019

Does this work in plain SQLAlchemy?

According to https://stackoverflow.com/a/47465718/400617 you must reference the other schema in the ForeignKey, even if the models belong to the same schema.

@rsyring rsyring modified the milestones: 2.x, 3.x Mar 9, 2019
@davidism
Copy link
Member

Closing, I'm assuming it was solved by specifying the schema in the foreign key.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Dec 5, 2020
@davidism davidism removed this from the 3.x milestone Sep 18, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

3 participants