Skip to content

Commit eb7b00f

Browse files
committed
Bring up URI check for sqlite engine
Includes a test to check that a database file is not created when using sqlite URI for in memory.
1 parent 42a36a3 commit eb7b00f

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

src/flask_sqlalchemy/extension.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -607,22 +607,22 @@ def _apply_driver_defaults(self, options: dict[str, t.Any], app: Flask) -> None:
607607
url = sa.engine.make_url(options["url"])
608608

609609
if url.drivername in {"sqlite", "sqlite+pysqlite"}:
610-
if url.database is None or url.database in {"", ":memory:"}:
610+
# the url might look like sqlite:///file:path?uri=true
611+
is_uri = url.query.get("uri", False)
612+
613+
if is_uri and url.database:
614+
db_str: t.Optional[str] = url.database[5:]
615+
else:
616+
db_str = url.database
617+
618+
if db_str is None or db_str in {"", ":memory:"}:
611619
options["poolclass"] = sa.pool.StaticPool
612620

613621
if "connect_args" not in options:
614622
options["connect_args"] = {}
615623

616624
options["connect_args"]["check_same_thread"] = False
617625
else:
618-
# the url might look like sqlite:///file:path?uri=true
619-
is_uri = url.query.get("uri", False)
620-
621-
if is_uri:
622-
db_str = url.database[5:]
623-
else:
624-
db_str = url.database
625-
626626
if not os.path.isabs(db_str):
627627
os.makedirs(app.instance_path, exist_ok=True)
628628
db_str = os.path.join(app.instance_path, db_str)

tests/test_engine.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,16 @@ def test_sqlite_driver_level_uri(app: Flask, model_class: t.Any) -> None:
110110
assert os.path.exists(db_path[5:])
111111

112112

113+
@pytest.mark.usefixtures("app_ctx")
114+
def test_sqlite_driver_level_uri_in_memory(app: Flask, model_class: t.Any) -> None:
115+
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///file::memory:?uri=true"
116+
db = SQLAlchemy(app, model_class=model_class)
117+
db.create_all()
118+
db_path = db.engine.url.database
119+
assert db_path is not None
120+
assert not os.path.exists(db_path[5:])
121+
122+
113123
@unittest.mock.patch.object(SQLAlchemy, "_make_engine", autospec=True)
114124
def test_sqlite_memory_defaults(
115125
make_engine: unittest.mock.Mock, app: Flask, model_class: t.Any

0 commit comments

Comments
 (0)