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

Bring up URI check for sqlite engine #1315

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 9 additions & 9 deletions src/flask_sqlalchemy/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,22 +609,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