Skip to content

Commit cfb61e1

Browse files
authored
show errors on multiple instances or missing init (#1151)
2 parents 2c2abaa + 182ba62 commit cfb61e1

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

CHANGES.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ Version 3.0.3
33

44
Unreleased
55

6+
- Show helpful errors when mistakenly using multiple ``SQLAlchemy`` instances for the
7+
same app, or without calling ``init_app``. :pr:`1151`
8+
69

710
Version 3.0.2
811
-------------

src/flask_sqlalchemy/extension.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,12 @@ def init_app(self, app: Flask) -> None:
249249
250250
:param app: The Flask application to initialize.
251251
"""
252+
if "sqlalchemy" in app.extensions:
253+
raise RuntimeError(
254+
"A 'SQLAlchemy' instance has already been registered on this Flask app."
255+
" Import and use that instance instead."
256+
)
257+
252258
app.extensions["sqlalchemy"] = self
253259

254260
if self._add_models_to_shell:
@@ -626,6 +632,14 @@ def engines(self) -> t.Mapping[str | None, sa.engine.Engine]:
626632
.. versionadded:: 3.0
627633
"""
628634
app = current_app._get_current_object() # type: ignore[attr-defined]
635+
636+
if app not in self._app_engines:
637+
raise RuntimeError(
638+
"The current Flask app is not registered with this 'SQLAlchemy'"
639+
" instance. Did you forget to call 'init_app', or did you create"
640+
" multiple 'SQLAlchemy' instances?"
641+
)
642+
629643
return self._app_engines[app]
630644

631645
@property

tests/test_metadata.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ def test_reflect(app: Flask) -> None:
116116
db.Table("post", sa.Column("id", sa.Integer, primary_key=True), bind_key="post")
117117
db.create_all()
118118

119+
del app.extensions["sqlalchemy"]
119120
db = SQLAlchemy(app)
120121
assert not db.metadata.tables
121122
db.reflect()

0 commit comments

Comments
 (0)