Skip to content
This repository was archived by the owner on Mar 16, 2026. It is now read-only.

Commit 3f3ab72

Browse files
committed
adds provision.py as part of experimenting on tests
1 parent 724983a commit 3f3ab72

File tree

1 file changed

+201
-0
lines changed

1 file changed

+201
-0
lines changed
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
2+
# dialects/sqlite/provision.py
3+
# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
4+
# <see AUTHORS file>
5+
#
6+
# This module is part of SQLAlchemy and is released under
7+
# the MIT License: https://www.opensource.org/licenses/mit-license.php
8+
# mypy: ignore-errors
9+
10+
import os
11+
import re
12+
13+
from ... import exc
14+
from ...engine import url as sa_url
15+
from ...testing.provision import create_db
16+
from ...testing.provision import drop_db
17+
from ...testing.provision import follower_url_from_main
18+
from ...testing.provision import generate_driver_url
19+
from ...testing.provision import log
20+
from ...testing.provision import post_configure_engine
21+
from ...testing.provision import run_reap_dbs
22+
from ...testing.provision import stop_test_class_outside_fixtures
23+
from ...testing.provision import temp_table_keyword_args
24+
from ...testing.provision import upsert
25+
26+
27+
28+
29+
# TODO: I can't get this to build dynamically with pytest-xdist procs
30+
_drivernames = {
31+
"pysqlite",
32+
"aiosqlite",
33+
"pysqlcipher",
34+
"pysqlite_numeric",
35+
"pysqlite_dollar",
36+
}
37+
38+
39+
def _format_url(url, driver, ident):
40+
"""given a sqlite url + desired driver + ident, make a canonical
41+
URL out of it
42+
43+
"""
44+
url = sa_url.make_url(url)
45+
46+
if driver is None:
47+
driver = url.get_driver_name()
48+
49+
filename = url.database
50+
51+
needs_enc = driver == "pysqlcipher"
52+
name_token = None
53+
54+
if filename and filename != ":memory:":
55+
assert "test_schema" not in filename
56+
tokens = re.split(r"[_\.]", filename)
57+
58+
new_filename = f"{driver}"
59+
60+
for token in tokens:
61+
if token in _drivernames:
62+
if driver is None:
63+
driver = token
64+
continue
65+
elif token in ("db", "enc"):
66+
continue
67+
elif name_token is None:
68+
name_token = token.strip("_")
69+
70+
assert name_token, f"sqlite filename has no name token: {url.database}"
71+
72+
new_filename = f"{name_token}_{driver}"
73+
if ident:
74+
new_filename += f"_{ident}"
75+
new_filename += ".db"
76+
if needs_enc:
77+
new_filename += ".enc"
78+
url = url.set(database=new_filename)
79+
80+
if needs_enc:
81+
url = url.set(password="test")
82+
83+
url = url.set(drivername="sqlite+%s" % (driver,))
84+
85+
return url
86+
87+
88+
@generate_driver_url.for_db("sqlite")
89+
def generate_driver_url(url, driver, query_str):
90+
url = _format_url(url, driver, None)
91+
92+
try:
93+
url.get_dialect()
94+
except exc.NoSuchModuleError:
95+
return None
96+
else:
97+
return url
98+
99+
100+
@follower_url_from_main.for_db("sqlite")
101+
def _sqlite_follower_url_from_main(url, ident):
102+
return _format_url(url, None, ident)
103+
104+
105+
@post_configure_engine.for_db("sqlite")
106+
def _sqlite_post_configure_engine(url, engine, follower_ident):
107+
from sqlalchemy import event
108+
109+
if follower_ident:
110+
attach_path = f"{follower_ident}_{engine.driver}_test_schema.db"
111+
else:
112+
attach_path = f"{engine.driver}_test_schema.db"
113+
114+
@event.listens_for(engine, "connect")
115+
def connect(dbapi_connection, connection_record):
116+
# use file DBs in all cases, memory acts kind of strangely
117+
# as an attached
118+
119+
# NOTE! this has to be done *per connection*. New sqlite connection,
120+
# as we get with say, QueuePool, the attaches are gone.
121+
# so schemes to delete those attached files have to be done at the
122+
# filesystem level and not rely upon what attachments are in a
123+
# particular SQLite connection
124+
dbapi_connection.execute(
125+
f'ATTACH DATABASE "{attach_path}" AS test_schema'
126+
)
127+
128+
@event.listens_for(engine, "engine_disposed")
129+
def dispose(engine):
130+
"""most databases should be dropped using
131+
stop_test_class_outside_fixtures
132+
133+
however a few tests like AttachedDBTest might not get triggered on
134+
that main hook
135+
136+
"""
137+
138+
if os.path.exists(attach_path):
139+
os.remove(attach_path)
140+
141+
filename = engine.url.database
142+
143+
if filename and filename != ":memory:" and os.path.exists(filename):
144+
os.remove(filename)
145+
146+
147+
@create_db.for_db("sqlite")
148+
def _sqlite_create_db(cfg, eng, ident):
149+
pass
150+
151+
152+
@drop_db.for_db("sqlite")
153+
def _sqlite_drop_db(cfg, eng, ident):
154+
_drop_dbs_w_ident(eng.url.database, eng.driver, ident)
155+
156+
157+
def _drop_dbs_w_ident(databasename, driver, ident):
158+
for path in os.listdir("."):
159+
fname, ext = os.path.split(path)
160+
if ident in fname and ext in [".db", ".db.enc"]:
161+
log.info("deleting SQLite database file: %s", path)
162+
os.remove(path)
163+
164+
165+
@stop_test_class_outside_fixtures.for_db("sqlite")
166+
def stop_test_class_outside_fixtures(config, db, cls):
167+
db.dispose()
168+
169+
170+
@temp_table_keyword_args.for_db("sqlite")
171+
def _sqlite_temp_table_keyword_args(cfg, eng):
172+
return {"prefixes": ["TEMPORARY"]}
173+
174+
175+
@run_reap_dbs.for_db("sqlite")
176+
def _reap_sqlite_dbs(url, idents):
177+
log.info("db reaper connecting to %r", url)
178+
log.info("identifiers in file: %s", ", ".join(idents))
179+
url = sa_url.make_url(url)
180+
for ident in idents:
181+
for drivername in _drivernames:
182+
_drop_dbs_w_ident(url.database, drivername, ident)
183+
184+
185+
@upsert.for_db("sqlite")
186+
def _upsert(
187+
cfg, table, returning, *, set_lambda=None, sort_by_parameter_order=False
188+
):
189+
from sqlalchemy.dialects.sqlite import insert
190+
191+
stmt = insert(table)
192+
193+
if set_lambda:
194+
stmt = stmt.on_conflict_do_update(set_=set_lambda(stmt.excluded))
195+
else:
196+
stmt = stmt.on_conflict_do_nothing()
197+
198+
stmt = stmt.returning(
199+
*returning, sort_by_parameter_order=sort_by_parameter_order
200+
)
201+
return stmt

0 commit comments

Comments
 (0)