From 5aa329f6489ccbb0c4d21781839f3ccd7f4f52e6 Mon Sep 17 00:00:00 2001 From: David Lord Date: Mon, 2 Oct 2017 12:04:43 -0700 Subject: [PATCH] model uses existing table by name fixes #550 --- CHANGES | 12 ++++++++++++ flask_sqlalchemy/model.py | 6 ++++++ tests/test_table_name.py | 12 ++++++++++++ 3 files changed, 30 insertions(+) diff --git a/CHANGES b/CHANGES index 147bdbaf..05367ee5 100644 --- a/CHANGES +++ b/CHANGES @@ -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 ------------- diff --git a/flask_sqlalchemy/model.py b/flask_sqlalchemy/model.py index 5e5ae797..b6452801 100644 --- a/flask_sqlalchemy/model.py +++ b/flask_sqlalchemy/model.py @@ -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 @@ -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) diff --git a/tests/test_table_name.py b/tests/test_table_name.py index 8a7d011e..6d54a7cd 100644 --- a/tests/test_table_name.py +++ b/tests/test_table_name.py @@ -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