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

model uses existing table by name #551

Merged
merged 1 commit into from
Oct 2, 2017
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
12 changes: 12 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ Changelog
=========


Version 2.3.1
-------------

In development

- If a model has a table name that matches an existing table in the metadata,
use that table. Fixes a regression where reflected tables were not picked up
by models. (`#551`_)

.. _#551: https://github.com/mitsuhiko/flask-sqlalchemy/pull/551


Version 2.3.0
-------------

Expand Down
6 changes: 6 additions & 0 deletions flask_sqlalchemy/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sqlalchemy as sa
from sqlalchemy import inspect
from sqlalchemy.ext.declarative import DeclarativeMeta, declared_attr
from sqlalchemy.schema import _get_table_key

from ._compat import to_str

Expand Down Expand Up @@ -72,6 +73,11 @@ def __table_cls__(cls, *args, **kwargs):
If no primary key is found, that indicates single-table inheritance,
so no table will be created and ``__tablename__`` will be unset.
"""
key = _get_table_key(args[0], kwargs.get('schema'))

if key in cls.metadata.tables:
return sa.Table(*args, **kwargs)

for arg in args:
if (
(isinstance(arg, sa.Column) and arg.primary_key)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_table_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,15 @@ def floats(self):
assert False

assert ns.accessed


def test_metadata_has_table(db):
user = db.Table(
'user',
db.Column('id', db.Integer, primary_key=True),
)

class User(db.Model):
pass

assert User.__table__ is user