Skip to content

Commit

Permalink
Bring up URI check for sqlite engine
Browse files Browse the repository at this point in the history
Includes a test to check that a database file is not created when using
sqlite URI for in memory.
  • Loading branch information
Sparrow0hawk committed Feb 19, 2024
1 parent 42a36a3 commit eb7b00f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
18 changes: 9 additions & 9 deletions src/flask_sqlalchemy/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,22 +607,22 @@ def _apply_driver_defaults(self, options: dict[str, t.Any], app: Flask) -> None:
url = sa.engine.make_url(options["url"])

if url.drivername in {"sqlite", "sqlite+pysqlite"}:
if url.database is None or url.database in {"", ":memory:"}:
# the url might look like sqlite:///file:path?uri=true
is_uri = url.query.get("uri", False)

if is_uri and url.database:
db_str: t.Optional[str] = url.database[5:]
else:
db_str = url.database

if db_str is None or db_str in {"", ":memory:"}:
options["poolclass"] = sa.pool.StaticPool

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

options["connect_args"]["check_same_thread"] = False
else:
# the url might look like sqlite:///file:path?uri=true
is_uri = url.query.get("uri", False)

if is_uri:
db_str = url.database[5:]
else:
db_str = url.database

if not os.path.isabs(db_str):
os.makedirs(app.instance_path, exist_ok=True)
db_str = os.path.join(app.instance_path, db_str)
Expand Down
10 changes: 10 additions & 0 deletions tests/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ def test_sqlite_driver_level_uri(app: Flask, model_class: t.Any) -> None:
assert os.path.exists(db_path[5:])


@pytest.mark.usefixtures("app_ctx")
def test_sqlite_driver_level_uri_in_memory(app: Flask, model_class: t.Any) -> None:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///file::memory:?uri=true"
db = SQLAlchemy(app, model_class=model_class)
db.create_all()
db_path = db.engine.url.database
assert db_path is not None
assert not os.path.exists(db_path[5:])


@unittest.mock.patch.object(SQLAlchemy, "_make_engine", autospec=True)
def test_sqlite_memory_defaults(
make_engine: unittest.mock.Mock, app: Flask, model_class: t.Any
Expand Down

0 comments on commit eb7b00f

Please sign in to comment.